From 952d72345c172ed6118c62926bd29b0b5165ff12 Mon Sep 17 00:00:00 2001 From: Ink-dark Date: Sat, 31 Oct 2026 15:14:29 +0800 Subject: [PATCH 01/14] [css] parse float/clear properties (CSS 2.1 section 9.5), non-inherited, computed fields (0.1.15) --- crates/nexty-css/Cargo.toml | 2 +- crates/nexty-css/src/cascade.rs | 47 ++++++++++-- crates/nexty-css/src/lib.rs | 12 +-- crates/nexty-css/src/value.rs | 106 ++++++++++++++++++++++++++- docs/plans/2026-10-31-round-float.md | 74 +++++++++++++++++++ 5 files changed, 223 insertions(+), 18 deletions(-) create mode 100644 docs/plans/2026-10-31-round-float.md diff --git a/crates/nexty-css/Cargo.toml b/crates/nexty-css/Cargo.toml index 3d30f8f..469db93 100644 --- a/crates/nexty-css/Cargo.toml +++ b/crates/nexty-css/Cargo.toml @@ -1,7 +1,7 @@ [package] name = "nexty-css" description = "Nexty CSS 层:解析与选择器匹配复用 cssparser/selectors,cascade 自研" -version = "0.1.14" +version = "0.1.15" edition.workspace = true license.workspace = true repository.workspace = true diff --git a/crates/nexty-css/src/cascade.rs b/crates/nexty-css/src/cascade.rs index b08ed94..483ba6e 100644 --- a/crates/nexty-css/src/cascade.rs +++ b/crates/nexty-css/src/cascade.rs @@ -18,12 +18,12 @@ use crate::parser::{Declaration, MediaViewport, StyleRule, Stylesheet, parse_inl use crate::selector::{NextySelector, atom_str, match_element_selectors}; use crate::value::{ AbsoluteSize, AlignItemsValue, AlignSelfValue, BorderColorValue, BorderStyle, BorderWidthValue, - BoxSizingValue, CssWideKeyword, DeclaredValue, DisplayValue, FlexDirectionValue, FlexWrapValue, - FontFamilyValue, FontSizeValue, FontStyleValue, FontWeightValue, GapValue, GridAutoFlowValue, - GridTrackList, InsetValue, JustifyContentValue, LineHeightValue, MAX_CSS_LENGTH, MarginValue, - OverflowValue, OverflowWrapValue, PaddingValue, PositionValue, PropertyId, PropertyValue, Rgba, - SizeValue, SpacingValue, TabSizeValue, TextAlignValue, TextIndentValue, ViewportUnit, - WhiteSpaceValue, WordBreakValue, + BoxSizingValue, ClearValue, CssWideKeyword, DeclaredValue, DisplayValue, FlexDirectionValue, + FlexWrapValue, FloatValue, FontFamilyValue, FontSizeValue, FontStyleValue, FontWeightValue, + GapValue, GridAutoFlowValue, GridTrackList, InsetValue, JustifyContentValue, LineHeightValue, + MAX_CSS_LENGTH, MarginValue, OverflowValue, OverflowWrapValue, PaddingValue, PositionValue, + PropertyId, PropertyValue, Rgba, SizeValue, SpacingValue, TabSizeValue, TextAlignValue, + TextIndentValue, ViewportUnit, WhiteSpaceValue, WordBreakValue, }; /// 本层 UA 的 medium 字号基准(CSS Fonts 4 §2.5:initial 值由 UA 决定, @@ -88,6 +88,10 @@ pub struct ComputedStyle { pub flex_basis: SizeValue, /// `position`(CSS Position 3 §2,initial static)。 pub position: PositionValue, + /// `float`(CSS 2.1 §9.5.1,initial none;不继承)。 + pub float: FloatValue, + /// `clear`(CSS 2.1 §9.5.2,initial none;不继承)。 + pub clear: ClearValue, /// 四边 inset(top / right / bottom / left;百分比与 auto 由 layout 解析)。 pub inset: Edges, /// `flex-direction`(CSS Flexbox §8.3.1,initial row)。 @@ -186,6 +190,8 @@ impl ComputedStyle { flex_grow: 0.0, flex_basis: SizeValue::Auto, position: PositionValue::Static, + float: FloatValue::None, + clear: ClearValue::None, inset: Edges::splat(InsetValue::Auto), flex_direction: FlexDirectionValue::Row, flex_wrap: FlexWrapValue::NoWrap, @@ -236,7 +242,7 @@ impl PropertyId { /// 顺序承载计算依赖:`FontSize` 先于 `LineHeight`(百分比按自身字号折算)、 /// `Color` 先于 border 颜色(currentcolor)、border style 先于 width /// (none/hidden 时宽度归零)。 -const PROPERTY_ORDER: [PropertyId; 62] = [ +const PROPERTY_ORDER: [PropertyId; 64] = [ PropertyId::Display, PropertyId::Color, PropertyId::BackgroundColor, @@ -264,6 +270,8 @@ const PROPERTY_ORDER: [PropertyId; 62] = [ PropertyId::FlexGrow, PropertyId::FlexBasis, PropertyId::Position, + PropertyId::Float, + PropertyId::Clear, PropertyId::Top, PropertyId::Right, PropertyId::Bottom, @@ -1102,6 +1110,12 @@ fn resolve_all( (PropertyId::Position, Decision::Use(PropertyValue::Position(value))) => { style.position = *value; } + (PropertyId::Float, Decision::Use(PropertyValue::Float(value))) => { + style.float = *value; + } + (PropertyId::Clear, Decision::Use(PropertyValue::Clear(value))) => { + style.clear = *value; + } (PropertyId::Top, Decision::Use(PropertyValue::Inset(value))) => { style.inset.top = resolve_inset(*value, viewport); } @@ -1241,6 +1255,8 @@ fn resolve_all( PropertyId::FlexGrow => style.flex_grow = source.flex_grow, PropertyId::FlexBasis => style.flex_basis = source.flex_basis, PropertyId::Position => style.position = source.position, + PropertyId::Float => style.float = source.float, + PropertyId::Clear => style.clear = source.clear, PropertyId::Top => style.inset.top = source.inset.top, PropertyId::Right => style.inset.right = source.inset.right, PropertyId::Bottom => style.inset.bottom = source.inset.bottom, @@ -2008,6 +2024,23 @@ mod tests { tracks: vec![GridTrack::Auto] } ); + assert_eq!(style.float, FloatValue::None); + assert_eq!(style.clear, ClearValue::None); + } + + /// `float` / `clear` 解析进 computed style 且**不**继承(CSS 2.1 §9.5)。 + #[test] + fn float_clear_properties_do_not_inherit() { + let document = build_document("

x

"); + let parsed = Stylesheet::parse(""); + let div = find_first_by_name(&document, "div").unwrap(); + let p = find_first_by_name(&document, "p").unwrap(); + let div_style = cascade(&document, div, &[&parsed], None, None); + assert_eq!(div_style.float, FloatValue::Left); + assert_eq!(div_style.clear, ClearValue::Both); + let p_style = cascade(&document, p, &[&parsed], None, None); + assert_eq!(p_style.float, FloatValue::None); + assert_eq!(p_style.clear, ClearValue::None); } /// `white-space` / `overflow-wrap` / `word-break` 均继承,initial 为 `normal`。 diff --git a/crates/nexty-css/src/lib.rs b/crates/nexty-css/src/lib.rs index 8393ef8..91412b1 100644 --- a/crates/nexty-css/src/lib.rs +++ b/crates/nexty-css/src/lib.rs @@ -43,10 +43,10 @@ pub use ua::html_ua_stylesheet; #[cfg(feature = "values")] pub use value::{ AbsoluteSize, AlignItemsValue, AlignSelfValue, BorderColorValue, BorderStyle, BorderWidthValue, - BoxSizingValue, CssWideKeyword, DeclaredValue, DisplayValue, FlexDirectionValue, FlexWrapValue, - FontFamilyValue, FontSizeValue, FontStyleValue, FontWeightValue, GapValue, GridAutoFlowValue, - GridTrack, GridTrackList, InsetValue, JustifyContentValue, LineHeightValue, MAX_CSS_LENGTH, - MarginValue, OverflowValue, OverflowWrapValue, PaddingValue, PositionValue, PropertyId, - PropertyValue, Rgba, SizeValue, SpacingValue, TabSizeValue, TextAlignValue, TextIndentValue, - ViewportUnit, WhiteSpaceValue, WordBreakValue, + BoxSizingValue, ClearValue, CssWideKeyword, DeclaredValue, DisplayValue, FlexDirectionValue, + FlexWrapValue, FloatValue, FontFamilyValue, FontSizeValue, FontStyleValue, FontWeightValue, + GapValue, GridAutoFlowValue, GridTrack, GridTrackList, InsetValue, JustifyContentValue, + LineHeightValue, MAX_CSS_LENGTH, MarginValue, OverflowValue, OverflowWrapValue, PaddingValue, + PositionValue, PropertyId, PropertyValue, Rgba, SizeValue, SpacingValue, TabSizeValue, + TextAlignValue, TextIndentValue, ViewportUnit, WhiteSpaceValue, WordBreakValue, }; diff --git a/crates/nexty-css/src/value.rs b/crates/nexty-css/src/value.rs index d0d388c..31c4767 100644 --- a/crates/nexty-css/src/value.rs +++ b/crates/nexty-css/src/value.rs @@ -124,6 +124,10 @@ pub enum PropertyId { FlexBasis, /// `position`。 Position, + /// `float`。 + Float, + /// `clear`。 + Clear, /// `top`。 Top, /// `right`。 @@ -228,6 +232,8 @@ impl PropertyId { PropertyId::FlexGrow => "flex-grow", PropertyId::FlexBasis => "flex-basis", PropertyId::Position => "position", + PropertyId::Float => "float", + PropertyId::Clear => "clear", PropertyId::Top => "top", PropertyId::Right => "right", PropertyId::Bottom => "bottom", @@ -270,7 +276,7 @@ impl PropertyId { /// (CSS Syntax:声明名匹配大小写不敏感)。 #[must_use] pub fn from_name(name: &str) -> Option { - const ALL: [PropertyId; 62] = [ + const ALL: [PropertyId; 64] = [ PropertyId::Display, PropertyId::Color, PropertyId::BackgroundColor, @@ -298,6 +304,8 @@ impl PropertyId { PropertyId::FlexGrow, PropertyId::FlexBasis, PropertyId::Position, + PropertyId::Float, + PropertyId::Clear, PropertyId::Top, PropertyId::Right, PropertyId::Bottom, @@ -413,6 +421,10 @@ pub enum PropertyValue { FlexBasis(SizeValue), /// `position` 关键字。 Position(PositionValue), + /// `float` 关键字。 + Float(FloatValue), + /// `clear` 关键字。 + Clear(ClearValue), /// `top` / `right` / `bottom` / `left` 值。 Inset(InsetValue), /// `flex-direction` 关键字。 @@ -810,6 +822,34 @@ pub enum PositionValue { Fixed, } +/// `float` 值 +/// ([CSS 2.1 §9.5.1](https://www.w3.org/TR/CSS21/visuren.html#float-position))。 +/// +/// 逻辑值 `inline-start` / `inline-end` 不做,记偏差(本层仅 LTR)。 +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +pub enum FloatValue { + /// `none`(initial):不浮动。 + None, + /// `left`:左浮动。 + Left, + /// `right`:右浮动。 + Right, +} + +/// `clear` 值 +/// ([CSS 2.1 §9.5.2](https://www.w3.org/TR/CSS21/visuren.html#flow-control))。 +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +pub enum ClearValue { + /// `none`(initial):允许两侧有浮动。 + None, + /// `left`:下移到左侧浮动之下。 + Left, + /// `right`:下移到右侧浮动之下。 + Right, + /// `both`:下移到任一侧浮动之下。 + Both, +} + /// `top` / `right` / `bottom` / `left` 值(inset) /// ([CSS Position 3 §3](https://drafts.csswg.org/css-position-3/#insets))。 #[derive(Debug, Clone, Copy, PartialEq)] @@ -1138,6 +1178,8 @@ fn parse_property_value(property: PropertyId, input: &mut Parser<'_>) -> Result< PropertyId::FlexGrow => parse_flex_grow(input).map(PropertyValue::FlexGrow), PropertyId::FlexBasis => parse_size(input).map(PropertyValue::FlexBasis), PropertyId::Position => parse_position(input).map(PropertyValue::Position), + PropertyId::Float => parse_float(input).map(PropertyValue::Float), + PropertyId::Clear => parse_clear(input).map(PropertyValue::Clear), PropertyId::Top | PropertyId::Right | PropertyId::Bottom | PropertyId::Left => { parse_inset(input).map(PropertyValue::Inset) } @@ -1396,7 +1438,39 @@ fn parse_position(input: &mut Parser<'_>) -> Result { } } -/// `top` / `right` / `bottom` / `left`: | | auto。 +/// `float`:none | left | right(ASCII case-insensitive,CSS 2.1 §9.5.1)。 +fn parse_float(input: &mut Parser<'_>) -> Result { + let Token::Ident(name) = input.next().map_err(|_| ())? else { + return Err(()); + }; + if name.eq_ignore_ascii_case("none") { + Ok(FloatValue::None) + } else if name.eq_ignore_ascii_case("left") { + Ok(FloatValue::Left) + } else if name.eq_ignore_ascii_case("right") { + Ok(FloatValue::Right) + } else { + Err(()) + } +} + +/// `clear`:none | left | right | both(ASCII case-insensitive,CSS 2.1 §9.5.2)。 +fn parse_clear(input: &mut Parser<'_>) -> Result { + let Token::Ident(name) = input.next().map_err(|_| ())? else { + return Err(()); + }; + if name.eq_ignore_ascii_case("none") { + Ok(ClearValue::None) + } else if name.eq_ignore_ascii_case("left") { + Ok(ClearValue::Left) + } else if name.eq_ignore_ascii_case("right") { + Ok(ClearValue::Right) + } else if name.eq_ignore_ascii_case("both") { + Ok(ClearValue::Both) + } else { + Err(()) + } +} fn parse_inset(input: &mut Parser<'_>) -> Result { match input.next().map_err(|_| ())? { Token::Ident(name) if name.eq_ignore_ascii_case("auto") => Ok(InsetValue::Auto), @@ -2729,8 +2803,8 @@ mod tests { #[test] fn position_inset_flex_grid_properties_parse() { use PropertyValue::{ - AlignItems, AlignSelf, FlexDirection, FlexShrink, FlexWrap, Gap, GridAutoFlow, - GridTrack as GridTrackValue, Inset, JustifyContent, Position, + AlignItems, AlignSelf, Clear, FlexDirection, FlexShrink, FlexWrap, Float, Gap, + GridAutoFlow, GridTrack as GridTrackValue, Inset, JustifyContent, Position, }; // position assert_eq!( @@ -2743,6 +2817,30 @@ mod tests { ); parse_err(PropertyId::Position, "sticky"); + // float / clear(CSS 2.1 §9.5.1/§9.5.2) + assert_eq!( + parse_one(PropertyId::Float, "left"), + Float(FloatValue::Left) + ); + assert_eq!( + parse_one(PropertyId::Float, "RIGHT"), + Float(FloatValue::Right) + ); + assert_eq!( + parse_one(PropertyId::Float, "none"), + Float(FloatValue::None) + ); + parse_err(PropertyId::Float, "inline-start"); + assert_eq!( + parse_one(PropertyId::Clear, "both"), + Clear(ClearValue::Both) + ); + assert_eq!( + parse_one(PropertyId::Clear, "Left"), + Clear(ClearValue::Left) + ); + parse_err(PropertyId::Clear, "inline-end"); + // inset(四边 longhand 共用 InsetValue) assert_eq!( parse_one(PropertyId::Top, "10px"), diff --git a/docs/plans/2026-10-31-round-float.md b/docs/plans/2026-10-31-round-float.md new file mode 100644 index 0000000..76f3210 --- /dev/null +++ b/docs/plans/2026-10-31-round-float.md @@ -0,0 +1,74 @@ +# goal.md — 本轮任务:float 布局轮(taffy float_layout 接线 + 行盒避让验证) + +日期:2026-10-31。前置:性能轮已完成(2026-10-25,css 0.1.14 / text 0.1.8 / +paint 0.1.7 / layout 0.1.27 / chrome 0.1.25),归档于 +[docs/plans/2026-10-25-round-perf.md](docs/plans/2026-10-25-round-perf.md)。 +本轮是 roadmap 排定的下一项(用户决策:paint 扩展先放一放,优先堆基础功能; +float 优先于 table / position:fixed)。 + +**关键侦察结论(动手前确认)**:taffy 0.14 自带 `float_layout` cargo feature +——`Style.float` / `Style.clear` 字段 + block 算法内的完整浮动实现 +(`compute/float.rs`:`FloatContext`、BFC 槽位、float 内容高度贡献、clear +与 margin 折叠交互、内在宽度计算)。本轮**不自研浮动放置**,按「不造轮子」 +规则以接线为主: + +1. nexty-css 解析 `float` / `clear` → `ComputedStyle` 字段; +2. nexty-layout 启用 taffy `float_layout`,`style_map` 映射两属性; +3. 验证自研行盒(run 叶 measure)在浮动旁收缩可用宽后正确环绕; +4. 片段树 / paint / hit-test 路径验证浮动盒自然流出。 + +## 任务清单与退出条件 + +### T1 nexty-css:`float` / `clear` 属性解析(css 0.1.14 → 0.1.15) +- `values` 模块:`float: none | left | right`、`clear: none | left | right | + both`(CSS 2.1 §9.5.1/§9.5.2 取值;`inline-start/end` 等逻辑值不做,记偏差)。 +- `ComputedStyle` 增字段;初始值 none;继承性:两者均不继承。 +- **退出条件**:属性解析单测(合法/非法/继承/级联覆盖);`cargo check -p + nexty-css` 零 warning;不改行为时版本 bump 记入 commit。 + +### T2 nexty-layout:启用 taffy `float_layout` + 样式映射(layout 0.1.27 → 0.1.28) +- `Cargo.toml`:taffy 依赖追加 features `float_layout`(taffy 常驻原则不变, + feature 是能力开关)。 +- `style_map`:`ComputedStyle.float/clear → taffy Style.float/clear`; + **blockify 修正**——`position: absolute/fixed` 与 flex/grid item 上的 + `float` 计算为 none(CSS 2.1 §9.7 / CSS Flexbox §4),映射层拦截。 +- `tree_build`:浮动盒作为普通 taffy 子节点建树(float 是块级化的); + 验证 run 叶 measure 在 taffy 浮动算法下收到的 `AvailableSpace` 已扣除 + 浮动占位(若 taffy 只对块级子盒收缩、不给 run 叶收缩宽度,需在 + `block` 装配或 measure 侧适配——先写探针测试确定行为再动手)。 +- **退出条件**:探针测试钉住——①单左浮动 + 文本环绕;②右浮动; + ③`clear: both` 下方下移;④浮动包含(父块高度含浮动,BFC 情形 + `overflow: hidden` 与普通块两种);⑤双浮动并排。行盒字形坐标相对 + 浮动避让后的可用区正确。逐 feature `--no-default-features` 编译零 warning。 + +### T3 nexty-layout:片段树 / 选区路径验证(并入 0.1.28) +- 浮动盒经 `assemble_element` 自然进入片段树(taffy 子节点递归);验证 + `border_box` 相对包含块内容盒的坐标约定成立(浮动 x 位置非 0 时)。 +- 选区/命中:浮动盒内文本参与 `TextMap`(按行盒几何,预期自动成立), + 探针测试钉住「命中浮动盒内文本返回该盒」。 +- **退出条件**:上述测试绿;既有测试(含 UAX#14 conformance、CSS Text 轮 + 测试)不改仍绿。 + +### T4 nexty-chrome:实机验证(chrome 不改则不 bump) +- `.workbuddy/t3-test` 加一个图文环绕测试页(左图环绕段落 + 右浮动侧栏 + + clear 分节)。 +- **退出条件**:实机冒烟——环绕文本不与浮动重叠、滚动不重排不闪烁、 + 浮动盒内文本可选可复制、链接点击命中浮动盒正常。 + +### T5 收尾:文档与登记 +- AGENTS.md:layout 状态段补 float 落地说明 + feature 映射表(float 能力 + 挂在既有 `block` feature 下,不新增 feature——taffy float 是 block 算法 + 的一部分);偏差清单登记(逻辑值 `inline-start/end`、float 跨 BFC 边缘 + 情形按 taffy 实现为准)。 +- `docs/decisions/` 若涉及新决策(直接采用 taffy float 而非自研)补记一条 + 短 ADR 或在选型 ADR 修正记录追加一段。 +- **退出条件**:`cargo check/test/clippy/fmt --workspace` 全绿;`cargo deny + check` 通过(未引入新依赖,预期无变化);逐任务独立 commit。 + +## 明确不做(偏差清单) +- `float: inline-start / inline-end`、`clear: inline-start/inline-end`(逻辑值)。 +- shape-outside、`position: fixed` 视口锚定、「最近定位祖先」搜索(独立轮)。 +- table(独立整轮)、paint 扩展(下一轮候选)。 + +## 整轮退出条件 +T1–T5 退出条件全部满足;`goal.md` 归档 + push;等用户验收。 From 98213855e9572226a08e70c4205cd8b1cc20a701 Mon Sep 17 00:00:00 2001 From: Ink-dark Date: Sat, 31 Oct 2026 15:54:38 +0800 Subject: [PATCH 02/14] [layout] float layout: enable taffy float_layout, map float/clear, wrap line boxes against placed floats (0.1.28) --- Cargo.lock | 2 +- crates/nexty-layout/Cargo.toml | 7 +- crates/nexty-layout/src/block.rs | 125 +++++++++++++--- crates/nexty-layout/src/inline/mod.rs | 94 ++++++++++-- crates/nexty-layout/src/style_map.rs | 32 +++- crates/nexty-layout/src/tree_build.rs | 91 ++++++++---- crates/nexty-layout/tests/layout.rs | 205 ++++++++++++++++++++++++++ 7 files changed, 487 insertions(+), 69 deletions(-) diff --git a/Cargo.lock b/Cargo.lock index 4c09830..3fab3fb 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -1706,7 +1706,7 @@ dependencies = [ [[package]] name = "nexty-css" -version = "0.1.14" +version = "0.1.15" dependencies = [ "cssparser", "nexty-dom", diff --git a/crates/nexty-layout/Cargo.toml b/crates/nexty-layout/Cargo.toml index 0c2c14d..ee7bf5e 100644 --- a/crates/nexty-layout/Cargo.toml +++ b/crates/nexty-layout/Cargo.toml @@ -1,7 +1,7 @@ [package] name = "nexty-layout" description = "Nexty 自研盒级布局" -version = "0.1.27" +version = "0.1.28" edition.workspace = true license.workspace = true repository.workspace = true @@ -44,9 +44,10 @@ selection = ["block"] nexty-dom = { path = "../nexty-dom", version = "0.1.0" } nexty-css = { path = "../nexty-css", version = "0.1.0" } nexty-text = { path = "../nexty-text", version = "0.1.0" } -# taffy 接管盒级几何(block/flex/grid/absolute);inline 与 table 仍自研。 +# taffy 接管盒级几何(block/flex/grid/absolute + float);inline 与 table 仍自研。 # 选型与边界见 docs/decisions/2026-10-01-crate-selection.md 修正记录。 -taffy = "0.14" +# float_layout:taffy block 算法内的浮动支持(FloatContext / clear / BFC 高度贡献)。 +taffy = { version = "0.14", features = ["float_layout"] } # 断行是布局层职责(text 层保持纯整形):UAX#29 扩展字形簇边界 # (cluster 不得跨字形簇切分;UAX#14 规则自研,见 src/inline.rs)。 unicode-segmentation = "1.13.3" diff --git a/crates/nexty-layout/src/block.rs b/crates/nexty-layout/src/block.rs index dadba4c..38c78d1 100644 --- a/crates/nexty-layout/src/block.rs +++ b/crates/nexty-layout/src/block.rs @@ -76,14 +76,19 @@ pub(crate) fn layout_root(ctx: &Context<'_>, root: NodeId, viewport_width: f32) return empty_fragment(root, &style); }; - compute_tree( - &mut boxes, - root_taffy, - TaffySize { - width: AvailableSpace::Definite(viewport_width), - height: AvailableSpace::MaxContent, - }, - ); + let available = TaffySize { + width: AvailableSpace::Definite(viewport_width), + height: AvailableSpace::MaxContent, + }; + compute_tree(&mut boxes, root_taffy, available); + // 浮动环绕修正:taffy 的 float_layout 不收缩 measure 叶的可用宽(叶无子 + // 内容可下钻),文本会与浮动重叠。首轮解算后浮动已就位,按真实浮动矩形 + // 重排 run 叶行盒;行数变化时把修正高度回写 taffy 再解算一轮,使容器 + // 高度、clear 与后续兄弟位置按实际行数收敛(浮动自身尺寸与文本无关, + // 第二轮浮动位置不变,一次迭代即固定点)。 + if apply_float_wrapping(&mut boxes, root_taffy) { + compute_tree(&mut boxes, root_taffy, available); + } let (margin_left, margin_top) = if boxes.root_is_element_box { ( @@ -116,14 +121,15 @@ pub(crate) fn layout_atomic_subtree( let Some(taffy_root) = boxes.root else { return empty_fragment(node, style); }; - compute_tree( - &mut boxes, - taffy_root, - TaffySize { - width: available_width, - height: AvailableSpace::MaxContent, - }, - ); + let available = TaffySize { + width: available_width, + height: AvailableSpace::MaxContent, + }; + compute_tree(&mut boxes, taffy_root, available); + // 原子盒(inline-block 等)是独立 BFC:内部浮动同样需要环绕修正 + if apply_float_wrapping(&mut boxes, taffy_root) { + compute_tree(&mut boxes, taffy_root, available); + } let layout = *boxes.tree.layout(taffy_root).expect("atomic layout"); let mut fragment = assemble_element(&boxes, ctx, taffy_root, node, (0.0, 0.0)); fragment.border_box.width = layout.size.width; @@ -133,6 +139,88 @@ pub(crate) fn layout_atomic_subtree( fragment } +/// 浮动环绕修正 pass:为含浮动子盒的容器重排 run 叶行盒。 +/// +/// taffy 的 `float_layout` 完成浮动放置、块盒/BFC 避让、`clear` 与容器高度 +/// 贡献,但 measure 叶(run 叶)没有子内容可下钻,拿不到浮动区间——行盒不 +/// 收缩会与浮动重叠。这里按首轮解算的真实浮动矩形逐行收缩重排,并把修正 +/// 高度回写上层的叶样式(返回 `true` 表示需要再解算一轮)。 +/// +/// 只收容器直接子节点中**位于该 run 之前**的浮动(CSS 2.2 §9.5:浮动只影响 +/// 其后内容);嵌套 BFC 的浮动由各自的容器递归处理。 +fn apply_float_wrapping(boxes: &mut BoxTree<'_>, root: TaffyNode) -> bool { + let mut changed = false; + wrap_recursive(boxes, root, &mut changed); + changed +} + +fn wrap_recursive(boxes: &mut BoxTree<'_>, container: TaffyNode, changed: &mut bool) { + let children = boxes.tree.children(container).unwrap_or_default(); + if children.is_empty() { + return; + } + let container_layout = *boxes.tree.layout(container).expect("layout"); + let inset = content_inset(&container_layout); + // 容器内容盒坐标下的浮动矩形(taffy 的 location 相对父边框盒) + let floats: Vec<(usize, crate::inline::FloatRect)> = children + .iter() + .enumerate() + .filter_map(|(order, &child)| { + let style = boxes.tree.style(child).ok()?; + if style.float == taffy::Float::None { + return None; + } + let layout = boxes.tree.layout(child).ok()?; + Some(( + order, + crate::inline::FloatRect { + x: layout.location.x - inset.0, + y: layout.location.y - inset.1, + width: layout.size.width, + height: layout.size.height, + }, + )) + }) + .collect(); + if !floats.is_empty() { + for (order, &child) in children.iter().enumerate() { + let Some(run) = boxes.runs.get(&child) else { + continue; + }; + let layout = *boxes.tree.layout(child).expect("run layout"); + let run_x = layout.location.x - inset.0; + let run_y = layout.location.y - inset.1; + // 只取排在该 run 之前的浮动,换算到 run 内容盒坐标 + let run_floats: Vec = floats + .iter() + .filter(|(float_order, _)| *float_order < order) + .map(|(_, float)| crate::inline::FloatRect { + x: float.x - run_x, + y: float.y - run_y, + ..*float + }) + .collect(); + if run_floats.is_empty() { + continue; + } + let height = run.wrap_against(layout.size.width, &run_floats); + if (height - layout.size.height).abs() > 0.01 { + let mut style = boxes.tree.style(child).expect("run style").clone(); + style.size.height = taffy::style_helpers::length(height); + if boxes.tree.set_style(child, style).is_ok() { + *changed = true; + } + } + } + } + for child in children { + if boxes.runs.contains_key(&child) { + continue; + } + wrap_recursive(boxes, child, changed); + } +} + /// 对一棵盒树执行 taffy 布局(禁用取整,保持与旧自研一致的小数几何)。 fn compute_tree(boxes: &mut BoxTree<'_>, root: TaffyNode, available: TaffySize) { boxes.tree.disable_rounding(); @@ -200,7 +288,10 @@ fn assemble_element( child_layout.location.x - inset.0, child_layout.location.y - inset.1, ); - let run_lines = run.lines_at(child_layout.size.width, false); + // 浮动环绕修正过的行盒优先(装配是 wrapped 缓存的唯一消费者) + let run_lines = run + .wrapped_lines() + .unwrap_or_else(|| run.lines_at(child_layout.size.width, false)); if merge_lines { for line in run_lines { // text-align 在行盒并入容器时施加:整行相对内容盒平移 diff --git a/crates/nexty-layout/src/inline/mod.rs b/crates/nexty-layout/src/inline/mod.rs index 8560763..3300293 100644 --- a/crates/nexty-layout/src/inline/mod.rs +++ b/crates/nexty-layout/src/inline/mod.rs @@ -930,6 +930,51 @@ pub(crate) fn ensure_analysis( } } +/// 浮动盒的占用矩形(相对 run 叶内容盒坐标)。 +/// +/// 行盒按浮动收缩(CSS 2.2 §9.5):行顶落在浮动纵向范围内时,行盒左右 +/// 各被浮动占据的部分让出。矩形由布局层从 taffy 已放置的浮动盒换算而来。 +#[derive(Debug, Clone, Copy, PartialEq)] +pub(crate) struct FloatRect { + pub x: f32, + pub y: f32, + pub width: f32, + pub height: f32, +} + +/// 行顶 `y` 处的可用水平区间 `(left, right)`:空浮动表恒为 `(0, max_width)`。 +/// +/// 判定只看行顶(行高在断行期未知):行跨入更深浮动区间时整行按行顶宽 +/// 放置——记为偏差(规范要求按行内内容跨度的最窄可用区缩短)。左/右由 +/// 浮动盒中心在包含块左半/右半判定(LTR 单侧浮动)。 +fn wrap_bounds(floats: &[FloatRect], y: f32, max_width: f32) -> (f32, f32) { + let mut left = 0.0_f32; + let mut right = max_width; + for float in floats { + if y + 0.001 >= float.y && y < float.y + float.height { + if float.x + float.width / 2.0 <= max_width / 2.0 { + left = left.max(float.x + float.width); + } else { + right = right.min(float.x); + } + } + } + (left, right) +} + +/// 断行放置约束(宽度 / 语义 / 缩进 / 浮动区间)。 +pub(crate) struct LineConstraints<'a> { + /// 定宽断行宽(min-content 语义下为 0,max-content 下为 +inf)。 + pub max_width: f32, + /// 是否 min-content 语义(`overflow-wrap: break-word` 的紧急断点不参与)。 + pub min_content: bool, + /// 首行缩进(CSS Text 3 §4;测量路径与后续行由调用方保证传 0)。 + pub first_line_indent: f32, + /// 该 run 所在 BFC 的浮动占用矩形(空表 = 无浮动,行为零变化); + /// 每行按行顶 y 查可用区间收缩(见 [`wrap_bounds`])。 + pub floats: &'a [FloatRect], +} + /// 贪心断行与行盒组装。 /// /// `analysis` 是与 `items` 平行的逐 chunk 宽度无关分析(见 @@ -937,21 +982,23 @@ pub(crate) fn ensure_analysis( /// 布局级度量缓存(同一 TextStyle 整次布局只整形一次探针)。 /// `block_style` 提供 strut(行盒的高度下限与基线位置)。原子图片按基线 /// 对齐(底边落在基线上,CSS 2.1 §10.8.1),不参与断行(不可拆)。 -/// `min_content` 为真时按 min-content 语义断行(`overflow-wrap: break-word` -/// 的紧急断点不参与)。`first_line_indent` 是已解析的首行缩进(CSS Text -/// 3 §4;测量路径与后续行由调用方保证传 0)——从首行可用宽中扣减。 +/// 宽度/语义/缩进/浮动区间见 [`LineConstraints`]。 pub(crate) fn build_lines( shaping: &crate::ShapingContext<'_>, items: &[InlineItem], analysis: &[Option], - max_width: f32, block_style: &ComputedStyle, - min_content: bool, - first_line_indent: f32, + constraints: &LineConstraints<'_>, ) -> Vec { if items.is_empty() { return Vec::new(); } + let LineConstraints { + max_width, + min_content, + first_line_indent, + floats, + } = *constraints; // 数值卫生兜底:NaN 按 0 降级(污染隔离在单元素);+inf 是 MaxContent // 测量的合法「不折行」语义,保留(游标累加的都是有限宽度,坐标不扩散 @@ -966,16 +1013,22 @@ pub(crate) fn build_lines( let strut_above = strut_metrics.ascent + strut_half_leading; let strut_below = strut_metrics.descent + strut_half_leading; + // 首行按 y = 0 查浮动区间:行内游标从浮动右缘之外开始(左浮动), + // 行右界收缩到右浮动左缘之前。 + let (first_left, first_right) = wrap_bounds(floats, 0.0, max_width); let mut builder = LineBuilder { shaping, items, analysis, max_width, + floats, + line_top: 0.0, + line_right: first_right, strut_above, strut_below, lines: Vec::new(), placed: Vec::new(), - cursor: first_line_indent, + cursor: first_left + first_line_indent, current_start: LineStart::Soft { space: false }, next_start: LineStart::Soft { space: false }, trailing_letter_spacing: 0.0, @@ -1047,6 +1100,12 @@ struct LineBuilder<'a> { items: &'a [InlineItem], analysis: &'a [Option], max_width: f32, + /// 浮动占用矩形(空表 = 无浮动环绕)。 + floats: &'a [FloatRect], + /// 已换出行的高度累计(下一行的行顶 y,用于查浮动区间)。 + line_top: f32, + /// 当前行的可用右界(无浮动时恒为 `max_width`)。 + line_right: f32, strut_above: f32, strut_below: f32, lines: Vec, @@ -1212,7 +1271,7 @@ impl LineBuilder<'_> { else { return; }; - if !self.placed.is_empty() && self.cursor + width > self.max_width { + if !self.placed.is_empty() && self.cursor + width > self.line_right { if break_before { self.mark_soft_break(Some(item_index), span.byte_start); self.flush(self.justify); @@ -1222,7 +1281,7 @@ impl LineBuilder<'_> { return; }; start = new_start; - if new_width > self.max_width + if new_width > self.line_right && let Some(emergency) = emergency { self.place_emergency(item_index, new_start, new_end, emergency); @@ -1237,7 +1296,7 @@ impl LineBuilder<'_> { } // 不可断且放不下:溢出放置(保留旧行为) } else if self.placed.is_empty() - && width > self.max_width + && width > self.line_right && let Some(emergency) = emergency { self.place_emergency(item_index, start, end, emergency); @@ -1270,7 +1329,7 @@ impl LineBuilder<'_> { else { continue; }; - if !self.placed.is_empty() && self.cursor + width > self.max_width { + if !self.placed.is_empty() && self.cursor + width > self.line_right { self.mark_soft_break(Some(item_index), part.byte_start); self.flush(self.justify); // 新行是空的:本段即使超宽也直接放置(单个 cluster 不可再拆) @@ -1286,7 +1345,7 @@ impl LineBuilder<'_> { /// 放置一个原子项(图片 / 原子盒):不可拆,放不下先换行。 fn place_atomic(&mut self, item_index: usize, width: f32, break_before: bool) { - if !self.placed.is_empty() && self.cursor + width > self.max_width && break_before { + if !self.placed.is_empty() && self.cursor + width > self.line_right && break_before { self.mark_soft_break(None, 0); self.flush(self.justify); } @@ -1404,7 +1463,7 @@ impl LineBuilder<'_> { } } } - let free = self.max_width - net; + let free = self.line_right - net; if free > 0.0 && free.is_finite() { let count = (0..self.placed.len() - 1) .filter(|&boundary| self.justify_opportunity(boundary)) @@ -1613,9 +1672,10 @@ impl LineBuilder<'_> { { glyph.advance -= letter; } + let line_height = baseline + below; self.lines.push(LineFragment { baseline, - height: baseline + below, + height: line_height, start: std::mem::replace( &mut self.current_start, std::mem::replace(&mut self.next_start, LineStart::Soft { space: false }), @@ -1625,7 +1685,11 @@ impl LineBuilder<'_> { boxes, }); self.placed.clear(); - self.cursor = 0.0; + // 下一行的行顶在上一行之下:按新 y 重新取浮动区间 + self.line_top += line_height; + let (left, right) = wrap_bounds(self.floats, self.line_top, self.max_width); + self.cursor = left; + self.line_right = right; } } diff --git a/crates/nexty-layout/src/style_map.rs b/crates/nexty-layout/src/style_map.rs index 1c4ab68..8adc9d5 100644 --- a/crates/nexty-layout/src/style_map.rs +++ b/crates/nexty-layout/src/style_map.rs @@ -37,16 +37,16 @@ #[cfg(feature = "absolute")] use nexty_css::InsetValue; use nexty_css::{ - AlignItemsValue, AlignSelfValue, BoxSizingValue, ComputedStyle, DisplayValue, - FlexDirectionValue, FlexWrapValue, GapValue, JustifyContentValue, MarginValue, OverflowValue, - PaddingValue, PositionValue, SizeValue, + AlignItemsValue, AlignSelfValue, BoxSizingValue, ClearValue, ComputedStyle, DisplayValue, + FlexDirectionValue, FlexWrapValue, FloatValue, GapValue, JustifyContentValue, MarginValue, + OverflowValue, PaddingValue, PositionValue, SizeValue, }; #[cfg(feature = "grid")] use nexty_css::{GridAutoFlowValue, GridTrack, GridTrackList}; use taffy::{ - AlignItems, AlignSelf, BoxSizing, Dimension, Display, FlexDirection, FlexWrap, JustifyContent, - LengthPercentage, LengthPercentageAuto, Overflow, Point, Position, Rect, Size, Style, - style_helpers as sh, + AlignItems, AlignSelf, BoxSizing, Clear, Dimension, Display, FlexDirection, FlexWrap, Float, + JustifyContent, LengthPercentage, LengthPercentageAuto, Overflow, Point, Position, Rect, Size, + Style, style_helpers as sh, }; #[cfg(feature = "grid")] use taffy::{ @@ -125,6 +125,26 @@ pub(crate) fn map_style(style: &ComputedStyle) -> Style { y: overflow, }; + // float / clear(CSS 2.1 §9.5.1/§9.5.2):blockify 拦截——绝对/固定定位的 + // 元素 `float` 计算为 none(CSS 2.1 §9.7)。flex/grid item 上的 float 由 + // taffy 的 flexbox/grid 算法忽略(其 Style 文档明确 float 只作用于 block + // 布局的子节点),行为与「计算为 none」一致。 + s.float = if s.position == Position::Absolute { + Float::None + } else { + match style.float { + FloatValue::None => Float::None, + FloatValue::Left => Float::Left, + FloatValue::Right => Float::Right, + } + }; + s.clear = match style.clear { + ClearValue::None => Clear::None, + ClearValue::Left => Clear::Left, + ClearValue::Right => Clear::Right, + ClearValue::Both => Clear::Both, + }; + // Flexbox 容器/子项。 s.flex_direction = match style.flex_direction { FlexDirectionValue::Row => FlexDirection::Row, diff --git a/crates/nexty-layout/src/tree_build.rs b/crates/nexty-layout/src/tree_build.rs index 1914523..310d5db 100644 --- a/crates/nexty-layout/src/tree_build.rs +++ b/crates/nexty-layout/src/tree_build.rs @@ -128,6 +128,8 @@ pub(crate) struct InlineRunNode<'a> { /// 簇映射 / 断点切分与可用宽无关,跨 measure 宽度档位复用——只有 /// 贪心放置按宽度重跑。items 在树构建期定型,长度即缓存长度。 analysis: RefCell>>, + /// 环绕修正后的行盒(浮动表非空时由布局层写入,装配优先消费)。 + wrapped: RefCell>>, } impl InlineRunNode<'_> { @@ -152,6 +154,46 @@ impl InlineRunNode<'_> { let (_, _, lines) = self.lines_cache.borrow_mut().remove(position); return lines; } + let lines = self.compute_lines(available_width, min_content, &[]); + self.lines_cache + .borrow_mut() + .push((available_width, min_content, lines.clone())); + lines + } + + /// 按浮动占用区间重排行盒(浮动环绕修正 pass),并存进 `wrapped` 缓存 + /// 供片段装配优先消费。返回修正后的行盒总高(作为 run 叶的定高回写 + /// taffy,使容器高度与后续兄弟位置按实际行数解算)。 + /// + /// 只在定宽语义下使用(`min_content` 恒 false):内在尺寸测量与浮动 + /// 无关(CSS 2.2 §10.3.7);不与 `lines_cache` 混用(同宽不同约束)。 + #[cfg(feature = "block")] + pub(crate) fn wrap_against( + &self, + available_width: f32, + floats: &[crate::inline::FloatRect], + ) -> f32 { + let lines = self.compute_lines(available_width, false, floats); + let height: f32 = lines.iter().map(|line| line.height).sum(); + *self.wrapped.borrow_mut() = Some(lines); + height + } + + /// 环绕修正后的行盒(未修正过返回 `None`)。 + #[cfg(feature = "block")] + pub(crate) fn wrapped_lines(&self) -> Option> { + self.wrapped.borrow_mut().take() + } + + /// 行盒计算内核:原子盒惰性布局 + 逐 chunk 分析缓存 + 贪心断行。 + /// + /// `floats` 为空时行为与历史一致(浮动区间恒为全宽)。 + fn compute_lines( + &self, + available_width: f32, + min_content: bool, + floats: &[crate::inline::FloatRect], + ) -> Vec { for item in self.items.borrow_mut().iter_mut() { if let InlineItem::Block(atomic) = item { // feature `block` 关闭时无原子盒递归布局管线:保持占位片段 @@ -172,32 +214,24 @@ impl InlineRunNode<'_> { } } let items = self.items.borrow(); - let lines = { - let mut analysis = self.analysis.borrow_mut(); - if analysis.len() != items.len() { - analysis.resize_with(items.len(), || None); - } - // 宽度无关部分(shaping / 簇映射 / 断点切分)按档位懒填充, - // 跨 measure 宽度档位复用;贪心放置在 build_lines 内按宽重跑 - crate::inline::ensure_analysis(self.ctx.shaper, &items, &mut analysis, min_content); - let shaping = crate::ShapingContext { - shaper: self.ctx.shaper, - metrics: &self.ctx.metrics, - }; - crate::inline::build_lines( - &shaping, - &items, - &analysis, - available_width, - &self.strut_style, - min_content, - self.first_line_indent(available_width, min_content), - ) + let mut analysis = self.analysis.borrow_mut(); + if analysis.len() != items.len() { + analysis.resize_with(items.len(), || None); + } + // 宽度无关部分(shaping / 簇映射 / 断点切分)按档位懒填充, + // 跨 measure 宽度档位复用;贪心放置在 build_lines 内按宽重跑 + crate::inline::ensure_analysis(self.ctx.shaper, &items, &mut analysis, min_content); + let shaping = crate::ShapingContext { + shaper: self.ctx.shaper, + metrics: &self.ctx.metrics, }; - self.lines_cache - .borrow_mut() - .push((available_width, min_content, lines.clone())); - lines + let constraints = crate::inline::LineConstraints { + max_width: available_width, + min_content, + first_line_indent: self.first_line_indent(available_width, min_content), + floats, + }; + crate::inline::build_lines(&shaping, &items, &analysis, &self.strut_style, &constraints) } /// 首行缩进的 used value(CSS Text 3 §4)。 @@ -495,9 +529,11 @@ fn collect_children_boxes<'a>( DisplayValue::Contents => { collect_children_boxes(ctx, boxes, child, child_style, kind, state); } - // 块容器走法:行内级子元素进 run 叶 + // 块容器走法:行内级子元素进 run 叶(浮动的元素被 blockify, + // CSS 2.1 §9.7,落进下面的块级分支) _ if kind == WalkKind::BlockContainer - && is_inline_level(child_style.display) => + && is_inline_level(child_style.display) + && child_style.float == nexty_css::FloatValue::None => { state .run @@ -550,6 +586,7 @@ fn flush_run<'a>( strut_style: strut_style.clone(), lines_cache: RefCell::new(Vec::new()), analysis: RefCell::new(Vec::new()), + wrapped: RefCell::new(None), }, ); state.participants.push(taffy); diff --git a/crates/nexty-layout/tests/layout.rs b/crates/nexty-layout/tests/layout.rs index d856205..57d0e6a 100644 --- a/crates/nexty-layout/tests/layout.rs +++ b/crates/nexty-layout/tests/layout.rs @@ -1704,3 +1704,208 @@ fn display_none_and_contents_in_inline_subtree_unchanged() { let text: String = line.runs.iter().map(|run| run.text.as_ref()).collect(); assert_eq!(text, "aCb", "none 丢弃、contents 穿透、其余连续"); } + +// --------------------------------------------------------------------------- +// 浮动布局(CSS 2.1 §9.5):taffy float_layout 接线的探针测试 +// --------------------------------------------------------------------------- + +/// 左浮动盒脱离常规流,后续文本逐行环绕:浮动旁边的行起点右移, +/// 浮动底缘之下的行回到左缘;多出行数体现在匿名块高度上。 +#[test] +fn float_left_wraps_subsequent_text() { + let words = "word ".repeat(60); + let (document, root) = layout( + &format!( + "
F
\ + {words}" + ), + "", + 400.0, + ); + let floated = find(&document, &root, "div").expect("floated fragment"); + // 浮动盒在左上:x = 0,且脱离流(后续文本从其右侧开始) + assert!(approx(floated.border_box.x, 0.0), "左浮动贴左缘"); + assert!(approx(floated.border_box.width, 100.0)); + let body_fragment = body(&document, &root); + // 块级浮动子元素使文本 run 成匿名块片段(CSS 2.2 §9.2.1.1 混排语义), + // 行盒在匿名片段里 + let anonymous = body_fragment + .children + .iter() + .find(|c| c.anonymous && !c.lines.is_empty()) + .expect("anonymous block holding wrapped text"); + // glyph.x 已是 run 内绝对坐标(含行左缩进);匿名块无 border/padding, + // 加上其 border_box.x 即容器内容盒坐标 + let line_x = |line: &LineFragment| { + line.runs + .first() + .and_then(|run| run.glyphs.first()) + .map(|glyph| glyph.x + anonymous.border_box.x) + .unwrap_or(f32::MAX) + }; + // 逐行累计高度推 y:行顶 < 浮动底缘(60px)的行收缩,之后的行回全宽 + let mut y = anonymous.border_box.y; + let mut beside = 0usize; + let mut below = 0usize; + for line in &anonymous.lines { + let x = line_x(line); + if y < 60.0 - 0.01 { + assert!( + x >= 100.0 - 0.01, + "浮动旁的行不得与浮动重叠(y={y}, x={x})" + ); + beside += 1; + } else { + assert!(x <= 0.01, "浮动下方的行回到左缘(y={y}, x={x})"); + below += 1; + } + y += line.height; + } + assert!(beside >= 2, "浮动旁至少两行(实际 {beside})"); + assert!(below >= 1, "浮动下方至少一行(实际 {below})"); + assert!( + anonymous.border_box.height >= y - anonymous.border_box.y - 0.01, + "匿名块高度覆盖全部行(高 {} 行底 {})", + anonymous.border_box.height, + y - anonymous.border_box.y + ); +} + +/// 右浮动:浮动旁的行右缘收缩到浮动左缘之前。 +#[test] +fn float_right_shrinks_line_right_edge() { + let words = "word ".repeat(12); + let (document, root) = layout( + &format!( + "
F
\ + {words}" + ), + "", + 400.0, + ); + let anonymous = body(&document, &root) + .children + .iter() + .find(|c| c.anonymous && !c.lines.is_empty()) + .expect("anonymous block holding wrapped text"); + let mut y = anonymous.border_box.y; + for line in &anonymous.lines { + if y < 60.0 - 0.01 { + let right = line + .runs + .iter() + .filter_map(|run| run.glyphs.last().map(|g| g.x + g.advance)) + .fold(0.0_f32, f32::max) + + anonymous.border_box.x; + assert!( + right <= 400.0 - 120.0 + 0.01, + "右浮动旁的行不越过浮动左缘(y={y}, 行右缘={right})" + ); + } + y += line.height; + } +} + +/// 图片浮动(``):行环绕图片,图片不参与行内流。 +#[test] +fn floated_image_wraps_text() { + let (document, root) = layout( + "\ + word word word word word word word word word word", + "", + 400.0, + ); + let image = find(&document, &root, "img").expect("image fragment child"); + assert!(approx(image.border_box.x, 0.0), "图片浮动贴左缘"); + assert!(approx(image.border_box.width, 80.0)); +} + +/// 右浮动盒贴包含块右缘。 +#[test] +fn float_right_hugs_right_edge() { + let (document, root) = layout( + "
F
\ + word word word", + "", + 400.0, + ); + let floated = find(&document, &root, "div").expect("floated fragment"); + assert!( + approx(floated.border_box.x + floated.border_box.width, 400.0), + "右浮动贴右缘(实际右缘={})", + floated.border_box.x + floated.border_box.width + ); +} + +/// `clear: both` 把后续块推到两侧浮动之下。 +#[test] +fn clear_both_pushes_below_floats() { + let (document, root) = layout( + "\ +
L
\ +
R
\ +

after

\ + ", + "p { margin: 0 }", + 400.0, + ); + let cleared = find(&document, &root, "p").expect("cleared fragment"); + assert!( + cleared.border_box.y >= 100.0 - 0.01, + "clear 后块在浮动底缘之下(实际 y={})", + cleared.border_box.y + ); +} + +/// 浮动盒参与父块高度(float_content_contribution,CSS 2.1 §9.5 常见依赖: +/// `overflow: hidden` 建立 BFC 后高度收缩包含浮动)。 +#[test] +fn float_contributes_to_parent_height() { + let (document, root) = layout( + "
\ +
F
\ +
", + "", + 400.0, + ); + // body 的第一个子片段即 outer(find 会先命中嵌套的内层 div) + let outer = body(&document, &root) + .children + .first() + .expect("outer div fragment"); + assert!( + outer.border_box.height >= 90.0 - 0.01, + "BFC(overflow:hidden)父块高度包含浮动(实际高度={})", + outer.border_box.height + ); +} + +/// 双左浮动横向并排放置(CSS 2.1 §9.5 规则 4:先尽量靠左上)。 +#[test] +fn two_left_floats_side_by_side() { + let (document, root) = layout( + "\ +
A
\ +
B
\ + ", + "", + 400.0, + ); + let b = body(&document, &root); + let floats: Vec<_> = b + .children + .iter() + .filter(|c| !c.anonymous && c.border_box.width > 0.0) + .collect(); + assert_eq!(floats.len(), 2, "两个浮动子片段"); + assert!(approx(floats[0].border_box.x, 0.0)); + assert!( + approx(floats[1].border_box.x, 60.0), + "第二个左浮动贴第一个右缘(实际 x={})", + floats[1].border_box.x + ); + assert!( + approx(floats[0].border_box.y, floats[1].border_box.y), + "同一行放置" + ); +} From 6d62b99f848714917a6c211ee44910b78a86765d Mon Sep 17 00:00:00 2001 From: Ink-dark Date: Sat, 31 Oct 2026 15:59:03 +0800 Subject: [PATCH 03/14] [layout] float wrap: hit-test and selection geometry follow shrunken lines --- crates/nexty-layout/tests/selection.rs | 43 ++++++++++++++++++++++++++ 1 file changed, 43 insertions(+) diff --git a/crates/nexty-layout/tests/selection.rs b/crates/nexty-layout/tests/selection.rs index 49eda3f..d118f70 100644 --- a/crates/nexty-layout/tests/selection.rs +++ b/crates/nexty-layout/tests/selection.rs @@ -278,6 +278,49 @@ fn text_position(node: NodeId, offset: usize) -> TextPosition { TextPosition { node, offset } } +/// 浮动环绕:浮动旁的行仍在 `TextMap` 里可命中,选区矩形按收缩后的行几何 +/// (左缘让出左浮动,不与浮动重叠)。 +#[test] +fn wrapped_lines_are_hit_testable_and_selectable() { + let words = "word ".repeat(20); + let (document, root) = layout( + &format!( + "
\ + {words}" + ), + "", + 400.0, + ); + let body_node = find(&document, &root, "body").unwrap().node; + let text_node = direct_text_node(&document, body_node); + let map = TextMap::new(&root); + + // 首行文本在浮动右侧:该点命中首个词内的源偏移(0..4) + let hit = map.hit(120.0, 8.0).expect("hit on wrapped first line"); + assert_eq!(hit.node, text_node); + assert!(hit.offset <= 4, "命中首词内部(offset={})", hit.offset); + // 浮动盒覆盖的点(左侧 0–100px):无精确文本,按吸附语义落到最近的 + // 正文行首(浮动盒本身不是文本,不产生命中原点) + let snapped = map.hit(50.0, 8.0).expect("snaps to nearest line"); + assert_eq!(snapped.node, text_node); + assert!( + snapped.offset <= 1, + "吸附到行首附近(offset={})", + snapped.offset + ); + // 选区矩形不会伸进浮动盒:首行相对 body 内容盒的左缘 ≥ 100 + let origin = content_origin(&document, &root, "body").expect("body origin"); + let rects = map.rects(text_position(text_node, 0), text_position(text_node, 4)); + assert!(!rects.is_empty()); + for rect in &rects { + assert!( + origin.0 + rect.x >= 100.0 - 0.01, + "浮动旁的选区矩形让出浮动(左缘={})", + origin.0 + rect.x + ); + } +} + #[test] fn hit_snaps_to_glyph_halves_and_line_ends() { let (document, root) = layout("

ab

", "", 400.0); From 266a61a47a4e3e2017c5a86e0ed3d7bb8384e544 Mon Sep 17 00:00:00 2001 From: Ink-dark Date: Sat, 31 Oct 2026 16:27:08 +0800 Subject: [PATCH 04/14] [layout] propagate BFC float rects to descendant run leaves across block boundaries (0.1.29) --- Cargo.lock | 2 +- crates/nexty-layout/Cargo.toml | 2 +- crates/nexty-layout/src/block.rs | 105 ++++++++++++++++++++++--------- 3 files changed, 78 insertions(+), 31 deletions(-) diff --git a/Cargo.lock b/Cargo.lock index 3fab3fb..5d6c6ef 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -1729,7 +1729,7 @@ dependencies = [ [[package]] name = "nexty-layout" -version = "0.1.27" +version = "0.1.29" dependencies = [ "harfrust", "nexty-css", diff --git a/crates/nexty-layout/Cargo.toml b/crates/nexty-layout/Cargo.toml index ee7bf5e..ded476d 100644 --- a/crates/nexty-layout/Cargo.toml +++ b/crates/nexty-layout/Cargo.toml @@ -1,7 +1,7 @@ [package] name = "nexty-layout" description = "Nexty 自研盒级布局" -version = "0.1.28" +version = "0.1.29" edition.workspace = true license.workspace = true repository.workspace = true diff --git a/crates/nexty-layout/src/block.rs b/crates/nexty-layout/src/block.rs index 38c78d1..dd74f17 100644 --- a/crates/nexty-layout/src/block.rs +++ b/crates/nexty-layout/src/block.rs @@ -48,6 +48,14 @@ //! 定位(relative/absolute)时与 CSS 一致——这是常见用法;父盒 static 时 //! 偏差,列为已知限制。`position: fixed` 同样映射为 taffy `Absolute` //! (视口锚定未建模)。 +//! 9. **浮动环绕**:浮动放置 / `clear` / BFC 避让 / 高度贡献由 taffy +//! `float_layout` 完成(CSS 2.2 §9.5),但 taffy 不收缩 measure 叶的可用宽 +//! (run 叶无子内容可下钻)——本模块的 [`apply_float_wrapping`] 在后处理 +//! pass 里按 taffy 已放置的浮动矩形逐行收缩重排文本行盒并回写叶定高(再解算 +//! 一轮收敛)。偏差:行按行顶 y 取可用区间(行跨入更窄区间不细分)、浮动 +//! 只按文档序判定「前置」(纹理式堆叠以 taffy 放置为准)。 +//! 10. **浮动影响后代行盒**:浮动属于祖先 BFC 的浮动,收缩传播到后代块的 +//! run 叶(跨块边界),遇建立新 BFC 的盒子截断继承。 use nexty_css::{ComputedStyle, MarginValue, TextAlignValue}; use nexty_dom::NodeId; @@ -146,23 +154,40 @@ pub(crate) fn layout_atomic_subtree( /// 收缩会与浮动重叠。这里按首轮解算的真实浮动矩形逐行收缩重排,并把修正 /// 高度回写上层的叶样式(返回 `true` 表示需要再解算一轮)。 /// -/// 只收容器直接子节点中**位于该 run 之前**的浮动(CSS 2.2 §9.5:浮动只影响 -/// 其后内容);嵌套 BFC 的浮动由各自的容器递归处理。 +/// 浮动的 BFC 是**祖先容器**(如 `body`),受影响的行盒可在任意后代块里 +/// (如 `

` 的 run 叶)——因此递归携带两样东西:已放置浮动的**绝对矩形 +/// 表**(换算到当前叶的坐标再收缩行盒)与绝对原点。浮动只影响其后的内容 +/// (CSS 2.2 §9.5),按子节点文档序过滤;遇到建立新 BFC 的盒子(浮动自身、 +/// `overflow` 非 visible、绝对/固定定位、`flow-root`)截断继承——那些盒子 +/// 的边框盒避让已由 taffy 完成,其内部行盒相对自身内容盒排布。 fn apply_float_wrapping(boxes: &mut BoxTree<'_>, root: TaffyNode) -> bool { let mut changed = false; - wrap_recursive(boxes, root, &mut changed); + wrap_recursive(boxes, root, (0.0, 0.0), &[], &mut changed); changed } -fn wrap_recursive(boxes: &mut BoxTree<'_>, container: TaffyNode, changed: &mut bool) { +/// 绝对坐标下的浮动矩形(相对文档原点)。 +type AbsFloat = (usize, crate::inline::FloatRect); + +fn wrap_recursive( + boxes: &mut BoxTree<'_>, + container: TaffyNode, + container_border_abs: (f32, f32), + inherited: &[AbsFloat], + changed: &mut bool, +) { let children = boxes.tree.children(container).unwrap_or_default(); if children.is_empty() { return; } let container_layout = *boxes.tree.layout(container).expect("layout"); let inset = content_inset(&container_layout); - // 容器内容盒坐标下的浮动矩形(taffy 的 location 相对父边框盒) - let floats: Vec<(usize, crate::inline::FloatRect)> = children + let content_abs = ( + container_border_abs.0 + inset.0, + container_border_abs.1 + inset.1, + ); + // 本容器的浮动子节点:绝对矩形 + 文档序(taffy location 相对父边框盒) + let own: Vec = children .iter() .enumerate() .filter_map(|(order, &child)| { @@ -174,51 +199,73 @@ fn wrap_recursive(boxes: &mut BoxTree<'_>, container: TaffyNode, changed: &mut b Some(( order, crate::inline::FloatRect { - x: layout.location.x - inset.0, - y: layout.location.y - inset.1, + x: content_abs.0 + layout.location.x - inset.0, + y: content_abs.1 + layout.location.y - inset.1, width: layout.size.width, height: layout.size.height, }, )) }) .collect(); - if !floats.is_empty() { - for (order, &child) in children.iter().enumerate() { - let Some(run) = boxes.runs.get(&child) else { - continue; - }; - let layout = *boxes.tree.layout(child).expect("run layout"); - let run_x = layout.location.x - inset.0; - let run_y = layout.location.y - inset.1; - // 只取排在该 run 之前的浮动,换算到 run 内容盒坐标 - let run_floats: Vec = floats + + for (order, &child) in children.iter().enumerate() { + // 该子节点可见的浮动:继承(祖先 BFC)+ 本容器中排在它之前的 + let visible: Vec = inherited + .iter() + .copied() + .chain( + own.iter() + .filter(|(float_order, _)| *float_order < order) + .copied(), + ) + .collect(); + + let child_layout = *boxes.tree.layout(child).expect("child layout"); + let child_abs = ( + container_border_abs.0 + child_layout.location.x, + container_border_abs.1 + child_layout.location.y, + ); + + if let Some(run) = boxes.runs.get(&child) { + // run 叶内容盒 = 边框盒(无 margin/padding/border) + let run_floats: Vec = visible .iter() - .filter(|(float_order, _)| *float_order < order) .map(|(_, float)| crate::inline::FloatRect { - x: float.x - run_x, - y: float.y - run_y, + x: float.x - child_abs.0, + y: float.y - child_abs.1, ..*float }) .collect(); if run_floats.is_empty() { continue; } - let height = run.wrap_against(layout.size.width, &run_floats); - if (height - layout.size.height).abs() > 0.01 { + let height = run.wrap_against(child_layout.size.width, &run_floats); + if (height - child_layout.size.height).abs() > 0.01 { let mut style = boxes.tree.style(child).expect("run style").clone(); style.size.height = taffy::style_helpers::length(height); if boxes.tree.set_style(child, style).is_ok() { *changed = true; } } + } else { + let child_style = boxes.tree.style(child).ok().cloned(); + let establishes_bfc = child_style.is_none_or(|style| { + style.float != taffy::Float::None + || style.position == taffy::Position::Absolute + || style.display == taffy::Display::FlowRoot + || style.display == taffy::Display::None + || style.overflow.x != taffy::Overflow::Visible + || style.overflow.y != taffy::Overflow::Visible + || style.contain.establishes_independent_formatting_context() + }); + if establishes_bfc { + // 新 BFC:祖先浮动不影响其内部行盒 + wrap_recursive(boxes, child, child_abs, &[], changed); + } else { + wrap_recursive(boxes, child, child_abs, &visible, changed); + } } } - for child in children { - if boxes.runs.contains_key(&child) { - continue; - } - wrap_recursive(boxes, child, changed); - } } /// 对一棵盒树执行 taffy 布局(禁用取整,保持与旧自研一致的小数几何)。 From ed8239115775908c9c7dc405870ad6627d15dfcc Mon Sep 17 00:00:00 2001 From: Ink-dark Date: Sat, 31 Oct 2026 16:27:39 +0800 Subject: [PATCH 05/14] [docs] archive float round: taffy float_layout wiring, wrap pass, cross-container regression test, AGENTS/ADR updates --- AGENTS.md | 6 ++-- crates/nexty-layout/tests/layout.rs | 32 +++++++++++++++++ docs/decisions/2026-10-01-crate-selection.md | 5 +++ docs/plans/2026-10-31-round-float.md | 37 ++++++++++++++++++++ 4 files changed, 77 insertions(+), 3 deletions(-) diff --git a/AGENTS.md b/AGENTS.md index 6bfa2a7..8182d7f 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -18,12 +18,12 @@ MusKitty 的**不造轮子**分支。MusKitty 从零手写浏览器核心模块 - `nexty-network`(v0.1.5)——reqwest blocking 实现 `NetworkFetcher`(`Send + Sync`,供并发抓取):GET/HEAD、`Request.headers` 请求头逐条应用、错误映射(URL 解析/协议 → `InvalidUrl`、超时 → `Timeout`、其余 → `Transport`);`resolve` 以文档 URL 为 base 解析相对子资源地址;回环离线测试覆盖全部错误路径与请求头到达。 - `nexty-text`(v0.1.8)——parley 实现 `TextShaper`:fontique 选字(CSS 字体族列表语义 + 按脚本回退——主族缺字形的码点交给系统字体,CJK 在 Windows 命中 YaHei 等)、harfrust 整形,CSS px 单位;`ShapedText.fonts` 记录本次整形实际用到的字体、`Glyph.font` 标注每个字形归属(供光栅层用正确字体渲染,修复回退字形被主字体渲染的豆腐块)、`Glyph.cluster` 标注该字形所属 cluster 的源文本字节偏移(LB9/LB10 组合序列并入基字符);`FontMetrics` 供 strut 计算,`FontResolver::resolve_font` 给光栅层提供字体字节(实例以 blob id 判等)。**性能(T1 基准发现的阻塞缺陷)**:`ParleyTextShaper` 按(blob id, face index)缓存 `ResolvedFont`——同一字体一份字节快照全进程共享(原先每次整形复制整个字体文件,CJK 回退字体 ≈20 MB/chunk 曾把 2,000 段页面的布局期内存推到 9 GB 后 abort)。单行整形(white-space 折叠归 layout 层)。注意:parley 0.11 的整形后端是 harfrust 而非 ADR 所列 swash,swash 已移出依赖树。 - `nexty-paint`(v0.1.7)——vello_cpu 实现 `Rasterizer`:`FillRect`(src-over + 覆盖率抗锯齿)、`StrokeRect`(只描边)、`DrawText`(字体数据由 text 层整形结果直接下发 `fonts`,按 `glyph.font` 分组用对应字体渲染字形——回退后一条 run 可跨多字体)、`DrawImage`(已解码 RGBA8 按矩形下发,1:1 整数缩放;**像素按 `Arc` 共享(M1)**——`Scene.images` 持引用计数,构建/发送/光栅全程零像素拷贝);`Scene::translated`(M6)生成整体平移的场景副本(字形与图片像素引用计数共享,滚动路径的 origin 平移下放到发送阶段);`decode` 提供最小图片解码路径(png 可选 feature,RGB/灰度归一为 RGBA8,不支持格式返回 `DecodeError` 而非 panic),**输入边界防护(解码预检)**:先 `into_dimensions()` 只读头部校验尺寸(边长 ≤ 16384 且 `宽 × 高` ≤ 2^26 ≈ 256 MB RGBA8,`MAX_DIMENSION` / `MAX_PIXEL_AREA` 公开常量),预检不通过返回 `SizeUnsupported` 且不做任何像素分配——分配失败是 abort,panic 兜底兜不住;facade 输出非预乘 RGBA8。GPU 后端 `vello_hybrid` 依赖 wgpu surface 由 chrome 层提供后接入,`Rasterizer` trait 即双后端接缝。 -- `nexty-layout`(v0.1.27)——盒级几何(block / flex / grid / absolute)由 `taffy` 接管(MIT,Servo/Blitz 采用;`taffy` 依赖常驻,feature 只切能力开关),**inline / 文本布局与 table 仍自研**。taffy 管线三步:`style_map`(`ComputedStyle → taffy::Style` 单向映射,覆盖 display/position/box-sizing/inset/尺寸/margin/padding/border/flex-*/grid-*/gap;映射前做数值卫生兜底——非有限长度/百分比降级 auto/0,污染隔离在单元素)、`tree_build`(按 CSS Display §3 生成盒树,`none` 跳过、`contents` 提升、`` 以自然尺寸建叶,维护 `NodeId ↔ taffy Node` 双向映射;`build_box` / `collect_children_boxes` 入口对 DOM 深度做 `debug_assert`(纵深防御,主防线在 html 解析入口截断);行内内容经 `inline` 模块收集后包装成**匿名块 run 叶节点**(行内子树中的块级子元素按 CSS 2.2 §9.2.1.1 把 run 拆成多段、各自成匿名块,块级子盒按普通块布局——不再丢弃),measure function 手动构造 `LayoutOutput`——跑自研断行 `inline::build_lines` 提供内在尺寸并上报**首行 baseline**,使 flex/grid `align-items: baseline` 生效;`margins_can_collapse_through` 语义与 `compute_leaf_layout` 对齐:仅实测高度 0 可穿透)、`block`(`compute_layout` 解算后读回 `taffy::Layout` 组装 `Fragment`,行盒并入块容器或承接为匿名块片段;`text-align` 的 center/right 在行盒并入时施加——整行平移,溢出行防负偏移)。taffy 覆盖:块级流(margin 折叠 §8.3.1、宽度解析 §10.3.3、min/max 收束 §10.4/§10.7)、flex(含 wrap/shrink/完整对齐值)、grid(轨道/auto-flow)、绝对定位(inset)。自研保留:行内断行(strut §10.8、混合样式 run、**`white-space` 六种取值**、`
`/保留换行硬断、UAX#14 贪心断行)、**CSS Text 放置期修正**(letter-spacing / word-spacing 按簇施加——行末簇字距不计行宽;`text-align: justify` 的 `auto` 近似——软折行非末行把自由空间均匀分配到折叠空格与同块簇间断点(行尾裁剪按字形 x 计量,末字形与空格间的字距间隙计入可见宽,保证各行右缘一致);`text-indent` 首行缩进——每容器一次、百分比按行盒包含块(块容器自身内容盒宽)折算〔与 Chromium 一致,Edge 实机对照确认〕、不进 min/max-content;`tab-size` 保留制表推进到 `tab-size`×空格宽的下一整数倍;pre-wrap 行尾空格悬挂——不占行宽可溢出、字节区间保留供复制/选区;全部为放置期修正、不改整形结果、不产生/消灭断点;偏差清单见 `inline/mod.rs` 模块文档:跨行内元素边界不加距、justify 不做 inter-word 收缩与 `text-justify` 分档、pre-wrap 空格不设空格机会、`each-line`/`hanging` 未实现)、行内原子盒(`inline-block`/`inline-flex`/`inline-table` 按 shrink-to-fit §10.3.7 独立布局,内在尺寸测量在 `tree_build::InlineRunNode::measure`)、替换元素尺寸解析(`attribute_px` 按 WHATWG §2.4.4.2 非负整数规则解析——只收数字、`40.5` → 40,结果须有限且 ≤ `MAX_CSS_LENGTH`,否则回落自然尺寸)、`build_lines` 包含块宽度 NaN 时按 0 降级(MaxContent 的 +inf 是合法「不折行」语义,保留)。UAX#14(Unicode 18.0.0)断点 / glyph cluster 映射 / min-content / span 切分 API(`break_opportunities` / `cluster_map` / `min_content_width` / `split_spans`,逐条比对官方 19,346 条 `LineBreakTest`,见 `tests/inline_conformance.rs`)**已接入 `build_lines`**:文本项只整形一次,按 `cluster_map → break_opportunities → split_spans` 切段后贪心放置;`word-break` / `overflow-wrap` 由 computed style 映射为 `BreakOptions`(`break-word` 的紧急断点不参与 min-content)。**性能(H4/M10/M12,layout 0.1.25–0.1.26)**:逐 chunk 宽度无关分析缓存(shaping / 簇映射 / 断点切分按 chunk 缓存于 run 节点,跨 measure 宽度档位复用,行为由片段树指纹测试钉住逐字节一致)、布局级 `MetricsCache`(同一 TextStyle 整次布局只整形一次 NBSP 探针——基线实测 text-heavy 64,818 次 → 10 次)、`root_style` 按 `ctx.styles` 借用(Cow)、run 叶行盒缓存命中 take 语义、`ensure_style` 按 NodeId 身份免全字段比较;`remap_glyph` 对越界字体下标跳过不 panic(M12,畸形整形器输出单测钉住)。conformance 代码按三分离拆为 `inline/{cluster_map,break_ops,span_split}.rs` 与 `inline/uax14/{classes,data,rules}.rs`。**文本选区**:`selection` 模块(`TextMap`)以「文本节点 + 源字节偏移」为端点,提供 glyph cluster 对齐的命中(不切 grapheme;命中/吸附按「y 距离 → x 距离 → 深度」选行并向嵌套原子盒内部行下钻——内部行不被外层行遮蔽)、逐行选区矩形、UAX#29 选词与复制文本重建(软折行不插换行、`
`/块边界插 `\n`、`pre` 保留空白);`Collector` 保留文本节点身份与逐字符源映射,`TextRun` 携带 `text` / `source_map` / 实际渲染字节区间,`LineFragment` 记录行首软/硬断行。片段树输出(边框盒 + 盒模型 + 文本行 + run 字体表 + 源映射)供 paint 与选区消费。盒级布局完备度约 35% → 约 75–80%(grid / 多行 flex / 绝对定位借 taffy 补齐,CSS Text 放置期修正落地)。**未实现**:table、float、`position: fixed` 视口锚定与「最近定位祖先」包含块搜索(taffy 相对树内父盒定位)、`text-align-last`/`text-justify`、多行 baseline 组、`vertical-align` 非 baseline、bidi/RTL(偏差清单见 `crates/nexty-layout/src/block.rs`、`inline/mod.rs`、`selection.rs` 与 `style_map.rs` 模块文档)。**栈预算**:512 层布局递归(taffy 解算 + 片段装配)实测需 5–6 MB 栈(约 10 KB/层),布局只跑在主线程——Windows PE 主线程栈默认仅 1 MiB,512 层页面曾直接栈溢出拖垮进程(实机验收抓到),已由 `nexty-chrome/build.rs` 把主线程栈预留提到 16 MiB(`/STACK`,MSVC);chrome 测试的全链加固回归用例把该约束钉在显式 32 MB 线程里。模块功能按 feature 拆分(`block`/`inline`/`flex`/`replaced`/`taffy-map`/`grid`/`absolute`/`selection`,`table` 预留),见下方Feature 映射表。 +- `nexty-layout`(v0.1.29)——盒级几何(block / flex / grid / absolute / float)由 `taffy` 接管(MIT,Servo/Blitz 采用;`taffy` 依赖常驻,feature 只切能力开关),**inline / 文本布局与 table 仍自研**。taffy 管线三步:`style_map`(`ComputedStyle → taffy::Style` 单向映射,覆盖 display/position/box-sizing/inset/尺寸/margin/padding/border/flex-*/grid-*/gap;映射前做数值卫生兜底——非有限长度/百分比降级 auto/0,污染隔离在单元素)、`tree_build`(按 CSS Display §3 生成盒树,`none` 跳过、`contents` 提升、`` 以自然尺寸建叶,维护 `NodeId ↔ taffy Node` 双向映射;`build_box` / `collect_children_boxes` 入口对 DOM 深度做 `debug_assert`(纵深防御,主防线在 html 解析入口截断);行内内容经 `inline` 模块收集后包装成**匿名块 run 叶节点**(行内子树中的块级子元素按 CSS 2.2 §9.2.1.1 把 run 拆成多段、各自成匿名块,块级子盒按普通块布局——不再丢弃),measure function 手动构造 `LayoutOutput`——跑自研断行 `inline::build_lines` 提供内在尺寸并上报**首行 baseline**,使 flex/grid `align-items: baseline` 生效;`margins_can_collapse_through` 语义与 `compute_leaf_layout` 对齐:仅实测高度 0 可穿透)、`block`(`compute_layout` 解算后读回 `taffy::Layout` 组装 `Fragment`,行盒并入块容器或承接为匿名块片段;`text-align` 的 center/right 在行盒并入时施加——整行平移,溢出行防负偏移)。taffy 覆盖:块级流(margin 折叠 §8.3.1、宽度解析 §10.3.3、min/max 收束 §10.4/§10.7)、flex(含 wrap/shrink/完整对齐值)、grid(轨道/auto-flow)、绝对定位(inset)、**float(`float_layout` feature:浮动放置 / `clear` / BFC 槽位避让 / 容器高度贡献,CSS 2.2 §9.5)**。**浮动环绕修正 pass(layout 0.1.28–0.1.29)**:taffy 的浮动实现只对有子内容可下钻的盒子收缩可用宽,measure 叶(run 叶)拿不到浮动区间——首轮解算后按 taffy 已放置的浮动矩形逐行收缩重排 run 叶行盒(`build_lines` 的 `LineConstraints.floats`),行数变化时回写叶定高再解算一轮(浮动尺寸与文本无关,一次迭代固定点);浮动矩形沿祖先 BFC 传播到后代 run 叶(跨 `

` 等块边界),遇新建 BFC(float / overflow 非 visible / absolute / flow-root)截断。偏差:行按行顶 y 取可用区间(跨入更窄区间不细分)、浮动只按文档序判定「前置」。自研保留:行内断行(strut §10.8、混合样式 run、**`white-space` 六种取值**、`
`/保留换行硬断、UAX#14 贪心断行)、**CSS Text 放置期修正**(letter-spacing / word-spacing 按簇施加——行末簇字距不计行宽;`text-align: justify` 的 `auto` 近似——软折行非末行把自由空间均匀分配到折叠空格与同块簇间断点(行尾裁剪按字形 x 计量,末字形与空格间的字距间隙计入可见宽,保证各行右缘一致);`text-indent` 首行缩进——每容器一次、百分比按行盒包含块(块容器自身内容盒宽)折算〔与 Chromium 一致,Edge 实机对照确认〕、不进 min/max-content;`tab-size` 保留制表推进到 `tab-size`×空格宽的下一整数倍;pre-wrap 行尾空格悬挂——不占行宽可溢出、字节区间保留供复制/选区;全部为放置期修正、不改整形结果、不产生/消灭断点;偏差清单见 `inline/mod.rs` 模块文档:跨行内元素边界不加距、justify 不做 inter-word 收缩与 `text-justify` 分档、pre-wrap 空格不设空格机会、`each-line`/`hanging` 未实现)、行内原子盒(`inline-block`/`inline-flex`/`inline-table` 按 shrink-to-fit §10.3.7 独立布局,内在尺寸测量在 `tree_build::InlineRunNode::measure`)、替换元素尺寸解析(`attribute_px` 按 WHATWG §2.4.4.2 非负整数规则解析——只收数字、`40.5` → 40,结果须有限且 ≤ `MAX_CSS_LENGTH`,否则回落自然尺寸)、`build_lines` 包含块宽度 NaN 时按 0 降级(MaxContent 的 +inf 是合法「不折行」语义,保留)。UAX#14(Unicode 18.0.0)断点 / glyph cluster 映射 / min-content / span 切分 API(`break_opportunities` / `cluster_map` / `min_content_width` / `split_spans`,逐条比对官方 19,346 条 `LineBreakTest`,见 `tests/inline_conformance.rs`)**已接入 `build_lines`**:文本项只整形一次,按 `cluster_map → break_opportunities → split_spans` 切段后贪心放置;`word-break` / `overflow-wrap` 由 computed style 映射为 `BreakOptions`(`break-word` 的紧急断点不参与 min-content)。**性能(H4/M10/M12,layout 0.1.25–0.1.26)**:逐 chunk 宽度无关分析缓存(shaping / 簇映射 / 断点切分按 chunk 缓存于 run 节点,跨 measure 宽度档位复用,行为由片段树指纹测试钉住逐字节一致)、布局级 `MetricsCache`(同一 TextStyle 整次布局只整形一次 NBSP 探针——基线实测 text-heavy 64,818 次 → 10 次)、`root_style` 按 `ctx.styles` 借用(Cow)、run 叶行盒缓存命中 take 语义、`ensure_style` 按 NodeId 身份免全字段比较;`remap_glyph` 对越界字体下标跳过不 panic(M12,畸形整形器输出单测钉住)。conformance 代码按三分离拆为 `inline/{cluster_map,break_ops,span_split}.rs` 与 `inline/uax14/{classes,data,rules}.rs`。**文本选区**:`selection` 模块(`TextMap`)以「文本节点 + 源字节偏移」为端点,提供 glyph cluster 对齐的命中(不切 grapheme;命中/吸附按「y 距离 → x 距离 → 深度」选行并向嵌套原子盒内部行下钻——内部行不被外层行遮蔽)、逐行选区矩形、UAX#29 选词与复制文本重建(软折行不插换行、`
`/块边界插 `\n`、`pre` 保留空白);`Collector` 保留文本节点身份与逐字符源映射,`TextRun` 携带 `text` / `source_map` / 实际渲染字节区间,`LineFragment` 记录行首软/硬断行。片段树输出(边框盒 + 盒模型 + 文本行 + run 字体表 + 源映射)供 paint 与选区消费。盒级布局完备度约 35% → 约 75–80%(grid / 多行 flex / 绝对定位借 taffy 补齐,CSS Text 放置期修正落地)。**未实现**:table、`position: fixed` 视口锚定与「最近定位祖先」包含块搜索(taffy 相对树内父盒定位)、`text-align-last`/`text-justify`、多行 baseline 组、`vertical-align` 非 baseline、bidi/RTL(偏差清单见 `crates/nexty-layout/src/block.rs`、`inline/mod.rs`、`selection.rs` 与 `style_map.rs` 模块文档)。**栈预算**:512 层布局递归(taffy 解算 + 片段装配)实测需 5–6 MB 栈(约 10 KB/层),布局只跑在主线程——Windows PE 主线程栈默认仅 1 MiB,512 层页面曾直接栈溢出拖垮进程(实机验收抓到),已由 `nexty-chrome/build.rs` 把主线程栈预留提到 16 MiB(`/STACK`,MSVC);chrome 测试的全链加固回归用例把该约束钉在显式 32 MB 线程里。模块功能按 feature 拆分(`block`/`inline`/`flex`/`replaced`/`taffy-map`/`grid`/`absolute`/`selection`,`table` 预留),见下方Feature 映射表。 - `nexty-chrome`(v0.1.25)——浏览器外壳:`pipeline`(HTML → 级联 → 布局 → 片段树 → paint 显示列表,含 CSS 边框转四条填充带、文本 run 绝对坐标与**行偏移累加**(run 携带字体表,`recascade` 以实际视口重级联——视口单位在 computed 阶段折算、resize 后取新值;`Page` 保留作者样式表供重级联并持有 `InlineStyleCache`(M5:recascade 复用内联样式解析)、**页面坐标系场景缓存 `SceneCache` 与 resize 合帧器 `ResizeCoalescer`(M6)**——滚动/滚动条拖拽只做 `Scene::translated` origin 平移零 emit,导航/重排/选区变化推进代次或高亮键失效重建,连发 Resized 折叠到下一次 RedrawRequested 每帧至多一次重排;**图片像素零拷贝(M1)**:`Page.images`/`Scene.images` 均为 `Arc`,`RenderThread::render` 按所有权收 `Scene` 不再整树克隆)、`bench`(性能基准共享支撑:确定性语料生成 + `CountingShaper` 整形调用计数 + BENCH_MODE 门控,基准正文 `benches/pipeline.rs` 跑在显式 32 MB 栈线程,基线见 [docs/2026-10-25-perf-baseline.md](docs/2026-10-25-perf-baseline.md))、行内/块级图片与行内原子盒的 `DrawImage`/递归下发、多表级联与子资源并发抓取编排、`hit_test`/`hit_test_ex`/`hover_kind` 悬停语义与 `link_target` 点击命中、`document_title` 提取、**选区高亮按行插在页面背景与文字之间**)、`selection`(页面文本选区状态机:拖拽、Shift+点击、双击选词、Ctrl+A 全选;端点按源位置保存,resize 后重新解析;`Ctrl+C` 经 `arboard` 写系统剪贴板,失败不 panic)、`history`(会话历史栈:push/go_back/go_forward,新导航截断前进分支)、`render`(渲染隔离线程 + `catch_unwind` 兜底,panic 转 `RenderError::Panicked` 且线程存活可继续服务;**异步呈现(T9 实机抓到并修复)**:主线程 request 光栅作业即返回,线程完成后经 EventLoopProxy 发 FrameReady 唤醒上屏、积压结果只 present 最后一份——同步阻塞会让巨页帧(数十秒)把窗口拖入系统「无响应」,winit 0.30 把 WM_PAINT 直接映射为 RedrawRequested,配合 DWM 失效重发形成无限重绘风暴)、`ui`(自绘工具带状态机:后退/前进/刷新按钮(可用标志禁用态)、地址栏**编辑态**——光标/选区/`←→`/Home/End/Shift 扩选/Ctrl+A/Backspace/Delete、点击=聚焦+全选、超宽文本按光标横向滚动、`shortcut()` 纯映射 Chrome 快捷键含 Ctrl+A/C;**整形缓存(M7)**:按钮字形一次整形、URL 按(文本, 字号)缓存未变不 reshape、光标/选区前缀宽度按已整形字形 cluster 前缀累加零整形,计数测试钉住「URL 不变 redraw 0 次整形、每键 ≤1 次」)、`scrollbar`(滚动几何 + 拖拽状态机:thumb 抓取偏移拖动、轨道点击翻页、悬停配色)、`app`(winit 0.30 + wgpu 29 surface,Pixmap→纹理→全屏 blit 呈现,Rgba8Unorm 优先/BGRA 换色回退;页面滚动(滚轮/PageUp/PageDown/Home/End/方向键)+ 可拖滚动条、resize 合帧重排、页面文本拖拽/双击/Shift+点击选择与 Ctrl+A/C、链接在释放且未拖动时导航、点击页面让地址栏失焦、导航清空选区、悬停系统光标(链接手型/文本 I 形)、Ctrl+L/Ctrl+R/F5/Esc 与 Alt+方向键、`Arc` 接驳缝 + 30s 超时 + User-Agent、窗口标题随 ``;pad_rows 行对齐 staging 缓冲按(宽, 高, 步幅)复用(M6);**输入边界防护**:主文档响应体预算 10 MB、错误串收敛为「错误类别 + 状态码」(不回显 reqwest 原始错误——其内含目标 URL)、错误页 HTML 对 URL 与错误文本做实体转义(防标记注入与第三方子资源请求);**无头环境不可自动化测试**,实机验证)、`resources`(子资源编排 + **响应体字节预算**:文档/样式表 10 MB、图片 50 MB,`MAX_DOCUMENT_BODY_BYTES` 等公开常量,超预算按降级语义跳过——巨响应的分配失败是 abort,panic 兜底兜不住;解码侧像素面积另由 paint 预检控制;同 URL 多节点共享一份像素)。入口 `cargo run -p nexty-chrome --bin nexty`。 `nexty-html` 带 WPT tree-construction 比对 harness:语料钉在 `web-platform-tests/wpt` commit `5cd8e3fa`,当前 **1854/1959 通过**。剩余 105 条已逐条入基线,分两类:**88 条语料过时**——`processing-instructions.dat` 等期望产出 PI 节点,而现行 WHATWG §13.2.5 已无处理指令词法状态(`<?…>` 在 tag open state 走 bogus comment),html5ever 的产出与规范一致;**17 条非语料问题**——11 条 html5ever 树构建未跟进规范(`in select` 模式、`<selectedcontent>` 克隆、`<template>` 的 frameset-ok/form 指针语义),6 条需 JSRT 的 scripted 用例。分词器不换:MusKitty 分词器的处理指令状态实现的是规范已删除的特性,评估与否决理由见 [docs/decisions/2026-10-01-muskitty-tokenizer-rejected.md](docs/decisions/2026-10-01-muskitty-tokenizer-rejected.md)。比对方式与基线见 `crates/nexty-html/tests/tree_construction.rs`。 -八层骨架均已有内部实现,管线 network→html→dom→css→layout→paint→chrome 端到端连通(`cargo run -p nexty-chrome --bin nexty` 起窗口,地址栏输入 URL 导航,支持滚动与滚动条拖拽、链接点击、悬停光标、地址栏编辑与快捷键、后退/前进/刷新、页面文本选择与复制)。后续深化方向:paint 指令集扩展(text-decoration/链接下划线、圆角/渐变、body 背景传播,下一轮)、M3/M4 chrome 正确性小轮(加载竞态 / wgpu error handler)、layout 补齐 float 与 table(各自整轮;grid/定位/多行 flex 已由 taffy 落地)、vello_hybrid GPU 后端接入。**性能轮已落地**(H4 整形与断行缓存、M1 图片零拷贝、M5 级联桶索引、M6 resize 合帧与滚动场景缓存、M7 工具带整形缓存、M10/M12 克隆链与畸形输入;基线与实测数字见 [docs/2026-10-25-perf-baseline.md](docs/2026-10-25-perf-baseline.md),遗留瓶颈:滚动光栅化需视口裁剪/增量光栅,后续大项)。CSS Text 排版细化(justify / text-indent / letter-spacing / word-spacing / tab-size / pre-wrap 悬挂)已落地。分层与 crate 选型见 [docs/decisions/2026-10-01-crate-selection.md](docs/decisions/2026-10-01-crate-selection.md)。 +八层骨架均已有内部实现,管线 network→html→dom→css→layout→paint→chrome 端到端连通(`cargo run -p nexty-chrome --bin nexty` 起窗口,地址栏输入 URL 导航,支持滚动与滚动条拖拽、链接点击、悬停光标、地址栏编辑与快捷键、后退/前进/刷新、页面文本选择与复制)。后续深化方向:paint 指令集扩展(text-decoration/链接下划线、圆角/渐变、body 背景传播,下一轮)、M3/M4 chrome 正确性小轮(加载竞态 / wgpu error handler)、layout 补齐 table(整轮;grid/定位/多行 flex/float 已由 taffy 落地)、vello_hybrid GPU 后端接入。**性能轮已落地**(H4 整形与断行缓存、M1 图片零拷贝、M5 级联桶索引、M6 resize 合帧与滚动场景缓存、M7 工具带整形缓存、M10/M12 克隆链与畸形输入;基线与实测数字见 [docs/2026-10-25-perf-baseline.md](docs/2026-10-25-perf-baseline.md),遗留瓶颈:滚动光栅化需视口裁剪/增量光栅,后续大项)。CSS Text 排版细化(justify / text-indent / letter-spacing / word-spacing / tab-size / pre-wrap 悬挂)已落地。分层与 crate 选型见 [docs/decisions/2026-10-01-crate-selection.md](docs/decisions/2026-10-01-crate-selection.md)。 ## Build & Test Commands @@ -186,7 +186,7 @@ Nexty/ # 主仓库 (Ink-dark/Nexty),workspace | | `ua-stylesheet` | `ua` UA 默认样式表 | ✅ | | nexty-text | `shaping` | `TextShaper` / `ParleyTextShaper`(隐含 `font-resolution`) | ✅ | | | `font-resolution` | `FontResolver` / `ResolvedFont` | ✅ | -| nexty-layout | `block` | `block` 块级流(taffy 解算 + Fragment 回填,隐含 `inline`) | ✅ | +| nexty-layout | `block` | `block` 块级流(taffy 解算 + Fragment 回填 + 浮动环绕修正 pass,隐含 `inline`;taffy `float_layout` 常开) | ✅ | | | `inline` | `inline` 行内流与匿名块(断行永久自研) | ✅ | | | `flex` | flex 容器 blockify(tree_build)+ `Display::Flex` 映射(style_map),几何由 taffy flexbox 解算(隐含 `block`) | ✅ | | | `replaced` | `block::is_image_element` 块级 `<img>` 替换盒 | ✅ | diff --git a/crates/nexty-layout/tests/layout.rs b/crates/nexty-layout/tests/layout.rs index 57d0e6a..0e8a707 100644 --- a/crates/nexty-layout/tests/layout.rs +++ b/crates/nexty-layout/tests/layout.rs @@ -1771,6 +1771,38 @@ fn float_left_wraps_subsequent_text() { ); } +/// 浮动在祖先容器、文本在后代块(`<p>`)内:祖先 BFC 的浮动同样收缩后代 +/// 行盒(CSS 2.2 §9.5 的行盒规则不分块边界)。 +#[test] +fn ancestor_float_wraps_descendant_paragraph() { + let words = "word ".repeat(40); + let (document, root) = layout( + &format!( + "<body><div style=\"float: left; width: 100px; height: 60px\">F</div>\ + <p>{words}</p></body>" + ), + "p { margin: 0 }", + 400.0, + ); + let paragraph = find(&document, &root, "p").expect("paragraph fragment"); + let mut y = paragraph.border_box.y; + let mut beside = 0usize; + for line in ¶graph.lines { + if y < 60.0 - 0.01 { + let x = line + .runs + .first() + .and_then(|run| run.glyphs.first()) + .map(|glyph| glyph.x + paragraph.border_box.x) + .unwrap_or(f32::MAX); + assert!(x >= 100.0 - 0.01, "段内行让出浮动(y={y}, x={x})"); + beside += 1; + } + y += line.height; + } + assert!(beside >= 1, "浮动旁至少一行(实际 {beside})"); +} + /// 右浮动:浮动旁的行右缘收缩到浮动左缘之前。 #[test] fn float_right_shrinks_line_right_edge() { diff --git a/docs/decisions/2026-10-01-crate-selection.md b/docs/decisions/2026-10-01-crate-selection.md index b70d4ae..594a961 100644 --- a/docs/decisions/2026-10-01-crate-selection.md +++ b/docs/decisions/2026-10-01-crate-selection.md @@ -130,3 +130,8 @@ MusKitty 从零手写浏览器核心模块(HTML/CSS/Layout/Render/Network 全 - **swash 退出**:选型时假设文本整形栈为 `parley + swash + fontique`。落地时核实:parley 0.11 的整形后端是 `harfrust`(HarfBuzz 整形算法的 Rust 实现,纯 Rust、Apache-2.0),字体选择用 `fontique`,swash 不参与。`nexty-text` 只依赖 parley,swash 移出依赖树。 - **vello_hybrid 缓接**:GPU 后端需要 wgpu device/surface,只有 chrome 层能提供。本轮 `nexty-paint` 仅落地 `vello_cpu` 后端并摘除 vello_hybrid 依赖,`Rasterizer` trait 保留为双后端接缝;接入时按上文约束对齐 wgpu 版本(当前 vello_hybrid 0.2 → wgpu 29)。 - **nexty-text 的 `FontFamily` 处理**:CSS 字体族列表的解析(族名 / generic 关键字 / 回退顺序)直接交给 parley 的 `FontFamily::Source`,本层不重复解析。 + +## 修正记录(2026-10-31,float 轮) + +- **float 放置采用 taffy `float_layout`,不自研**:浮动放置、`clear`、块盒/BFC 避让与容器高度贡献(`FloatContext` / BFC 槽位 / `float_content_contribution`)由 taffy 0.14 的 `float_layout` feature 提供,`nexty-layout` 只做样式映射(`float`/`clear`)与 blockify 拦截(绝对/固定定位上 `float: none`;flex/grid item 由 taffy 算法忽略,等价于计算值 none)。 +- **上游边界:measure 叶没有行盒收缩**。taffy 的浮动实现只对**有子内容可下钻**的盒子收缩可用宽;run 叶(自研文本叶)是 measure 节点,拿不到浮动区间,行盒会与浮动重叠。`nexty-layout` 补一个**环绕修正 pass**:首轮解算后按 taffy 已放置的浮动矩形逐行收缩重排 run 叶行盒(`build_lines` 的 `LineConstraints.floats`),行数变化时回写叶定高再解算一轮(浮动尺寸与文本无关,一次迭代即固定点)。浮动矩形沿祖先 BFC 传播到后代 run 叶(跨块边界),遇建立新 BFC 的盒子截断。 diff --git a/docs/plans/2026-10-31-round-float.md b/docs/plans/2026-10-31-round-float.md index 76f3210..172aef1 100644 --- a/docs/plans/2026-10-31-round-float.md +++ b/docs/plans/2026-10-31-round-float.md @@ -72,3 +72,40 @@ float 优先于 table / position:fixed)。 ## 整轮退出条件 T1–T5 退出条件全部满足;`goal.md` 归档 + push;等用户验收。 + +--- + +## 归档结果(2026-10-31) + +**落地方式**(侦察后调整):taffy 0.14 自带 `float_layout`(浮动放置 / clear / +BFC 槽位 / 高度贡献),本轮启用该 feature 而非自研浮动放置。taffy 的上游边界是 +**measure 叶没有行盒收缩**(run 叶拿不到浮动区间,文本会与浮动重叠),由 +`nexty-layout` 的**环绕修正 pass** 补齐:首轮解算后按 taffy 已放置的浮动矩形 +逐行收缩重排 run 叶行盒,行数变化时回写叶定高再解算一轮(一次迭代固定点)。 +浮动矩形沿祖先 BFC 传播到后代 run 叶(跨 `<p>` 等块边界),遇新 BFC 截断。 + +**版本**:css 0.1.15(`float`/`clear` 解析)、layout 0.1.29(接线 + 环绕 pass + +跨容器传播修复)。 + +**commit**: +- `952d723` css:float/clear 解析(CSS 2.1 §9.5),不继承(0.1.15) +- `9821385` layout:启用 taffy float_layout + 样式映射 + 环绕 pass(0.1.28) +- `6d62b99` layout:浮动行盒的命中与选区几何测试 +- T5 收尾(本文档 + AGENTS.md + ADR + 跨容器传播修复) + +**测试**:layout 集成测试 +7(左右浮动环绕、clear、BFC 高度包含、双浮动并排、 +右侧行右缘收缩、图片浮动、祖先浮动影响后代段落);选区 +1(环绕行的命中与 +选区矩形让出浮动);全 workspace 绿。 + +**实机冒烟**(`.workbuddy/t3-test/float.html`,http://127.0.0.1:8931/): +左浮动 160×120 + 右浮动 120×90 图文环绕逐行收缩、第 5 行起回到全宽、`clear: +both` 段落在浮动下方、`overflow:hidden` 容器内文本让出内部浮动;双击选词 + +Ctrl+C + 滚动正常。**顺带确认的 paint 缺口**(非本轮):`background-color` +未下发绘制,验证浮动盒位置需用 `border`。 + +**修过的过程性缺陷**:首版环绕 pass 只处理「同容器的 run 叶」,实机抓到 +`<body>` 浮动 + `<p>` 文本不收缩——改为递归携带绝对坐标与活跃浮动表。 + +**遗留(下轮候选)**:行顶 y 判定不做行内跨区间细化(行跨入更窄区间时按行顶 +宽放置);浮动只按文档序判定「前置」,复杂交叠堆叠以 taffy 放置为准; +`float: inline-start/end` 未做;paint 的 background-color / 圆角 / 渐变仍缺。 From ec5ea1962521534775c7ad25171608b8906df322 Mon Sep 17 00:00:00 2001 From: zwork <zwork@local> Date: Sat, 31 Oct 2026 18:29:49 +0800 Subject: [PATCH 06/14] [dom] add K1 event model: Event/EventTarget/propagation/data plane/EventLoop, WHATWG DOM 2.9 simplified (0.1.4) --- ...sion_164476f9d97ffaabe4f6dc9715b6aad5.json | 1 + ...24fdb88882b47c23cc0e0c80a30c7d53759.source | 596 +++++++++++++ ...f9d97ffaabe4f6dc9715b6aad5-5e056c09de.json | 14 + crates/nexty-dom/Cargo.toml | 10 +- crates/nexty-dom/src/event/data.rs | 177 ++++ crates/nexty-dom/src/event/event_loop.rs | 144 ++++ crates/nexty-dom/src/event/mod.rs | 804 ++++++++++++++++++ crates/nexty-dom/src/lib.rs | 16 +- crates/nexty-dom/src/tree.rs | 7 + 9 files changed, 1763 insertions(+), 6 deletions(-) create mode 100644 crates/nexty-dom/.mimosa/hook-state/session_164476f9d97ffaabe4f6dc9715b6aad5.json create mode 100644 crates/nexty-dom/.mimosa/hook-state/session_164476f9d97ffaabe4f6dc9715b6aad5.mvmexexs-91620-47163f59c9.baseline/b1a35a68f14e696205874893c07fd24fdb88882b47c23cc0e0c80a30c7d53759.source create mode 100644 crates/nexty-dom/.mimosa/hook-status/session_164476f9d97ffaabe4f6dc9715b6aad5-5e056c09de.json create mode 100644 crates/nexty-dom/src/event/data.rs create mode 100644 crates/nexty-dom/src/event/event_loop.rs create mode 100644 crates/nexty-dom/src/event/mod.rs diff --git a/crates/nexty-dom/.mimosa/hook-state/session_164476f9d97ffaabe4f6dc9715b6aad5.json b/crates/nexty-dom/.mimosa/hook-state/session_164476f9d97ffaabe4f6dc9715b6aad5.json new file mode 100644 index 0000000..0c88041 --- /dev/null +++ b/crates/nexty-dom/.mimosa/hook-state/session_164476f9d97ffaabe4f6dc9715b6aad5.json @@ -0,0 +1 @@ +{"touched":["D:\\Nexty\\crates\\nexty-dom\\src\\lib.rs"],"bashMutation":false,"reportedFindings":[],"findingEvents":[],"baseline":{"storageId":"mvmexexs-91620-47163f59c9","createdAt":"2026-10-24T13:06:32.032Z","files":{"src/lib.rs":{"existed":true,"snapshot":"b1a35a68f14e696205874893c07fd24fdb88882b47c23cc0e0c80a30c7d53759.source"}},"complete":false,"candidateLimit":5000,"discoveredFiles":0,"capturedFiles":1,"truncated":false,"omittedAtLeast":0,"firstOmitted":"","errors":[{"stage":"baseline-capture","target":".","reason":"global task baseline was unavailable; captured only the touched file"},{"stage":"baseline-snapshot","target":"../nexty-html/src/lib.rs","reason":"file is outside project"},{"stage":"baseline-snapshot","target":"../nexty-html/src/lib.rs","reason":"file is outside project"},{"stage":"baseline-snapshot","target":"../nexty-html/src/lib.rs","reason":"file is outside project"},{"stage":"baseline-snapshot","target":"../nexty-html/src/lib.rs","reason":"file is outside project"},{"stage":"baseline-snapshot","target":"../nexty-html/src/lib.rs","reason":"file is outside project"}]},"stateErrors":[],"omittedReportedFindings":0,"omittedFindingEvents":0,"processing":null,"updatedAt":"2026-10-24T13:12:32.202Z"} \ No newline at end of file diff --git a/crates/nexty-dom/.mimosa/hook-state/session_164476f9d97ffaabe4f6dc9715b6aad5.mvmexexs-91620-47163f59c9.baseline/b1a35a68f14e696205874893c07fd24fdb88882b47c23cc0e0c80a30c7d53759.source b/crates/nexty-dom/.mimosa/hook-state/session_164476f9d97ffaabe4f6dc9715b6aad5.mvmexexs-91620-47163f59c9.baseline/b1a35a68f14e696205874893c07fd24fdb88882b47c23cc0e0c80a30c7d53759.source new file mode 100644 index 0000000..12eec3d --- /dev/null +++ b/crates/nexty-dom/.mimosa/hook-state/session_164476f9d97ffaabe4f6dc9715b6aad5.mvmexexs-91620-47163f59c9.baseline/b1a35a68f14e696205874893c07fd24fdb88882b47c23cc0e0c80a30c7d53759.source @@ -0,0 +1,596 @@ +//! Nexty 自研 arena DOM。 +//! +//! 本层不依赖任何外部 crate。选型时排除了现成方案:`kuchiki` 式的 Rc 不可变树 +//! 与 DOM 可变性冲突,`ego-tree` / `indextree` 仍需自接 JSRT 绑定层;性能评估 +//! 显示 arena 在构建、遍历、随机访问、兄弟遍历与内存分配上全面领先。 +//! 决策见 `docs/decisions/2026-10-01-crate-selection.md`。 +//! +//! 行为 ground truth:[WHATWG DOM Standard](https://dom.spec.whatwg.org/)。 +//! 节点类型见 `node` 模块,树变更算法见 `tree` 模块。 +//! +//! 已落地:节点类型(含 doctype / fragment / 处理指令)与元素命名空间、 +//! 树变更算法(insert / remove / replace / clone / normalize)。JS 绑定层尚未接入。 +//! +//! **Feature**:节点数据层(`node`)与树变更算法(`tree`)分别受feature 控制, +//! 默认全开;`tree` 隐含 `node`。 + +#![forbid(unsafe_code)] + +#[cfg(feature = "node")] +mod node; +#[cfg(feature = "tree")] +mod tree; + +#[cfg(feature = "node")] +pub use node::{ + Attribute, DocumentTypeData, DomError, ElementData, Namespace, NodeId, NodeKind, + ProcessingInstructionData, QuirksMode, +}; +#[cfg(feature = "tree")] +pub use tree::{Children, Document, MAX_TREE_DEPTH}; + +#[cfg(all(test, feature = "tree"))] +mod tests { + use super::*; + + fn element(doc: &mut Document, name: &str) -> NodeId { + doc.create_node(NodeKind::Element(ElementData { + name: name.into(), + namespace: Namespace::Html, + attributes: Vec::new(), + })) + } + + fn text(doc: &mut Document, data: &str) -> NodeId { + doc.create_node(NodeKind::Text(data.into())) + } + + fn children_of(doc: &Document, id: NodeId) -> Vec<NodeId> { + doc.children(id).collect() + } + + #[test] + fn new_document_contains_root_only() { + let doc = Document::new(); + assert_eq!(doc.node_count(), 1); + assert_eq!(doc.node(doc.root()), Some(&NodeKind::Document)); + assert_eq!(doc.quirks_mode(), QuirksMode::NoQuirks); + } + + #[test] + fn created_node_is_readable_and_distinct_from_root() { + let mut doc = Document::new(); + let id = doc.create_node(NodeKind::Text("hi".into())); + assert_ne!(id, doc.root()); + assert_eq!(doc.node(id), Some(&NodeKind::Text("hi".into()))); + assert_eq!(doc.node_count(), 2); + } + + #[test] + fn node_mut_replaces_kind() { + let mut doc = Document::new(); + let id = doc.create_node(NodeKind::Comment("old".into())); + if let Some(kind) = doc.node_mut(id) { + *kind = NodeKind::Comment("new".into()); + } + assert_eq!(doc.node(id), Some(&NodeKind::Comment("new".into()))); + } + + #[test] + fn unknown_index_returns_none() { + let doc = Document::new(); + assert_eq!(doc.node(NodeId(99)), None); + assert_eq!(doc.parent(NodeId(99)), None); + } + + #[test] + fn element_data_keeps_attribute_order_and_namespace() { + let mut doc = Document::new(); + let id = doc.create_node(NodeKind::Element(ElementData { + name: "a".into(), + namespace: Namespace::Svg, + attributes: vec![ + Attribute { + name: "href".into(), + namespace: Namespace::None, + value: "/x".into(), + }, + Attribute { + name: "href".into(), + namespace: Namespace::Other("http://www.w3.org/1999/xlink".into()), + value: "/y".into(), + }, + ], + })); + let Some(NodeKind::Element(data)) = doc.node(id) else { + panic!("expected element node"); + }; + assert_eq!(data.namespace, Namespace::Svg); + assert_eq!(data.attributes[0].namespace, Namespace::None); + assert_eq!( + data.attributes[1].namespace, + Namespace::Other("http://www.w3.org/1999/xlink".into()) + ); + } + + #[test] + fn append_child_links_parent_and_siblings() { + let mut doc = Document::new(); + let parent = element(&mut doc, "div"); + let a = text(&mut doc, "a"); + let b = text(&mut doc, "b"); + let c = text(&mut doc, "c"); + + doc.append_child(a, parent).unwrap(); + doc.append_child(b, parent).unwrap(); + doc.append_child(c, parent).unwrap(); + + assert_eq!(doc.parent(a), Some(parent)); + assert_eq!(doc.first_child(parent), Some(a)); + assert_eq!(doc.last_child(parent), Some(c)); + assert_eq!(children_of(&doc, parent), vec![a, b, c]); + assert_eq!(doc.next_sibling(a), Some(b)); + assert_eq!(doc.previous_sibling(b), Some(a)); + assert_eq!(doc.next_sibling(c), None); + } + + #[test] + fn insert_before_places_node_at_reference() { + let mut doc = Document::new(); + let parent = element(&mut doc, "ul"); + let a = element(&mut doc, "li"); + let b = element(&mut doc, "li"); + let mid = element(&mut doc, "li"); + + doc.append_child(a, parent).unwrap(); + doc.append_child(b, parent).unwrap(); + doc.insert_before(mid, parent, Some(b)).unwrap(); + + assert_eq!(children_of(&doc, parent), vec![a, mid, b]); + } + + #[test] + fn insert_before_self_is_noop() { + let mut doc = Document::new(); + let parent = element(&mut doc, "div"); + let a = element(&mut doc, "span"); + let b = element(&mut doc, "span"); + doc.append_child(a, parent).unwrap(); + doc.append_child(b, parent).unwrap(); + + doc.insert_before(a, parent, Some(a)).unwrap(); + assert_eq!(children_of(&doc, parent), vec![a, b]); + } + + #[test] + fn moving_node_detaches_from_old_parent() { + let mut doc = Document::new(); + let first = element(&mut doc, "div"); + let second = element(&mut doc, "div"); + let moved = element(&mut doc, "p"); + + doc.append_child(moved, first).unwrap(); + doc.append_child(moved, second).unwrap(); + + assert_eq!(children_of(&doc, first), Vec::<NodeId>::new()); + assert_eq!(children_of(&doc, second), vec![moved]); + assert_eq!(doc.parent(moved), Some(second)); + } + + #[test] + fn fragment_insert_expands_children_in_order() { + let mut doc = Document::new(); + let parent = element(&mut doc, "div"); + let fragment = doc.create_node(NodeKind::DocumentFragment); + let a = text(&mut doc, "a"); + let b = text(&mut doc, "b"); + doc.append_child(a, fragment).unwrap(); + doc.append_child(b, fragment).unwrap(); + + doc.append_child(fragment, parent).unwrap(); + + assert_eq!(children_of(&doc, fragment), Vec::<NodeId>::new()); + assert_eq!(children_of(&doc, parent), vec![a, b]); + assert_eq!(doc.parent(a), Some(parent)); + } + + #[test] + fn empty_fragment_insert_is_noop() { + let mut doc = Document::new(); + let parent = element(&mut doc, "div"); + let fragment = doc.create_node(NodeKind::DocumentFragment); + doc.append_child(fragment, parent).unwrap(); + assert_eq!(children_of(&doc, parent), Vec::<NodeId>::new()); + } + + #[test] + fn remove_child_clears_links_and_reports_missing_parent() { + let mut doc = Document::new(); + let parent = element(&mut doc, "div"); + let a = element(&mut doc, "span"); + let b = element(&mut doc, "span"); + doc.append_child(a, parent).unwrap(); + doc.append_child(b, parent).unwrap(); + + doc.remove_child(a, parent).unwrap(); + assert_eq!(doc.parent(a), None); + assert_eq!(doc.next_sibling(a), None); + assert_eq!(children_of(&doc, parent), vec![b]); + assert_eq!(doc.first_child(parent), Some(b)); + assert_eq!(doc.previous_sibling(b), None); + assert_eq!(doc.remove_child(a, parent), Err(DomError::NotFound)); + } + + #[test] + fn replace_child_swaps_in_place() { + let mut doc = Document::new(); + let parent = element(&mut doc, "div"); + let a = element(&mut doc, "span"); + let b = element(&mut doc, "span"); + let replacement = element(&mut doc, "em"); + doc.append_child(a, parent).unwrap(); + doc.append_child(b, parent).unwrap(); + + doc.replace_child(a, replacement, parent).unwrap(); + assert_eq!(children_of(&doc, parent), vec![replacement, b]); + assert_eq!(doc.parent(a), None); + } + + #[test] + fn replace_all_clears_then_inserts() { + let mut doc = Document::new(); + let parent = element(&mut doc, "div"); + let a = element(&mut doc, "span"); + let b = element(&mut doc, "span"); + let fresh = text(&mut doc, "fresh"); + doc.append_child(a, parent).unwrap(); + doc.append_child(b, parent).unwrap(); + + doc.replace_all(Some(fresh), parent); + assert_eq!(children_of(&doc, parent), vec![fresh]); + assert_eq!(doc.parent(a), None); + + doc.replace_all(None, parent); + assert_eq!(children_of(&doc, parent), Vec::<NodeId>::new()); + } + + #[test] + fn insert_into_own_subtree_is_rejected() { + let mut doc = Document::new(); + let parent = element(&mut doc, "div"); + let child = element(&mut doc, "span"); + doc.append_child(child, parent).unwrap(); + + assert_eq!( + doc.append_child(parent, child), + Err(DomError::HierarchyRequest) + ); + } + + #[test] + fn insert_with_foreign_reference_is_not_found() { + let mut doc = Document::new(); + let parent = element(&mut doc, "div"); + let other = element(&mut doc, "div"); + let loose = element(&mut doc, "span"); + + assert_eq!( + doc.insert_before(loose, parent, Some(other)), + Err(DomError::NotFound) + ); + } + + #[test] + fn document_rejects_second_element_and_text_children() { + let mut doc = Document::new(); + let root = doc.root(); + let html = element(&mut doc, "html"); + doc.append_child(html, root).unwrap(); + + let second = element(&mut doc, "html"); + assert_eq!( + doc.append_child(second, root), + Err(DomError::HierarchyRequest) + ); + + let text = text(&mut doc, "nope"); + assert_eq!( + doc.append_child(text, root), + Err(DomError::HierarchyRequest) + ); + } + + #[test] + fn document_rejects_doctype_after_element() { + let mut doc = Document::new(); + let root = doc.root(); + let html = element(&mut doc, "html"); + doc.append_child(html, root).unwrap(); + + let doctype = doc.create_node(NodeKind::Doctype(DocumentTypeData { + name: "html".into(), + public_id: String::new(), + system_id: String::new(), + })); + assert_eq!( + doc.append_child(doctype, root), + Err(DomError::HierarchyRequest) + ); + } + + #[test] + fn doctype_before_element_is_allowed_once() { + let mut doc = Document::new(); + let root = doc.root(); + let doctype = doc.create_node(NodeKind::Doctype(DocumentTypeData { + name: "html".into(), + public_id: String::new(), + system_id: String::new(), + })); + doc.append_child(doctype, root).unwrap(); + + let html = element(&mut doc, "html"); + doc.append_child(html, root).unwrap(); + assert_eq!(children_of(&doc, root), vec![doctype, html]); + + let duplicate = doc.create_node(NodeKind::Doctype(DocumentTypeData::default())); + assert_eq!( + doc.append_child(duplicate, root), + Err(DomError::HierarchyRequest) + ); + } + + #[test] + fn doctype_rejected_outside_document() { + let mut doc = Document::new(); + let parent = element(&mut doc, "div"); + let doctype = doc.create_node(NodeKind::Doctype(DocumentTypeData::default())); + assert_eq!( + doc.append_child(doctype, parent), + Err(DomError::HierarchyRequest) + ); + } + + #[test] + fn clone_shallow_copies_data_but_not_children() { + let mut doc = Document::new(); + let source = doc.create_node(NodeKind::Element(ElementData { + name: "a".into(), + namespace: Namespace::Svg, + attributes: vec![Attribute { + name: "href".into(), + namespace: Namespace::None, + value: "/x".into(), + }], + })); + let child = text(&mut doc, "text"); + doc.append_child(child, source).unwrap(); + + let copy = doc.clone_node(source, false); + assert_ne!(copy, source); + assert_eq!(doc.node(copy), doc.node(source)); + assert_eq!(children_of(&doc, copy), Vec::<NodeId>::new()); + assert_eq!(doc.parent(copy), None); + } + + #[test] + fn clone_subtree_copies_descendants() { + let mut doc = Document::new(); + let source = element(&mut doc, "ul"); + let item = element(&mut doc, "li"); + let label = text(&mut doc, "one"); + doc.append_child(item, source).unwrap(); + doc.append_child(label, item).unwrap(); + + let copy = doc.clone_node(source, true); + let copied_item = doc.first_child(copy).unwrap(); + let copied_label = doc.first_child(copied_item).unwrap(); + assert_eq!(doc.node(copied_item), doc.node(item)); + assert_eq!(doc.node(copied_label), Some(&NodeKind::Text("one".into()))); + assert_ne!(copied_item, item); + } + + #[test] + fn clone_template_gets_fresh_contents() { + let mut doc = Document::new(); + let template = element(&mut doc, "template"); + let contents = doc.create_node(NodeKind::DocumentFragment); + let inner = element(&mut doc, "span"); + doc.append_child(inner, contents).unwrap(); + doc.set_template_contents(template, contents); + + let shallow = doc.clone_node(template, false); + let shallow_contents = doc.template_contents(shallow).unwrap(); + assert_ne!(shallow_contents, contents); + assert_eq!(children_of(&doc, shallow_contents), Vec::<NodeId>::new()); + + let deep = doc.clone_node(template, true); + let deep_contents = doc.template_contents(deep).unwrap(); + assert_eq!(children_of(&doc, deep_contents).len(), 1); + } + + #[test] + fn normalize_merges_adjacent_text_and_drops_empty() { + let mut doc = Document::new(); + let parent = element(&mut doc, "p"); + let a = text(&mut doc, "a"); + let empty = text(&mut doc, ""); + let b = text(&mut doc, "b"); + let c = text(&mut doc, "c"); + let br = element(&mut doc, "br"); + let d = text(&mut doc, "d"); + + for node in [a, empty, b, c, br, d] { + doc.append_child(node, parent).unwrap(); + } + + doc.normalize(parent); + + assert_eq!(doc.node(a), Some(&NodeKind::Text("abc".into()))); + assert_eq!(children_of(&doc, parent), vec![a, br, d]); + assert_eq!(doc.parent(empty), None); + assert_eq!(doc.parent(c), None); + } + + #[test] + fn normalize_descends_into_subtrees() { + let mut doc = Document::new(); + let outer = element(&mut doc, "div"); + let inner = element(&mut doc, "p"); + doc.append_child(inner, outer).unwrap(); + let a = text(&mut doc, "x"); + let b = text(&mut doc, "y"); + doc.append_child(a, inner).unwrap(); + doc.append_child(b, inner).unwrap(); + + doc.normalize(outer); + assert_eq!(doc.node(a), Some(&NodeKind::Text("xy".into()))); + assert_eq!(children_of(&doc, inner), vec![a]); + } + + #[test] + fn quirks_mode_round_trips() { + let mut doc = Document::new(); + doc.set_quirks_mode(QuirksMode::Quirks); + assert_eq!(doc.quirks_mode(), QuirksMode::Quirks); + } + + // ---- 树深度维护(不可信输入防线的地基) ---- + + #[test] + fn depth_is_zero_for_root_and_grows_per_level() { + let mut doc = Document::new(); + let root = doc.root(); + assert_eq!(doc.depth(root), 0); + + let html = element(&mut doc, "html"); + let body = element(&mut doc, "body"); + let div = element(&mut doc, "div"); + doc.append_child(html, root).unwrap(); + doc.append_child(body, html).unwrap(); + doc.append_child(div, body).unwrap(); + + assert_eq!(doc.depth(html), 1); + assert_eq!(doc.depth(body), 2); + assert_eq!(doc.depth(div), 3); + } + + #[test] + fn insert_before_assigns_reference_depth() { + let mut doc = Document::new(); + let parent = element(&mut doc, "div"); + let a = element(&mut doc, "span"); + let b = element(&mut doc, "span"); + doc.append_child(a, parent).unwrap(); + doc.insert_before(b, parent, Some(a)).unwrap(); + + assert_eq!(doc.depth(parent), 1); + assert_eq!(doc.depth(b), 2); + } + + #[test] + fn replace_child_assigns_replacement_depth() { + let mut doc = Document::new(); + let root = doc.root(); + let a = element(&mut doc, "div"); + let b = element(&mut doc, "div"); + doc.append_child(a, root).unwrap(); + doc.replace_child(a, b, root).unwrap(); + + assert_eq!(doc.depth(b), 1); + assert_eq!(doc.depth(a), 1, "detach 不清深度,游离节点值无意义"); + } + + #[test] + fn relinking_recomputes_depth_from_new_parent() { + let mut doc = Document::new(); + let shallow = element(&mut doc, "div"); + let deep = element(&mut doc, "div"); + let inner = element(&mut doc, "div"); + doc.append_child(inner, deep).unwrap(); + let grand = element(&mut doc, "div"); + doc.append_child(grand, inner).unwrap(); + assert_eq!(doc.depth(inner), 2); + + // 移动到浅层父节点:深度按新父重算 + doc.append_child(inner, shallow).unwrap(); + assert_eq!(doc.depth(inner), 2); + assert_eq!(doc.depth(grand), 3, "子树整体平移"); + + // 再挂到根下:回到深度 1,子树跟着平移 + doc.append_child(inner, doc.root()).unwrap(); + assert_eq!(doc.depth(inner), 1); + assert_eq!(doc.depth(grand), 2); + } + + #[test] + fn moved_subtree_depths_track_new_position() { + let mut doc = Document::new(); + let source = element(&mut doc, "ul"); + let item = element(&mut doc, "li"); + let label = element(&mut doc, "em"); + doc.append_child(item, source).unwrap(); + doc.append_child(label, item).unwrap(); + + let target = element(&mut doc, "div"); + let shell = element(&mut doc, "section"); + doc.append_child(shell, target).unwrap(); + doc.append_child(shell, doc.root()).unwrap(); + assert_eq!(doc.depth(shell), 1); + + // 整棵子树挂到 shell 下:全部按新位置重算 + doc.append_child(item, shell).unwrap(); + assert_eq!(doc.depth(item), 2); + assert_eq!(doc.depth(label), 3); + } + + #[test] + fn fragment_insert_assigns_children_depths() { + let mut doc = Document::new(); + let parent = element(&mut doc, "div"); + let fragment = doc.create_node(NodeKind::DocumentFragment); + let a = element(&mut doc, "span"); + doc.append_child(a, fragment).unwrap(); + + doc.append_child(fragment, parent).unwrap(); + assert_eq!(doc.depth(a), 2); + } + + #[test] + fn template_contents_depth_restarts_from_zero() { + let mut doc = Document::new(); + let root = doc.root(); + let deep = element(&mut doc, "div"); + let mut current = deep; + doc.append_child(deep, root).unwrap(); + for _ in 0..10 { + let next = element(&mut doc, "div"); + doc.append_child(next, current).unwrap(); + current = next; + } + assert_eq!(doc.depth(current), 11); + + let template = element(&mut doc, "template"); + doc.append_child(template, current).unwrap(); + let contents = doc.create_node(NodeKind::DocumentFragment); + let inner = element(&mut doc, "span"); + doc.append_child(inner, contents).unwrap(); + doc.set_template_contents(template, contents); + + assert_eq!(doc.depth(contents), 0, "模板内容片段独立起算"); + assert_eq!(doc.depth(inner), 1); + } + + #[test] + fn deep_chain_well_under_max_depth_stays_consistent() { + let mut doc = Document::new(); + let mut current = doc.root(); + for i in 0..(MAX_TREE_DEPTH + 64) { + let node = element(&mut doc, "div"); + doc.append_child(node, current).unwrap(); + current = node; + assert_eq!(doc.depth(current), (i + 1) as u32); + } + assert_eq!(doc.depth(current), (MAX_TREE_DEPTH + 64) as u32); + } +} diff --git a/crates/nexty-dom/.mimosa/hook-status/session_164476f9d97ffaabe4f6dc9715b6aad5-5e056c09de.json b/crates/nexty-dom/.mimosa/hook-status/session_164476f9d97ffaabe4f6dc9715b6aad5-5e056c09de.json new file mode 100644 index 0000000..32b061c --- /dev/null +++ b/crates/nexty-dom/.mimosa/hook-status/session_164476f9d97ffaabe4f6dc9715b6aad5-5e056c09de.json @@ -0,0 +1,14 @@ +{ + "schemaVersion": "mimosa-hook-status/v1", + "recordedAt": "2026-10-24T13:12:34.751Z", + "sessionId": "session_164476f9d97ffaabe4f6dc9715b6aad5", + "event": "PostToolUse", + "toolName": "Edit", + "file": "D:\\Nexty\\crates\\nexty-html\\src\\lib.rs", + "outcome": "inconclusive", + "coverage": "partial", + "findingCount": 0, + "durationMs": 17, + "hostState": "hook_complete", + "reportHint": ".mimosa/reports/" +} diff --git a/crates/nexty-dom/Cargo.toml b/crates/nexty-dom/Cargo.toml index 6bd189d..6833cfb 100644 --- a/crates/nexty-dom/Cargo.toml +++ b/crates/nexty-dom/Cargo.toml @@ -1,7 +1,7 @@ [package] name = "nexty-dom" description = "Nexty 自研 arena DOM" -version = "0.1.3" +version = "0.1.4" edition.workspace = true license.workspace = true repository.workspace = true @@ -9,11 +9,15 @@ rust-version.workspace = true [features] # 默认开启全部已实现能力;DOM 是所有层的地基,默认必须全开。 -default = ["node", "tree"] +default = ["node", "tree", "event"] # 节点数据层:NodeKind / ElementData / Attribute / Namespace / QuirksMode 等。 node = [] # 树变更算法:Document / Children(pre-insert / insert / remove / replace / # clone / normalize)。依赖节点数据层,故隐含 node。 tree = ["node"] +# 事件模型(WHATWG DOM §2.9 简化档):Event / 监听器注册表(Document 侧容器)/ +# 传播算法 / 事件数据面 / EventLoop 与生命周期事件。传播沿祖先链走、监听器 +# 容器挂在 Document 上,故隐含 tree。 +event = ["tree"] -[dependencies] \ No newline at end of file +[dependencies] diff --git a/crates/nexty-dom/src/event/data.rs b/crates/nexty-dom/src/event/data.rs new file mode 100644 index 0000000..0e22d4b --- /dev/null +++ b/crates/nexty-dom/src/event/data.rs @@ -0,0 +1,177 @@ +//! 事件数据面([UI Events](https://www.w3.org/TR/uievents/) 简化档)。 +//! +//! 各类型组合核心 [`Event`](crate::Event) 与自身数据字段:派发传 +//! `&mut ev.event`(监听器只见核心面,见 `event` 模块偏差清单),派发方随后 +//! 读自身数据字段与 `default_prevented` 决定默认动作(先派发后默认)。 +//! +//! 偏差:`WheelEvent` 不含鼠标坐标面(DOM 中 WheelEvent 继承 MouseEvent), +//! 不建模 delta_z;`FocusEvent` 仅类型面(无派发点,K10 补),不建模 +//! related_target;`UIEvent` 的 view 属性未建模(无 window 对象)。 + +use super::Event; + +/// UIEvent 数据面([UI Events §5.1](https://www.w3.org/TR/uievents/#interface-uievent))。 +#[derive(Debug)] +pub struct UiEvent { + /// 核心 Event 面:派发与监听回调都作用于此。 + pub event: Event, + /// `detail` 属性:实现相关细节,鼠标类事件为同一位置的点击计数。 + pub detail: u32, +} + +impl UiEvent { + /// 构造 UIEvent,数据字段取零值,由派发方按需填充。 + #[must_use] + pub fn new(type_: impl Into<String>, bubbles: bool, cancelable: bool) -> Self { + Self { + event: Event::new(type_, bubbles, cancelable), + detail: 0, + } + } +} + +/// MouseEvent 数据面([UI Events §5.2](https://www.w3.org/TR/uievents/#interface-mouseevent))。 +#[derive(Debug)] +pub struct MouseEvent { + /// 核心 Event 面:派发与监听回调都作用于此。 + pub event: Event, + /// `detail` 属性:同一位置的点击计数(mousedown/up 为 1,dblclick 为 2)。 + pub detail: u32, + /// `screenX`:相对屏幕原点的横坐标。 + pub screen_x: i32, + /// `screenY`:相对屏幕原点的纵坐标。 + pub screen_y: i32, + /// `clientX`:相对视口的横坐标(命中测试结果)。 + pub client_x: i32, + /// `clientY`:相对视口的纵坐标。 + pub client_y: i32, + /// `button`:按下/释放的按键——0 主、1 中、2 次。 + pub button: u16, + /// `buttons`:当前按住位掩码——bit0 主、bit1 中、bit2 次。 + pub buttons: u16, + /// `ctrlKey`。 + pub ctrl_key: bool, + /// `shiftKey`。 + pub shift_key: bool, + /// `altKey`。 + pub alt_key: bool, + /// `metaKey`。 + pub meta_key: bool, +} + +impl MouseEvent { + /// 构造 MouseEvent:button=0(主键)、坐标与修饰键零值,由派发方按命中 + /// 测试结果填充。 + #[must_use] + pub fn new(type_: impl Into<String>, bubbles: bool, cancelable: bool) -> Self { + Self { + event: Event::new(type_, bubbles, cancelable), + detail: 0, + screen_x: 0, + screen_y: 0, + client_x: 0, + client_y: 0, + button: 0, + buttons: 0, + ctrl_key: false, + shift_key: false, + alt_key: false, + meta_key: false, + } + } +} + +/// KeyboardEvent 数据面([UI Events §6](https://www.w3.org/TR/uievents/#events-keyboard-events))。 +#[derive(Debug)] +pub struct KeyboardEvent { + /// 核心 Event 面:派发与监听回调都作用于此。 + pub event: Event, + /// `key` 属性:按键对应的键值字符串(如 `"a"`、`"Enter"`)。 + pub key: String, + /// `code` 属性:物理键位(如 `"KeyA"`、`"ArrowDown"`)。 + pub code: String, + /// `ctrlKey`。 + pub ctrl_key: bool, + /// `shiftKey`。 + pub shift_key: bool, + /// `altKey`。 + pub alt_key: bool, + /// `metaKey`。 + pub meta_key: bool, + /// `repeat`:持续按住触发的自动重复。 + pub repeat: bool, +} + +impl KeyboardEvent { + /// 构造 KeyboardEvent:key / code 为空串、修饰键与 repeat 零值,由派发方填充。 + #[must_use] + pub fn new(type_: impl Into<String>, bubbles: bool, cancelable: bool) -> Self { + Self { + event: Event::new(type_, bubbles, cancelable), + key: String::new(), + code: String::new(), + ctrl_key: false, + shift_key: false, + alt_key: false, + meta_key: false, + repeat: false, + } + } +} + +/// 滚动增量单位(UI Events +/// [WheelEvent 的 deltaMode](https://www.w3.org/TR/uievents/#dom-wheelevent-deltamode))。 +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +pub enum DeltaMode { + /// `DOM_DELTA_PIXEL`。 + Pixel, + /// `DOM_DELTA_LINE`。 + Line, + /// `DOM_DELTA_PAGE`。 + Page, +} + +/// WheelEvent 数据面([UI Events §5.3](https://www.w3.org/TR/uievents/#interface-wheelevent))。 +#[derive(Debug)] +pub struct WheelEvent { + /// 核心 Event 面:派发与监听回调都作用于此。 + pub event: Event, + /// `deltaX`:横向滚动增量。 + pub delta_x: f64, + /// `deltaY`:纵向滚动增量。 + pub delta_y: f64, + /// `deltaMode`:增量单位。 + pub delta_mode: DeltaMode, +} + +impl WheelEvent { + /// 构造 WheelEvent:增量为 0、单位为 Pixel,由派发方填充。 + #[must_use] + pub fn new(type_: impl Into<String>, bubbles: bool, cancelable: bool) -> Self { + Self { + event: Event::new(type_, bubbles, cancelable), + delta_x: 0.0, + delta_y: 0.0, + delta_mode: DeltaMode::Pixel, + } + } +} + +/// FocusEvent 数据面([UI Events §5.4](https://www.w3.org/TR/uievents/#interface-focusevent))。 +/// +/// 本轮仅类型面:无派发点(K10 焦点模型补),不建模 related_target。 +#[derive(Debug)] +pub struct FocusEvent { + /// 核心 Event 面。 + pub event: Event, +} + +impl FocusEvent { + /// 构造 FocusEvent。 + #[must_use] + pub fn new(type_: impl Into<String>, bubbles: bool, cancelable: bool) -> Self { + Self { + event: Event::new(type_, bubbles, cancelable), + } + } +} diff --git a/crates/nexty-dom/src/event/event_loop.rs b/crates/nexty-dom/src/event/event_loop.rs new file mode 100644 index 0000000..df3237f --- /dev/null +++ b/crates/nexty-dom/src/event/event_loop.rs @@ -0,0 +1,144 @@ +//! 事件循环:FIFO 宏任务队列([HTML §8.1 event loops] +//! (https://html.spec.whatwg.org/multipage/webappapis.html#event-loops) 简化档)。 +//! +//! - [`Task`]:宏任务的自身 `FnOnce` 包装类型,运行时拿到 [`TaskContext`]—— +//! Document 访问入口 + 继续投递任务的唯一通道。 +//! - [`EventLoop::post_task`] 投递到队尾;[`EventLoop::run_pending_tasks`] +//! FIFO 逐个执行,当前任务跑完才取下一个——任务执行中投递的任务只入队, +//! 由同一循环在其后继续执行,不重入(任务拿不到队列的执行权,结构上排除 +//! 递归排空)。 +//! - 微任务队列只留接口空位:K5(JS 运行时)接入时补「每任务后的微任务检查 +//! 点」;当前无微任务源,不预留存储(接口缝隙即 [`TaskContext`],届时在此 +//! 增补微任务投递与执行点)。 + +use std::collections::VecDeque; +use std::fmt; + +use crate::Document; + +/// 宏任务:自身 `FnOnce` 包装类型(HTML +/// [task](https://html.spec.whatwg.org/multipage/webappapis.html#concept-task) +/// 简化档)。 +/// +/// 任务体签名固定为 `FnOnce(&mut TaskContext<'_>)`:运行时拿 Document 访问与 +/// 继续投递任务的入口。 +pub struct Task(Box<dyn for<'a, 'b> FnOnce(&'b mut TaskContext<'a>) + 'static>); + +impl Task { + /// 把闭包包装为任务。 + #[must_use] + pub fn new<F>(run: F) -> Self + where + F: for<'a, 'b> FnOnce(&'b mut TaskContext<'a>) + 'static, + { + Self(Box::new(run)) + } +} + +impl fmt::Debug for Task { + fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { + f.debug_struct("Task").finish_non_exhaustive() + } +} + +/// 单个任务的运行上下文:Document 访问 + 任务内投递后续任务的通道。 +pub struct TaskContext<'a> { + doc: &'a mut Document, + tasks: &'a mut VecDeque<Task>, +} + +impl TaskContext<'_> { + /// Document 访问入口(派发生命周期事件等)。 + pub fn document(&mut self) -> &mut Document { + self.doc + } + + /// 任务执行中投递后续任务:只入队尾,排在当前任务之后执行(不重入)。 + pub fn post_task(&mut self, task: Task) { + self.tasks.push_back(task); + } +} + +/// FIFO 宏任务队列(HTML event loop 的任务队列简化档:单源、同线程、无选择步骤)。 +#[derive(Debug, Default)] +pub struct EventLoop { + tasks: VecDeque<Task>, +} + +impl EventLoop { + /// 空队列。 + #[must_use] + pub fn new() -> Self { + Self::default() + } + + /// 投递任务到队尾。 + pub fn post_task(&mut self, task: Task) { + self.tasks.push_back(task); + } + + /// FIFO 排空任务队列:每次取队首任务独占执行,当前任务跑完才取下一个; + /// 执行中经 [`TaskContext::post_task`] 投递的任务追加到队尾,由本循环继续 + /// 按序执行——派发中 post 排队不重入。 + pub fn run_pending_tasks(&mut self, doc: &mut Document) { + while let Some(task) = self.tasks.pop_front() { + let mut ctx = TaskContext { + doc: &mut *doc, + tasks: &mut self.tasks, + }; + (task.0)(&mut ctx); + } + } +} + +#[cfg(test)] +mod tests { + use super::*; + use std::cell::RefCell; + use std::rc::Rc; + + type Log = Rc<RefCell<Vec<&'static str>>>; + + /// T2 ① FIFO 顺序。 + #[test] + fn tasks_run_in_fifo_order() { + let log: Log = Rc::new(RefCell::new(Vec::new())); + let mut event_loop = EventLoop::new(); + let mut doc = Document::new(); + + for label in ["a", "b", "c"] { + let log = Rc::clone(&log); + event_loop.post_task(Task::new(move |_| { + log.borrow_mut().push(label); + })); + } + + event_loop.run_pending_tasks(&mut doc); + assert_eq!(*log.borrow(), ["a", "b", "c"]); + } + + /// T2 ② 派发中 post_task 排队不重入:b 只能在 a 跑完之后执行。 + #[test] + fn task_posted_during_run_executes_after_current_completes() { + let log: Log = Rc::new(RefCell::new(Vec::new())); + let mut event_loop = EventLoop::new(); + let mut doc = Document::new(); + + let log_a = Rc::clone(&log); + event_loop.post_task(Task::new(move |ctx| { + log_a.borrow_mut().push("a-start"); + let log_b = Rc::clone(&log_a); + ctx.post_task(Task::new(move |_| { + log_b.borrow_mut().push("b"); + })); + log_a.borrow_mut().push("a-end"); + })); + + event_loop.run_pending_tasks(&mut doc); + assert_eq!( + *log.borrow(), + ["a-start", "a-end", "b"], + "b 不得在 a 执行期间重入" + ); + } +} diff --git a/crates/nexty-dom/src/event/mod.rs b/crates/nexty-dom/src/event/mod.rs new file mode 100644 index 0000000..af323e0 --- /dev/null +++ b/crates/nexty-dom/src/event/mod.rs @@ -0,0 +1,804 @@ +//! 事件模型:Event / 监听器注册表 / 传播算法(WHATWG DOM Standard §2.9 简化档)。 +//! +//! 行为 ground truth:[DOM Standard §2.9 Dispatching events] +//! (https://dom.spec.whatwg.org/#dispatching-events)。 +//! +//! 结构: +//! - [`Event`]:事件核心(type / bubbles / cancelable / eventPhase / +//! defaultPrevented / timeStamp)与三个干预方法。 +//! - 监听器为自身 trait 类型 [`EventListener`](另含 `FnMut(&mut Event)` 的 +//! 便捷实现),按(事件类型,capture 标志)登记在 +//! [`Document`](crate::Document) 侧的注册表容器——arena 节点不挂堆结构; +//! EventTarget 语义(add / remove / dispatch)由 `Document` 方法承载。 +//! - 传播([`Document::dispatch`]):capture 沿祖先链下行 → target → bubble +//! 上行;target 上 capture 与非 capture 监听器都触发且按注册顺序; +//! `bubbles=false` 停在 target。 +//! - 事件数据面见 [`data`] 模块;任务队列见 [`event_loop`] 模块。 +//! +//! ## 偏差清单(DOM §2.9 简化档) +//! +//! - 无 shadow tree / retargeting / composed path;无 trusted 语义(无 isTrusted)。 +//! - 监听器身份是 [`ListenerId`] 句柄而非回调对象地址——`Box` 移交注册表后 +//! 对象地址身份不可用;允许重复注册(同 DOM 语义:触发两次,各按句柄独立移除)。 +//! - 无 passive / once / AbortSignal 选项。 +//! - 监听器回调只接触核心 [`Event`] 面;类型化数据([`MouseEvent`] 等)由派发方 +//! 持有,回调读不到——K5 接 JS 绑定时再扩回调签名。 +//! - 监听器不随节点从树中摘下而清理(游离节点按 DOM 语义保留监听器,随 +//! `Document` 一起释放)。 +//! - 事件对象按单次派发使用:stop / canceled 标志不随派发重置(同规范), +//! 复用同一对象再派发会携带旧标志。 +//! - [`FocusEvent`] 仅类型面,无派发点(K10 焦点模型补);无 pointer capture / +//! 合成事件 / IME(本轮明确不做)。 +//! - 微任务队列只留接口空位(K5 填充),见 [`EventLoop`] 模块文档。 + +mod data; +mod event_loop; + +pub use data::{DeltaMode, FocusEvent, KeyboardEvent, MouseEvent, UiEvent, WheelEvent}; +pub use event_loop::{EventLoop, Task, TaskContext}; + +use std::collections::HashMap; +use std::fmt; +use std::time::{SystemTime, UNIX_EPOCH}; + +use crate::{Document, NodeId}; + +/// `DOMContentLoaded` 生命周期事件类型字符串。 +/// +/// bubbles=true、cancelable=false,在 Document 上派发(HTML 语法章节 +/// [the end](https://html.spec.whatwg.org/multipage/syntax.html#the-end) 的 +/// DOMContentLoaded 报告步骤);派发时机由 chrome 接线(K1 T3)。 +pub const DOM_CONTENT_LOADED: &str = "DOMContentLoaded"; + +/// `load` 生命周期事件类型字符串。 +/// +/// bubbles=false、cancelable=false,在 Document 上派发(HTML 语法章节 +/// [the end](https://html.spec.whatwg.org/multipage/syntax.html#the-end) 的 +/// load 事件步骤);派发时机由 chrome 接线(K1 T3,子资源编排 settle 点)。 +pub const LOAD: &str = "load"; + +/// 事件传播阶段(DOM Standard +/// [eventPhase](https://dom.spec.whatwg.org/#dom-event-eventphase))。 +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +pub enum EventPhase { + /// 未在派发中(构造后、派发结束后)。 + None, + /// 捕获阶段:祖先链下行,只触发 capture 监听器。 + Capturing, + /// 位于 target:capture 与非 capture 监听器都触发、按注册顺序。 + AtTarget, + /// 冒泡阶段:祖先链上行,只触发非 capture 监听器。 + Bubbling, +} + +/// 事件核心(DOM Standard [Event](https://dom.spec.whatwg.org/#interface-event) +/// 简化档:无 shadow、无 trusted)。 +/// +/// 生命周期事件直接用 [`Event::dom_content_loaded`] / [`Event::load`] 构造; +/// 带数据的事件见数据面类型([`MouseEvent`] 等,各自组合 `event: Event`)。 +#[derive(Debug)] +pub struct Event { + type_: String, + bubbles: bool, + cancelable: bool, + phase: EventPhase, + default_prevented: bool, + stop_propagation_flag: bool, + stop_immediate_propagation_flag: bool, + time_stamp: u64, +} + +impl Event { + /// 构造事件。 + /// + /// `timeStamp` 取构造时刻的 Unix 毫秒数(饱和);标志位全部初始为假, + /// 阶段为 [`EventPhase::None`]。 + #[must_use] + pub fn new(type_: impl Into<String>, bubbles: bool, cancelable: bool) -> Self { + let time_stamp = SystemTime::now() + .duration_since(UNIX_EPOCH) + .map_or(0, |since_epoch| { + u64::try_from(since_epoch.as_millis()).unwrap_or(u64::MAX) + }); + Self { + type_: type_.into(), + bubbles, + cancelable, + phase: EventPhase::None, + default_prevented: false, + stop_propagation_flag: false, + stop_immediate_propagation_flag: false, + time_stamp, + } + } + + /// DOM `type` 属性:事件类型字符串。 + #[must_use] + pub fn type_(&self) -> &str { + &self.type_ + } + + /// `bubbles` 标志:是否沿祖先链冒泡。 + #[must_use] + pub fn bubbles(&self) -> bool { + self.bubbles + } + + /// `cancelable` 标志:[`prevent_default`](Self::prevent_default) 是否有效。 + #[must_use] + pub fn cancelable(&self) -> bool { + self.cancelable + } + + /// 当前传播阶段;派发结束后回到 [`EventPhase::None`]。 + #[must_use] + pub fn event_phase(&self) -> EventPhase { + self.phase + } + + /// `defaultPrevented`:默认动作是否已被取消(仅 cancelable 事件可为真)。 + #[must_use] + pub fn default_prevented(&self) -> bool { + self.default_prevented + } + + /// `timeStamp`:构造时刻的 Unix 毫秒数。 + #[must_use] + pub fn time_stamp(&self) -> u64 { + self.time_stamp + } + + /// `DOMContentLoaded` 生命周期事件(HTML 语法章节 + /// [the end](https://html.spec.whatwg.org/multipage/syntax.html#the-end)): + /// bubbles=true、cancelable=false,在 Document 上派发;派发时机由 chrome + /// 接线(K1 T3)。 + #[must_use] + pub fn dom_content_loaded() -> Self { + Self::new(DOM_CONTENT_LOADED, true, false) + } + + /// `load` 生命周期事件(同上):bubbles=false、cancelable=false,在 + /// Document 上派发;派发时机由 chrome 接线(K1 T3)。 + #[must_use] + pub fn load() -> Self { + Self::new(LOAD, false, false) + } + + /// 阻断事件向后续节点与阶段传播;当前节点已排到的剩余监听器照常触发 + /// (DOM Standard + /// [stopPropagation](https://dom.spec.whatwg.org/#dom-event-stoppropagation))。 + pub fn stop_propagation(&mut self) { + self.stop_propagation_flag = true; + } + + /// 在 [`stop_propagation`](Self::stop_propagation) 的基础上同时终止当前 + /// 节点剩余监听器(DOM Standard + /// [stopImmediatePropagation](https://dom.spec.whatwg.org/#dom-event-stopimmediatepropagation))。 + pub fn stop_immediate_propagation(&mut self) { + self.stop_propagation_flag = true; + self.stop_immediate_propagation_flag = true; + } + + /// 取消默认动作;cancelable=false 的事件上无效(DOM Standard + /// [preventDefault](https://dom.spec.whatwg.org/#dom-event-preventdefault))。 + pub fn prevent_default(&mut self) { + if self.cancelable { + self.default_prevented = true; + } + } +} + +/// 事件监听器(自身 trait 类型,不外泄依赖类型——本 crate 本就零依赖)。 +/// +/// 回调只接触核心 [`Event`] 面(阶段与干预标志);类型化数据由派发方持有。 +/// 闭包可经 `FnMut(&mut Event)` 便捷实现直接当监听器用——闭包参数须标注 +/// `&mut Event` 类型,未标注时 rustc 的高阶生命周期推断可能报 +/// "not general enough"。 +pub trait EventListener { + /// 处理事件。可在回调内调用 [`stop_propagation`](Event::stop_propagation) / + /// [`stop_immediate_propagation`](Event::stop_immediate_propagation) / + /// [`prevent_default`](Event::prevent_default)。 + fn handle_event(&mut self, event: &mut Event); +} + +impl<F> EventListener for F +where + F: FnMut(&mut Event), +{ + fn handle_event(&mut self, event: &mut Event) { + self(event); + } +} + +/// 监听器句柄:[`Document::add_listener`] 返回,[`Document::remove_listener`] +/// 凭句柄移除。 +/// +/// 用句柄而非对象地址作身份——监听器 `Box` 移交注册表后地址身份不可用。 +#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)] +pub struct ListenerId(u64); + +/// 单条监听器登记(注册表内部)。 +struct ListenerEntry { + capture: bool, + id: ListenerId, + listener: Box<dyn EventListener>, +} + +/// 监听器注册表:节点 → 事件类型 → 注册序条目。 +/// +/// 同一(节点,类型)下的条目保持注册顺序(DOM 的 event listener list 是 +/// 单条有序表),capture 标志记录在条目上——capture / bubble 阶段按标志过滤, +/// target 阶段两种混序按同一注册顺序触发(DOM §2.9「invoke」)。事件类型作 +/// 哈希键、条目为小 Vec,与(type, capture)存取语义等价且省一次排序。 +#[derive(Default)] +pub(crate) struct ListenerRegistry { + by_node: HashMap<NodeId, HashMap<String, Vec<ListenerEntry>>>, + next_id: u64, +} + +impl ListenerRegistry { + /// 登记监听器,返回移除用句柄。允许重复注册(同 DOM:触发两次)。 + fn add( + &mut self, + target: NodeId, + event_type: &str, + capture: bool, + listener: Box<dyn EventListener>, + ) -> ListenerId { + let id = ListenerId(self.next_id); + self.next_id += 1; + self.by_node + .entry(target) + .or_default() + .entry(event_type.to_string()) + .or_default() + .push(ListenerEntry { + capture, + id, + listener, + }); + id + } + + /// 移除指定条目;未找到返回 false。 + fn remove(&mut self, target: NodeId, event_type: &str, id: ListenerId) -> bool { + let Some(entries) = self + .by_node + .get_mut(&target) + .and_then(|by_type| by_type.get_mut(event_type)) + else { + return false; + }; + let Some(position) = entries.iter().position(|entry| entry.id == id) else { + return false; + }; + entries.remove(position); + if entries.is_empty() + && let Some(by_type) = self.by_node.get_mut(&target) + { + by_type.remove(event_type); + if by_type.is_empty() { + self.by_node.remove(&target); + } + } + true + } + + /// 按(节点,类型)取条目表。 + fn for_type_mut( + &mut self, + target: NodeId, + event_type: &str, + ) -> Option<&mut Vec<ListenerEntry>> { + self.by_node.get_mut(&target)?.get_mut(event_type) + } +} + +impl fmt::Debug for ListenerRegistry { + fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { + let listener_count: usize = self + .by_node + .values() + .map(|by_type| by_type.values().map(Vec::len).sum::<usize>()) + .sum(); + f.debug_struct("ListenerRegistry") + .field("nodes", &self.by_node.len()) + .field("listeners", &listener_count) + .finish() + } +} + +impl Document { + /// 在 `target` 上登记 `event_type` 监听器(DOM + /// [addEventListener](https://dom.spec.whatwg.org/#dom-eventtarget-addeventlistener) + /// 简化档:无 passive / once / signal)。`capture` 为真时该监听器在捕获 + /// 阶段触发(在 target 上则随注册顺序参与 target 阶段)。 + /// + /// 返回 [`ListenerId`] 供 [`remove_listener`](Self::remove_listener) 使用; + /// 允许重复注册(同 DOM 语义:触发两次)。 + pub fn add_listener( + &mut self, + target: NodeId, + event_type: &str, + capture: bool, + listener: Box<dyn EventListener>, + ) -> ListenerId { + self.listeners.add(target, event_type, capture, listener) + } + + /// 移除监听器(DOM + /// [removeEventListener](https://dom.spec.whatwg.org/#dom-eventtarget-removeeventlistener) + /// 简化档)。返回是否确有移除;同一句柄重复移除返回 false。 + pub fn remove_listener(&mut self, target: NodeId, event_type: &str, id: ListenerId) -> bool { + self.listeners.remove(target, event_type, id) + } + + /// 派发事件(DOM Standard + /// [dispatch](https://dom.spec.whatwg.org/#concept-event-dispatch) 简化档: + /// 无 shadow、无 retargeting)。 + /// + /// 传播:capture 沿祖先链自根下行 → target(capture 与非 capture 监听器 + /// 都触发、按注册顺序)→ bubble 上行;`bubbles=false` 停在 target;target + /// 无祖先链(含 Document 根)时仅 target 阶段。 + /// + /// 返回「未取消」:false 表示 cancelable 事件已被 + /// [`prevent_default`](Event::prevent_default) 取消,调用方应跳过默认动作 + /// (先派发后默认契约)。 + pub fn dispatch(&mut self, target: NodeId, event: &mut Event) -> bool { + // 祖先链(根 → target 的直接父节点,自上而下)。深度受 MAX_TREE_DEPTH + // 约束,迭代收集不递归。 + let mut chain = Vec::new(); + let mut current = self.parent(target); + while let Some(node) = current { + chain.push(node); + current = self.parent(node); + } + chain.reverse(); + + for &node in &chain { + if event.stop_propagation_flag { + break; + } + event.phase = EventPhase::Capturing; + self.invoke(node, event); + } + if !event.stop_propagation_flag { + event.phase = EventPhase::AtTarget; + self.invoke(target, event); + } + if event.bubbles { + for &node in chain.iter().rev() { + if event.stop_propagation_flag { + break; + } + event.phase = EventPhase::Bubbling; + self.invoke(node, event); + } + } + event.phase = EventPhase::None; + !event.default_prevented + } + + /// invoke(DOM §2.9「invoke an event listener」简化档):按事件当前阶段 + /// 过滤条目——Capturing 只触发 capture 条目、Bubbling 只触发非 capture、 + /// AtTarget 全部按注册序触发;stopImmediatePropagation 终止当前节点剩余 + /// 监听器,stopPropagation 不影响当前节点、只阻断后续节点与阶段。 + fn invoke(&mut self, node: NodeId, event: &mut Event) { + let (capture_only, all_entries) = match event.phase { + EventPhase::Capturing => (true, false), + EventPhase::AtTarget => (false, true), + EventPhase::Bubbling => (false, false), + EventPhase::None => return, + }; + let type_ = event.type_(); + let Some(entries) = self.listeners.for_type_mut(node, type_) else { + return; + }; + for entry in entries.iter_mut() { + if event.stop_immediate_propagation_flag { + break; + } + if !all_entries && entry.capture != capture_only { + continue; + } + entry.listener.handle_event(event); + } + } +} + +#[cfg(test)] +mod tests { + use super::*; + use crate::{ElementData, Namespace, NodeKind}; + use std::cell::RefCell; + use std::rc::Rc; + + fn element(doc: &mut Document, name: &str) -> NodeId { + doc.create_node(NodeKind::Element(ElementData { + name: name.into(), + namespace: Namespace::Html, + attributes: Vec::new(), + })) + } + + type Log = Rc<RefCell<Vec<(&'static str, EventPhase)>>>; + + /// 监听动作:记录(标签, 阶段)后可选注入一种干预。 + #[derive(Clone, Copy)] + enum Action { + None, + StopPropagation, + StopImmediate, + PreventDefault, + } + + struct Recorder { + label: &'static str, + action: Action, + log: Log, + } + + impl EventListener for Recorder { + fn handle_event(&mut self, event: &mut Event) { + self.log + .borrow_mut() + .push((self.label, event.event_phase())); + match self.action { + Action::None => {} + Action::StopPropagation => event.stop_propagation(), + Action::StopImmediate => event.stop_immediate_propagation(), + Action::PreventDefault => event.prevent_default(), + } + } + } + + fn recorder(label: &'static str, action: Action, log: &Log) -> Box<dyn EventListener> { + Box::new(Recorder { + label, + action, + log: Rc::clone(log), + }) + } + + fn labels_of(log: &Log) -> Vec<&'static str> { + log.borrow().iter().map(|(label, _)| *label).collect() + } + + // ---- T1 退出条件 ---- + + /// ① 三阶段顺序与注册顺序(含 target 双捕获语义)。 + #[test] + fn dispatch_runs_capture_target_bubble_in_registration_order() { + let mut doc = Document::new(); + let outer = element(&mut doc, "outer"); + let inner = element(&mut doc, "inner"); + doc.append_child(outer, doc.root()).unwrap(); + doc.append_child(inner, outer).unwrap(); + + let log: Log = Rc::new(RefCell::new(Vec::new())); + doc.add_listener( + doc.root(), + "click", + true, + recorder("root-capture", Action::None, &log), + ); + doc.add_listener( + outer, + "click", + true, + recorder("outer-capture", Action::None, &log), + ); + doc.add_listener( + outer, + "click", + false, + recorder("outer-bubble", Action::None, &log), + ); + // target 上 capture 与非 capture 混合注册:触发顺序 = 注册顺序。 + doc.add_listener( + inner, + "click", + true, + recorder("inner-cap-1", Action::None, &log), + ); + doc.add_listener( + inner, + "click", + false, + recorder("inner-bubble", Action::None, &log), + ); + doc.add_listener( + inner, + "click", + true, + recorder("inner-cap-2", Action::None, &log), + ); + + let mut event = Event::new("click", true, true); + assert!(doc.dispatch(inner, &mut event)); + + assert_eq!( + labels_of(&log), + [ + "root-capture", + "outer-capture", + "inner-cap-1", + "inner-bubble", + "inner-cap-2", + "outer-bubble" + ] + ); + for (label, phase) in log.borrow().iter() { + let expected = match *label { + "root-capture" | "outer-capture" => EventPhase::Capturing, + "outer-bubble" => EventPhase::Bubbling, + _ => EventPhase::AtTarget, + }; + assert_eq!(*phase, expected, "{label} 观察到的阶段不符"); + } + } + + /// ② stopPropagation:同节点剩余监听器照跑,后续节点与冒泡阶段阻断。 + #[test] + fn stop_propagation_keeps_remaining_target_listeners_and_blocks_ancestors() { + let mut doc = Document::new(); + let parent = element(&mut doc, "parent"); + let target = element(&mut doc, "target"); + doc.append_child(parent, doc.root()).unwrap(); + doc.append_child(target, parent).unwrap(); + + let log: Log = Rc::new(RefCell::new(Vec::new())); + doc.add_listener( + parent, + "click", + true, + recorder("parent-capture", Action::None, &log), + ); + doc.add_listener( + parent, + "click", + false, + recorder("parent-bubble", Action::None, &log), + ); + doc.add_listener(target, "click", false, recorder("t1", Action::None, &log)); + doc.add_listener( + target, + "click", + false, + recorder("t2", Action::StopPropagation, &log), + ); + doc.add_listener(target, "click", false, recorder("t3", Action::None, &log)); + + let mut event = Event::new("click", true, true); + doc.dispatch(target, &mut event); + + assert_eq!( + labels_of(&log), + ["parent-capture", "t1", "t2", "t3"], + "stopPropagation:t3 照跑,parent-bubble 不触发" + ); + } + + /// ② stopImmediatePropagation:额外终止当前节点剩余监听器(与上一条对照)。 + #[test] + fn stop_immediate_propagation_additionally_stops_current_node() { + let mut doc = Document::new(); + let parent = element(&mut doc, "parent"); + let target = element(&mut doc, "target"); + doc.append_child(parent, doc.root()).unwrap(); + doc.append_child(target, parent).unwrap(); + + let log: Log = Rc::new(RefCell::new(Vec::new())); + doc.add_listener( + parent, + "click", + true, + recorder("parent-capture", Action::None, &log), + ); + doc.add_listener(target, "click", false, recorder("t1", Action::None, &log)); + doc.add_listener( + target, + "click", + false, + recorder("t2", Action::StopImmediate, &log), + ); + doc.add_listener(target, "click", false, recorder("t3", Action::None, &log)); + + let mut event = Event::new("click", true, true); + doc.dispatch(target, &mut event); + + assert_eq!( + labels_of(&log), + ["parent-capture", "t1", "t2"], + "stopImmediatePropagation:t3 不再触发" + ); + } + + /// ③ preventDefault:cancelable=false 时无效;取消后 defaultPrevented=true + /// 且 dispatch 返回 false。 + #[test] + fn prevent_default_only_takes_effect_on_cancelable_events() { + let mut doc = Document::new(); + let node = element(&mut doc, "a"); + doc.append_child(node, doc.root()).unwrap(); + + let log: Log = Rc::new(RefCell::new(Vec::new())); + doc.add_listener( + node, + "submit", + false, + recorder("prevent", Action::PreventDefault, &log), + ); + + let mut non_cancelable = Event::new("submit", true, false); + assert!( + doc.dispatch(node, &mut non_cancelable), + "cancelable=false 时 preventDefault 无效,dispatch 返回未取消" + ); + assert!(!non_cancelable.default_prevented()); + + let mut cancelable = Event::new("submit", true, true); + assert!( + !doc.dispatch(node, &mut cancelable), + "取消后 dispatch 返回 false(默认动作应跳过)" + ); + assert!(cancelable.default_prevented()); + } + + /// ④ bubbles=false 停在 target(capture 链照常、无冒泡)。 + #[test] + fn non_bubbling_event_stops_after_target() { + let mut doc = Document::new(); + let outer = element(&mut doc, "outer"); + let inner = element(&mut doc, "inner"); + doc.append_child(outer, doc.root()).unwrap(); + doc.append_child(inner, outer).unwrap(); + + let log: Log = Rc::new(RefCell::new(Vec::new())); + doc.add_listener( + doc.root(), + "click", + true, + recorder("root-capture", Action::None, &log), + ); + doc.add_listener( + outer, + "click", + true, + recorder("outer-capture", Action::None, &log), + ); + doc.add_listener( + outer, + "click", + false, + recorder("outer-bubble", Action::None, &log), + ); + doc.add_listener( + inner, + "click", + false, + recorder("inner-bubble", Action::None, &log), + ); + + let mut event = Event::new("click", false, true); + doc.dispatch(inner, &mut event); + + assert_eq!( + labels_of(&log), + ["root-capture", "outer-capture", "inner-bubble"], + "bubbles=false:capture 链照常、target 照常、无冒泡" + ); + } + + /// ⑤ remove_listener 后不再触发;重复移除返回 false。 + #[test] + fn remove_listener_takes_effect_on_subsequent_dispatch() { + let mut doc = Document::new(); + let node = element(&mut doc, "a"); + doc.append_child(node, doc.root()).unwrap(); + + let log: Log = Rc::new(RefCell::new(Vec::new())); + let id = doc.add_listener(node, "click", false, recorder("a", Action::None, &log)); + + let mut first = Event::new("click", true, false); + doc.dispatch(node, &mut first); + assert_eq!(log.borrow().len(), 1); + + assert!(doc.remove_listener(node, "click", id)); + let mut second = Event::new("click", true, false); + doc.dispatch(node, &mut second); + assert_eq!(log.borrow().len(), 1, "移除后不再触发"); + + assert!( + !doc.remove_listener(node, "click", id), + "重复移除返回 false" + ); + } + + // ---- T2 退出条件(生命周期事件字段与 bubbles)---- + + #[test] + fn lifecycle_events_carry_documented_flags() { + let dom_content_loaded = Event::dom_content_loaded(); + assert_eq!(dom_content_loaded.type_(), DOM_CONTENT_LOADED); + assert!(dom_content_loaded.bubbles()); + assert!(!dom_content_loaded.cancelable()); + assert!(!dom_content_loaded.default_prevented()); + assert_eq!(dom_content_loaded.event_phase(), EventPhase::None); + + let load = Event::load(); + assert_eq!(load.type_(), LOAD); + assert!(!load.bubbles(), "load 不冒泡"); + assert!(!load.cancelable()); + assert!(!load.default_prevented()); + } + + #[test] + fn lifecycle_events_dispatch_on_document_root_at_target_only() { + let mut doc = Document::new(); + let log: Log = Rc::new(RefCell::new(Vec::new())); + doc.add_listener( + doc.root(), + DOM_CONTENT_LOADED, + false, + recorder("dcl", Action::None, &log), + ); + + let mut event = Event::dom_content_loaded(); + assert!(doc.dispatch(doc.root(), &mut event)); + assert_eq!( + *log.borrow(), + [("dcl", EventPhase::AtTarget)], + "根节点无祖先链:仅 target 阶段,恰好一次" + ); + + // capture 监听器在 target(根节点)上同样按注册序参与 target 阶段。 + doc.add_listener( + doc.root(), + LOAD, + true, + recorder("load-capture", Action::None, &log), + ); + let mut load = Event::load(); + assert!(doc.dispatch(doc.root(), &mut load)); + assert_eq!( + log.borrow().get(1), + Some(&("load-capture", EventPhase::AtTarget)) + ); + } + + // ---- 补充钉住的语义 ---- + + #[test] + fn closure_listeners_invoke_through_blanket_impl() { + let mut doc = Document::new(); + let node = element(&mut doc, "a"); + doc.append_child(node, doc.root()).unwrap(); + + let hits = Rc::new(RefCell::new(0u32)); + let counter = Rc::clone(&hits); + doc.add_listener( + node, + "click", + false, + Box::new(move |_event: &mut Event| { + *counter.borrow_mut() += 1; + }), + ); + + let mut event = Event::new("click", true, false); + assert!(doc.dispatch(node, &mut event)); + assert_eq!(*hits.borrow(), 1); + } + + #[test] + fn dispatch_without_listeners_completes_and_resets_phase() { + let mut doc = Document::new(); + let node = element(&mut doc, "div"); + doc.append_child(node, doc.root()).unwrap(); + + let mut event = Event::new("hover", true, true); + assert!(doc.dispatch(node, &mut event)); + assert_eq!(event.event_phase(), EventPhase::None, "派发结束后回到 None"); + } +} diff --git a/crates/nexty-dom/src/lib.rs b/crates/nexty-dom/src/lib.rs index 9b640e0..37752ac 100644 --- a/crates/nexty-dom/src/lib.rs +++ b/crates/nexty-dom/src/lib.rs @@ -9,18 +9,28 @@ //! 节点类型见 `node` 模块,树变更算法见 `tree` 模块。 //! //! 已落地:节点类型(含 doctype / fragment / 处理指令)与元素命名空间、 -//! 树变更算法(insert / remove / replace / clone / normalize)。JS 绑定层尚未接入。 +//! 树变更算法(insert / remove / replace / clone / normalize)、事件模型 +//! (Event / 监听器注册表 / 传播算法 / 事件数据面 / EventLoop——DOM §2.9 +//! 简化档,见 `event` 模块文档及其偏差清单)。JS 绑定层尚未接入。 //! -//! **Feature**:节点数据层(`node`)与树变更算法(`tree`)分别受feature 控制, -//! 默认全开;`tree` 隐含 `node`。 +//! **Feature**:节点数据层(`node`)、树变更算法(`tree`)与事件模型 +//! (`event`)分别受 feature 控制,默认全开;`tree` 隐含 `node`, +//! `event` 隐含 `tree`。 #![forbid(unsafe_code)] +#[cfg(feature = "event")] +mod event; #[cfg(feature = "node")] mod node; #[cfg(feature = "tree")] mod tree; +#[cfg(feature = "event")] +pub use event::{ + DOM_CONTENT_LOADED, DeltaMode, Event, EventListener, EventLoop, EventPhase, FocusEvent, + KeyboardEvent, LOAD, ListenerId, MouseEvent, Task, TaskContext, UiEvent, WheelEvent, +}; #[cfg(feature = "node")] pub use node::{ Attribute, DocumentTypeData, DomError, ElementData, Namespace, NodeId, NodeKind, diff --git a/crates/nexty-dom/src/tree.rs b/crates/nexty-dom/src/tree.rs index 3032a45..e73420e 100644 --- a/crates/nexty-dom/src/tree.rs +++ b/crates/nexty-dom/src/tree.rs @@ -60,6 +60,11 @@ impl Node { pub struct Document { nodes: Vec<Node>, quirks_mode: QuirksMode, + /// 事件监听器注册表(`event` feature):节点 → 事件类型 → 注册序条目。 + /// 容器挂在 Document 侧(arena 节点不挂堆结构);读写接口在 `event` 模块 + /// 的 `impl Document` 块内(add_listener / remove_listener / dispatch)。 + #[cfg(feature = "event")] + pub(crate) listeners: crate::event::ListenerRegistry, } impl Default for Document { @@ -75,6 +80,8 @@ impl Document { Self { nodes: vec![Node::detached(NodeKind::Document)], quirks_mode: QuirksMode::NoQuirks, + #[cfg(feature = "event")] + listeners: crate::event::ListenerRegistry::default(), } } From 1f8919d2c23123131833035113898e769f9d2a56 Mon Sep 17 00:00:00 2001 From: zwork <zwork@local> Date: Sat, 31 Oct 2026 18:30:02 +0800 Subject: [PATCH 07/14] [css] K2 drawing properties (text-decoration/z-index/border-radius/linear-gradient) + K4 @font-face parsing + UA link underline (0.1.18) --- ..._593b0e04-d177-44d2-b3cc-247d233520f7.json | 1 + ...06c80651a6e5acc29a13d3c84bf63ac1cdd.source | 2367 +++++++++++ ...15a93dd1817d31e6788691cdb29752fd612.source | 3534 +++++++++++++++++ ..._ca7e797f-14f7-4cd4-a65e-6a69d7418103.json | 1 + ...06c80651a6e5acc29a13d3c84bf63ac1cdd.source | 1509 +++++++ ...52fbcef87b5e360662bb527c96d9a615542.source | 31 + ...3eff4d1aa9330836f5b91cac68c5398193f.source | 1435 +++++++ ...15a93dd1817d31e6788691cdb29752fd612.source | 2840 +++++++++++++ ...sion_164476f9d97ffaabe4f6dc9715b6aad5.json | 1 + ...06c80651a6e5acc29a13d3c84bf63ac1cdd.source | 1656 ++++++++ ...24fdb88882b47c23cc0e0c80a30c7d53759.source | 50 + ...15a93dd1817d31e6788691cdb29752fd612.source | 3181 +++++++++++++++ ...177-44d2-b3cc-247d233520f7-3522fc697d.json | 14 + ...4f7-4cd4-a65e-6a69d7418103-35569b193b.json | 14 + ...f9d97ffaabe4f6dc9715b6aad5-5e056c09de.json | 14 + crates/nexty-css/Cargo.toml | 2 +- crates/nexty-css/src/cascade.rs | 337 +- crates/nexty-css/src/lib.rs | 29 +- crates/nexty-css/src/parser.rs | 1197 +++++- crates/nexty-css/src/ua.rs | 6 +- crates/nexty-css/src/value.rs | 666 +++- 21 files changed, 18834 insertions(+), 51 deletions(-) create mode 100644 crates/nexty-css/.mimosa/hook-state/sess_593b0e04-d177-44d2-b3cc-247d233520f7.json create mode 100644 crates/nexty-css/.mimosa/hook-state/sess_593b0e04-d177-44d2-b3cc-247d233520f7.mvw2dq8j-91568-cc032940c8.baseline/01bd7f2baaf2335e56694f02b60c806c80651a6e5acc29a13d3c84bf63ac1cdd.source create mode 100644 crates/nexty-css/.mimosa/hook-state/sess_593b0e04-d177-44d2-b3cc-247d233520f7.mvw2dq8j-91568-cc032940c8.baseline/be1c878c753064b7eaddf4a10ba4215a93dd1817d31e6788691cdb29752fd612.source create mode 100644 crates/nexty-css/.mimosa/hook-state/sess_ca7e797f-14f7-4cd4-a65e-6a69d7418103.json create mode 100644 crates/nexty-css/.mimosa/hook-state/sess_ca7e797f-14f7-4cd4-a65e-6a69d7418103.mv37y1v5-51660-adb7c830c0.baseline/01bd7f2baaf2335e56694f02b60c806c80651a6e5acc29a13d3c84bf63ac1cdd.source create mode 100644 crates/nexty-css/.mimosa/hook-state/sess_ca7e797f-14f7-4cd4-a65e-6a69d7418103.mv37y1v5-51660-adb7c830c0.baseline/2e9d962a08321605940b5a657135052fbcef87b5e360662bb527c96d9a615542.source create mode 100644 crates/nexty-css/.mimosa/hook-state/sess_ca7e797f-14f7-4cd4-a65e-6a69d7418103.mv37y1v5-51660-adb7c830c0.baseline/4a04259da480a6b794a2e947e4cc03eff4d1aa9330836f5b91cac68c5398193f.source create mode 100644 crates/nexty-css/.mimosa/hook-state/sess_ca7e797f-14f7-4cd4-a65e-6a69d7418103.mv37y1v5-51660-adb7c830c0.baseline/be1c878c753064b7eaddf4a10ba4215a93dd1817d31e6788691cdb29752fd612.source create mode 100644 crates/nexty-css/.mimosa/hook-state/session_164476f9d97ffaabe4f6dc9715b6aad5.json create mode 100644 crates/nexty-css/.mimosa/hook-state/session_164476f9d97ffaabe4f6dc9715b6aad5.mvmgp416-93016-2afbe7aa51.baseline/01bd7f2baaf2335e56694f02b60c806c80651a6e5acc29a13d3c84bf63ac1cdd.source create mode 100644 crates/nexty-css/.mimosa/hook-state/session_164476f9d97ffaabe4f6dc9715b6aad5.mvmgp416-93016-2afbe7aa51.baseline/b1a35a68f14e696205874893c07fd24fdb88882b47c23cc0e0c80a30c7d53759.source create mode 100644 crates/nexty-css/.mimosa/hook-state/session_164476f9d97ffaabe4f6dc9715b6aad5.mvmgp416-93016-2afbe7aa51.baseline/be1c878c753064b7eaddf4a10ba4215a93dd1817d31e6788691cdb29752fd612.source create mode 100644 crates/nexty-css/.mimosa/hook-status/sess_593b0e04-d177-44d2-b3cc-247d233520f7-3522fc697d.json create mode 100644 crates/nexty-css/.mimosa/hook-status/sess_ca7e797f-14f7-4cd4-a65e-6a69d7418103-35569b193b.json create mode 100644 crates/nexty-css/.mimosa/hook-status/session_164476f9d97ffaabe4f6dc9715b6aad5-5e056c09de.json diff --git a/crates/nexty-css/.mimosa/hook-state/sess_593b0e04-d177-44d2-b3cc-247d233520f7.json b/crates/nexty-css/.mimosa/hook-state/sess_593b0e04-d177-44d2-b3cc-247d233520f7.json new file mode 100644 index 0000000..b542b9a --- /dev/null +++ b/crates/nexty-css/.mimosa/hook-state/sess_593b0e04-d177-44d2-b3cc-247d233520f7.json @@ -0,0 +1 @@ +{"touched":["D:\\Nexty\\crates\\nexty-css\\src\\value.rs","D:\\Nexty\\crates\\nexty-css\\src\\cascade.rs"],"bashMutation":true,"reportedFindings":[],"findingEvents":[],"baseline":{"storageId":"mvw2dq8j-91568-cc032940c8","createdAt":"2026-10-31T07:12:59.923Z","files":{"src/value.rs":{"existed":true,"snapshot":"be1c878c753064b7eaddf4a10ba4215a93dd1817d31e6788691cdb29752fd612.source"},"src/cascade.rs":{"existed":true,"snapshot":"01bd7f2baaf2335e56694f02b60c806c80651a6e5acc29a13d3c84bf63ac1cdd.source"}},"complete":false,"candidateLimit":5000,"discoveredFiles":0,"capturedFiles":2,"truncated":false,"omittedAtLeast":0,"firstOmitted":"","errors":[{"stage":"baseline-capture","target":".","reason":"global task baseline was unavailable; captured only the touched file"}]},"stateErrors":[],"omittedReportedFindings":0,"omittedFindingEvents":0,"processing":null,"updatedAt":"2026-10-31T07:14:15.698Z"} \ No newline at end of file diff --git a/crates/nexty-css/.mimosa/hook-state/sess_593b0e04-d177-44d2-b3cc-247d233520f7.mvw2dq8j-91568-cc032940c8.baseline/01bd7f2baaf2335e56694f02b60c806c80651a6e5acc29a13d3c84bf63ac1cdd.source b/crates/nexty-css/.mimosa/hook-state/sess_593b0e04-d177-44d2-b3cc-247d233520f7.mvw2dq8j-91568-cc032940c8.baseline/01bd7f2baaf2335e56694f02b60c806c80651a6e5acc29a13d3c84bf63ac1cdd.source new file mode 100644 index 0000000..0460168 --- /dev/null +++ b/crates/nexty-css/.mimosa/hook-state/sess_593b0e04-d177-44d2-b3cc-247d233520f7.mvw2dq8j-91568-cc032940c8.baseline/01bd7f2baaf2335e56694f02b60c806c80651a6e5acc29a13d3c84bf63ac1cdd.source @@ -0,0 +1,2367 @@ +//! 自研 cascade 与 computed style。 +//! +//! 行为 ground truth: +//! - 级联排序:[CSS Cascading and Inheritance Level 5 §6](https://drafts.csswg.org/css-cascade-5/#cascading) +//! - 继承 / 初始值:[CSS Cascade 5 §7](https://drafts.csswg.org/css-cascade-5/#defaulting) +//! - 字号计算:[CSS Fonts 4 §2.5](https://drafts.csswg.org/css-fonts-4/#font-size-prop) +//! - 相对字重:[CSS Fonts 4 §2.2.1](https://drafts.csswg.org/css-fonts-4/#relative-weights) +//! +//! 本轮只有 author origin(UA 样式表未引入),故排序桶为: +//! importance → 内联样式 → 特异度 → 源顺序。`revert` 回退到 UA origin, +//! 而 UA 无声明,等价于 initial。 + +use std::collections::HashMap; + +use nexty_dom::{Document, NodeId, NodeKind}; + +use crate::parser::{Declaration, MediaViewport, StyleRule, Stylesheet, parse_inline_style}; +use crate::selector::{NextySelector, atom_str, match_element_selectors}; +use crate::value::{ + AbsoluteSize, AlignItemsValue, AlignSelfValue, BorderColorValue, BorderStyle, BorderWidthValue, + BoxSizingValue, ClearValue, CssWideKeyword, DeclaredValue, DisplayValue, FlexDirectionValue, + FloatValue, FlexWrapValue, + FontFamilyValue, FontSizeValue, FontStyleValue, FontWeightValue, GapValue, GridAutoFlowValue, + GridTrackList, InsetValue, JustifyContentValue, LineHeightValue, MAX_CSS_LENGTH, MarginValue, + OverflowValue, OverflowWrapValue, PaddingValue, PositionValue, PropertyId, PropertyValue, Rgba, + SizeValue, SpacingValue, TabSizeValue, TextAlignValue, TextIndentValue, ViewportUnit, + WhiteSpaceValue, WordBreakValue, +}; + +/// 本层 UA 的 medium 字号基准(CSS Fonts 4 §2.5:initial 值由 UA 决定, +/// 对齐浏览器默认 16px;绝对尺寸关键字按 §2.5.1 缩放系数相对它计算)。 +pub(crate) const MEDIUM_FONT_SIZE: f32 = 16.0; + +/// 一个元素的 computed style(属性集随管线逐轮扩展)。 +#[derive(Debug, Clone, PartialEq)] +pub struct ComputedStyle { + /// `display`。 + pub display: DisplayValue, + /// `color`。 + pub color: Rgba, + /// `background-color`。 + pub background_color: Rgba, + /// 计算字号(CSS px)。 + pub font_size: f32, + /// 计算字重(1–1000)。 + pub font_weight: f32, + /// `font-style`。 + pub font_style: FontStyleValue, + /// `font-family` 列表。 + pub font_family: Vec<FontFamilyValue>, + /// `text-align`。 + pub text_align: TextAlignValue, + /// `line-height`(数值/normal 保持原样;长度为绝对 px; + /// 百分比与 em 已按本元素 font-size 折算)。 + pub line_height: LineHeightValue, + /// `white-space`(CSS Text 3 §3.1)。 + pub white_space: WhiteSpaceValue, + /// `overflow-wrap`(CSS Text 3 §5.4)。 + pub overflow_wrap: OverflowWrapValue, + /// `word-break`(CSS Text 3 §5.1)。 + pub word_break: WordBreakValue, + /// `letter-spacing` 的附加字距(CSS px;`normal` 与 0 同义,CSS Text 3 §8.1)。 + pub letter_spacing: f32, + /// `word-spacing`(CSS Text 3 §8.2;`normal` 语义保留给 layout,em 已折算)。 + pub word_spacing: SpacingValue, + /// `text-indent`(CSS Text 3 §4;em 已折算,百分比由 layout 按包含块解析)。 + pub text_indent: TextIndentValue, + /// `tab-size`(CSS Text 3 §5;整数形态由 layout 按空格 advance 解析)。 + pub tab_size: TabSizeValue, + /// `width`(百分比由 layout 解析)。 + pub width: SizeValue, + /// `height`(百分比由 layout 解析)。 + pub height: SizeValue, + /// `min-width`(CSS 2.1 §10.4)。 + pub min_width: SizeValue, + /// `max-width`(CSS 2.1 §10.4)。 + pub max_width: SizeValue, + /// `min-height`(CSS 2.1 §10.7)。 + pub min_height: SizeValue, + /// `max-height`(CSS 2.1 §10.7)。 + pub max_height: SizeValue, + /// `box-sizing`(CSS Sizing 4 §5.3)。 + pub box_sizing: BoxSizingValue, + /// `overflow`(CSS Overflow 3 §3;仅裁剪标记,裁剪未实现)。 + pub overflow: OverflowValue, + /// `flex-grow`(CSS Flexbox §7.1,initial 0)。 + pub flex_grow: f32, + /// `flex-basis`(CSS Flexbox §7.2,initial auto)。 + pub flex_basis: SizeValue, + /// `position`(CSS Position 3 §2,initial static)。 + pub position: PositionValue, + /// `float`(CSS 2.1 §9.5.1,initial none;不继承)。 + pub float: FloatValue, + /// `clear`(CSS 2.1 §9.5.2,initial none;不继承)。 + pub clear: ClearValue, + /// 四边 inset(top / right / bottom / left;百分比与 auto 由 layout 解析)。 + pub inset: Edges<InsetValue>, + /// `flex-direction`(CSS Flexbox §8.3.1,initial row)。 + pub flex_direction: FlexDirectionValue, + /// `flex-wrap`(CSS Flexbox §8.4.1,initial nowrap)。 + pub flex_wrap: FlexWrapValue, + /// `flex-shrink`(CSS Flexbox §7.2,initial 1)。 + pub flex_shrink: f32, + /// `align-items`(CSS Box Alignment §7,initial stretch)。 + pub align_items: AlignItemsValue, + /// `justify-content`(CSS Box Alignment §8,initial flex-start)。 + pub justify_content: JustifyContentValue, + /// `align-self`(CSS Box Alignment §7,initial auto)。 + pub align_self: AlignSelfValue, + /// `grid-template-columns`(CSS Grid §7.2,initial 空)。 + pub grid_template_columns: GridTrackList, + /// `grid-template-rows`(CSS Grid §7.3,initial 空)。 + pub grid_template_rows: GridTrackList, + /// `row-gap`(CSS Box Alignment §6,initial normal)。 + pub row_gap: GapValue, + /// `column-gap`(CSS Box Alignment §6,initial normal)。 + pub column_gap: GapValue, + /// `grid-auto-flow`(CSS Grid §7.7,initial row)。 + pub grid_auto_flow: GridAutoFlowValue, + /// 四边 margin(百分比与 auto 由 layout 解析)。 + pub margin: Edges<MarginValue>, + /// 四边 padding(百分比由 layout 解析)。 + pub padding: Edges<PaddingValue>, + /// 四边 border 宽度(computed 值:style 为 none/hidden 时为 0)。 + pub border_width: Edges<f32>, + /// 四边 border 样式。 + pub border_style: Edges<BorderStyle>, + /// 四边 border 颜色(currentcolor 已按本元素 color 解析)。 + pub border_color: Edges<Rgba>, +} + +/// 四边值(top / right / bottom / left)。 +#[derive(Debug, Clone, Copy, PartialEq)] +pub struct Edges<T> { + /// 上边。 + pub top: T, + /// 右边。 + pub right: T, + /// 下边。 + pub bottom: T, + /// 左边。 + pub left: T, +} + +impl<T: Copy> Edges<T> { + /// 用同一值填充四边。 + #[must_use] + pub const fn splat(value: T) -> Self { + Self { + top: value, + right: value, + bottom: value, + left: value, + } + } +} + +impl ComputedStyle { + /// 全部属性取 initial 值。 + /// + /// initial 值逐条对应各属性规范;UA 相关的(`color` 的 `CanvasText`、 + /// `font-family` 的 UA 默认、`font-size` 的 medium、`line-height` 的 + /// normal)取本层固定选择:黑色、serif、16px。 + #[must_use] + pub fn initial() -> Self { + Self { + display: DisplayValue::Inline, + color: Rgba::opaque(0, 0, 0), + background_color: Rgba::transparent(), + font_size: MEDIUM_FONT_SIZE, + font_weight: 400.0, + font_style: FontStyleValue::Normal, + font_family: vec![FontFamilyValue::Generic("serif")], + text_align: TextAlignValue::Start, + line_height: LineHeightValue::Normal, + white_space: WhiteSpaceValue::Normal, + overflow_wrap: OverflowWrapValue::Normal, + word_break: WordBreakValue::Normal, + letter_spacing: 0.0, + word_spacing: SpacingValue::Normal, + text_indent: TextIndentValue::Length(0.0), + tab_size: TabSizeValue::Integer(8), + width: SizeValue::Auto, + height: SizeValue::Auto, + min_width: SizeValue::Auto, + max_width: SizeValue::Auto, + min_height: SizeValue::Auto, + max_height: SizeValue::Auto, + box_sizing: BoxSizingValue::ContentBox, + overflow: OverflowValue::Visible, + flex_grow: 0.0, + flex_basis: SizeValue::Auto, + position: PositionValue::Static, + float: FloatValue::None, + clear: ClearValue::None, + inset: Edges::splat(InsetValue::Auto), + flex_direction: FlexDirectionValue::Row, + flex_wrap: FlexWrapValue::NoWrap, + flex_shrink: 1.0, + align_items: AlignItemsValue::Stretch, + justify_content: JustifyContentValue::FlexStart, + align_self: AlignSelfValue::Auto, + grid_template_columns: GridTrackList::default(), + grid_template_rows: GridTrackList::default(), + row_gap: GapValue::Normal, + column_gap: GapValue::Normal, + grid_auto_flow: GridAutoFlowValue::Row, + margin: Edges::splat(MarginValue::Length(0.0)), + padding: Edges::splat(PaddingValue::Length(0.0)), + border_width: Edges::splat(0.0), + border_style: Edges::splat(BorderStyle::None), + border_color: Edges::splat(Rgba::opaque(0, 0, 0)), + } + } +} + +impl PropertyId { + /// 属性是否继承(各属性规范 "Inherited" 行)。 + #[must_use] + pub fn inherited(self) -> bool { + matches!( + self, + Self::Color + | Self::FontSize + | Self::FontWeight + | Self::FontStyle + | Self::FontFamily + | Self::TextAlign + | Self::LineHeight + | Self::WhiteSpace + | Self::OverflowWrap + | Self::WordBreak + | Self::LetterSpacing + | Self::WordSpacing + | Self::TextIndent + | Self::TabSize + ) + } +} + +/// 全部属性的固定枚举顺序。 +/// +/// 顺序承载计算依赖:`FontSize` 先于 `LineHeight`(百分比按自身字号折算)、 +/// `Color` 先于 border 颜色(currentcolor)、border style 先于 width +/// (none/hidden 时宽度归零)。 +const PROPERTY_ORDER: [PropertyId; 64] = [ + PropertyId::Display, + PropertyId::Color, + PropertyId::BackgroundColor, + PropertyId::FontSize, + PropertyId::FontWeight, + PropertyId::FontStyle, + PropertyId::FontFamily, + PropertyId::TextAlign, + PropertyId::LineHeight, + PropertyId::WhiteSpace, + PropertyId::OverflowWrap, + PropertyId::WordBreak, + PropertyId::LetterSpacing, + PropertyId::WordSpacing, + PropertyId::TextIndent, + PropertyId::TabSize, + PropertyId::Width, + PropertyId::Height, + PropertyId::MinWidth, + PropertyId::MaxWidth, + PropertyId::MinHeight, + PropertyId::MaxHeight, + PropertyId::BoxSizing, + PropertyId::Overflow, + PropertyId::FlexGrow, + PropertyId::FlexBasis, + PropertyId::Position, + PropertyId::Float, + PropertyId::Clear, + PropertyId::Top, + PropertyId::Right, + PropertyId::Bottom, + PropertyId::Left, + PropertyId::FlexDirection, + PropertyId::FlexWrap, + PropertyId::FlexShrink, + PropertyId::AlignItems, + PropertyId::JustifyContent, + PropertyId::AlignSelf, + PropertyId::GridTemplateColumns, + PropertyId::GridTemplateRows, + PropertyId::RowGap, + PropertyId::ColumnGap, + PropertyId::GridAutoFlow, + PropertyId::MarginTop, + PropertyId::MarginRight, + PropertyId::MarginBottom, + PropertyId::MarginLeft, + PropertyId::PaddingTop, + PropertyId::PaddingRight, + PropertyId::PaddingBottom, + PropertyId::PaddingLeft, + PropertyId::BorderTopStyle, + PropertyId::BorderRightStyle, + PropertyId::BorderBottomStyle, + PropertyId::BorderLeftStyle, + PropertyId::BorderTopWidth, + PropertyId::BorderRightWidth, + PropertyId::BorderBottomWidth, + PropertyId::BorderLeftWidth, + PropertyId::BorderTopColor, + PropertyId::BorderRightColor, + PropertyId::BorderBottomColor, + PropertyId::BorderLeftColor, +]; + +/// 级联 origin 桶(CSS Cascade 5 §6.4,仅 UA 与 author 两个 origin; +/// user origin 尚未引入)。 +/// +/// 值越大优先级越高:UA 普通 < author 普通 < author `!important` < +/// UA `!important`。 +#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord)] +enum OriginBucket { + UaNormal = 0, + AuthorNormal = 1, + AuthorImportant = 2, + UaImportant = 3, +} + +/// 级联排序键(CSS Cascade 5 §6.4)。 +/// +/// 字典序即优先级:先 origin/importance 桶;author 声明中内联样式排在 +/// 样式表声明之后(§6.4 style attribute);然后按特异度、规则顺序、声明顺序。 +#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord)] +struct CascadeKey { + bucket: OriginBucket, + inline: bool, + specificity: u32, + rule_order: usize, + declaration_order: usize, +} + +/// 级联 origin(CSS Cascade 5 §6.4;user origin 尚未引入)。 +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +enum Origin { + Ua, + Author, +} + +/// origin + importance → 排序桶:UA 普通 < author 普通 < author `!important` +/// < UA `!important`。 +fn bucket_of(origin: Origin, important: bool) -> OriginBucket { + match (origin, important) { + (Origin::Ua, false) => OriginBucket::UaNormal, + (Origin::Author, false) => OriginBucket::AuthorNormal, + (Origin::Author, true) => OriginBucket::AuthorImportant, + (Origin::Ua, true) => OriginBucket::UaImportant, + } +} + +/// 选择器的必要条件(M5 分桶):匹配该选择器的元素**必然**满足的条件。 +/// +/// 只取顶层 compound 里的直接简单选择器(`Class` / `ID` / `LocalName`)—— +/// `:is()` / `:where()` / `:has()` 内部是备选分支而非必要条件,含组合器的 +/// 选择器其条件分布在多个 compound 上,一概保守回落 +/// [`Requirement::Always`]。键统一 ASCII 小写:quirks 模式的 +/// case-insensitive 与严格模式都只会「多测不会漏」(大小写不同的名字折到 +/// 同一键,仍然进入匹配)。 +#[derive(Debug, Clone, PartialEq, Eq, Hash)] +enum Requirement { + /// 元素必须带有该 class。 + Class(String), + /// 元素必须是该标签名。 + Tag(String), + /// 元素必须带有该 id。 + Id(String), + /// 无可提取的必要条件:每元素必测。 + Always, +} + +/// 从一条已解析选择器提取必要条件(优先 id > class > tag,其余 Always)。 +fn requirement_of(selector: &NextySelector) -> Requirement { + use selectors::parser::Component; + use std::borrow::Borrow; + let mut class: Option<&str> = None; + let mut tag: Option<&str> = None; + for component in selector.selector.iter_raw_match_order() { + match component { + // 组合器连接多个 compound:条件不再唯一,保守全测 + Component::Combinator(_) => return Requirement::Always, + Component::ID(atom) => { + return Requirement::Id(atom_str(atom).to_ascii_lowercase()); + } + Component::Class(atom) if class.is_none() => class = Some(atom_str(atom)), + Component::LocalName(local) if tag.is_none() => tag = Some(local.lower_name.borrow()), + _ => {} + } + } + if let Some(class) = class { + return Requirement::Class(class.to_ascii_lowercase()); + } + if let Some(tag) = tag { + return Requirement::Tag(tag.to_ascii_lowercase()); + } + Requirement::Always +} + +/// 桶内候选:一次选择器测试的全部输入(特异度已在解析期算好)。 +struct Candidate<'a> { + /// 规则在所属 origin 展平序列中的序号(CascadeKey::rule_order)。 + rule_order: usize, + /// 展平选择器槽位(同元素去重用:同一选择器可出现在多个桶)。 + slot: usize, + selector: &'a NextySelector, +} + +/// 一组样式表的规则桶索引(M5 ④):构建一次,全文档每元素复用。 +/// +/// 语义与全量扫描逐条一致:只有「必要条件已失败」的选择器被跳过——它们 +/// 本就不可能匹配。命中声明仍按 origin → importance → specificity → +/// 源顺序仲裁(CascadeKey 不变)。 +struct SheetIndex<'a> { + /// 展平的(序号, 规则)序列:rule_order 与声明借用的来源。 + rules: Vec<(usize, &'a StyleRule)>, + class: HashMap<String, Vec<Candidate<'a>>>, + tag: HashMap<String, Vec<Candidate<'a>>>, + id: HashMap<String, Vec<Candidate<'a>>>, + /// 无可提取必要条件的选择器:每元素必测。 + always: Vec<Candidate<'a>>, + /// 展平选择器总数(去重 scratch 的尺寸)。 + selector_count: usize, +} + +impl<'a> SheetIndex<'a> { + /// 为一组样式表构建索引(规则按传入顺序、选择器按源顺序展平编号)。 + fn build(sheets: &[&'a Stylesheet]) -> Self { + let mut rules = Vec::new(); + let mut class: HashMap<String, Vec<Candidate<'a>>> = HashMap::new(); + let mut tag: HashMap<String, Vec<Candidate<'a>>> = HashMap::new(); + let mut id: HashMap<String, Vec<Candidate<'a>>> = HashMap::new(); + let mut always = Vec::new(); + let mut selector_count = 0usize; + for (rule_order, rule) in sheets.iter().flat_map(|sheet| sheet.rules()).enumerate() { + rules.push((rule_order, rule)); + for selector in rule.selectors() { + let slot = selector_count; + selector_count += 1; + let candidate = Candidate { + rule_order, + slot, + selector, + }; + match requirement_of(selector) { + Requirement::Class(key) => class.entry(key).or_default().push(candidate), + Requirement::Tag(key) => tag.entry(key).or_default().push(candidate), + Requirement::Id(key) => id.entry(key).or_default().push(candidate), + Requirement::Always => always.push(candidate), + } + } + } + Self { + rules, + class, + tag, + id, + always, + selector_count, + } + } + + /// 元素的必要条件集合:class 列表 + tag + id(键与桶同为小写)。 + fn requirements_of( + document: &Document, + element: NodeId, + ) -> (Vec<String>, String, Option<String>) { + let Some(NodeKind::Element(data)) = document.node(element) else { + return (Vec::new(), String::new(), None); + }; + let attribute = |name: &str| { + data.attributes + .iter() + .find(|attr| attr.namespace == nexty_dom::Namespace::None && attr.name == name) + .map(|attr| attr.value.as_str()) + }; + let classes = attribute("class") + .map(|value| { + value + .split_ascii_whitespace() + .map(str::to_ascii_lowercase) + .collect() + }) + .unwrap_or_default(); + let tag = data.name.to_ascii_lowercase(); + let id = attribute("id").map(str::to_ascii_lowercase); + (classes, tag, id) + } +} + +/// 元素级收集的去重 scratch:跨元素复用(epoch 标记免清零)。 +#[derive(Default)] +struct GatherScratch { + seen: Vec<u32>, + epoch: u32, +} + +/// 收集一个元素在 UA + author 两个索引下的全部命中声明(引用,零克隆)。 +/// +/// `inline` 是本元素的内联样式解析结果([`InlineStyleCache`] 或现解析), +/// 声明同样以引用进入 matched——声明的生命周期覆盖 `resolve_all` 调用。 +fn collect_matched<'a: 'd, 'd>( + document: &Document, + element: NodeId, + ua: Option<&'a SheetIndex<'a>>, + author: &'a SheetIndex<'a>, + inline: Option<&'d [Declaration]>, + scratch: &mut GatherScratch, + matched: &mut Vec<(CascadeKey, &'d Declaration)>, +) { + // 把一个桶的去重候选并入 test(嵌套 fn 而非闭包:参数需要显式生命周期) + fn push_bucket<'a>( + bucket: &'a [Candidate<'a>], + is_ua: bool, + slot_offset: usize, + seen: &mut [u32], + epoch: u32, + test: &mut Vec<(&'a Candidate<'a>, bool)>, + ) { + for candidate in bucket { + let slot = candidate.slot + slot_offset; + if seen[slot] == epoch { + continue; + } + seen[slot] = epoch; + test.push((candidate, is_ua)); + } + } + + // 从一个索引的全部相关桶收集候选 + fn gather<'a>( + index: &'a SheetIndex<'a>, + document: &Document, + element: NodeId, + is_ua: bool, + slot_offset: usize, + scratch: &mut GatherScratch, + test: &mut Vec<(&'a Candidate<'a>, bool)>, + ) { + let (classes, tag, id) = SheetIndex::requirements_of(document, element); + for key in &classes { + if let Some(bucket) = index.class.get(key) { + push_bucket( + bucket, + is_ua, + slot_offset, + &mut scratch.seen, + scratch.epoch, + test, + ); + } + } + if let Some(bucket) = index.tag.get(&tag) { + push_bucket( + bucket, + is_ua, + slot_offset, + &mut scratch.seen, + scratch.epoch, + test, + ); + } + if let Some(id) = &id + && let Some(bucket) = index.id.get(id) + { + push_bucket( + bucket, + is_ua, + slot_offset, + &mut scratch.seen, + scratch.epoch, + test, + ); + } + push_bucket( + &index.always, + is_ua, + slot_offset, + &mut scratch.seen, + scratch.epoch, + test, + ); + } + + // 命中规则的声明组按引用入 matched(嵌套 fn:显式生命周期) + fn push_rule<'d>( + matched: &mut Vec<(CascadeKey, &'d Declaration)>, + origin: Origin, + rule_order: usize, + specificity: Option<u32>, + declarations: &'d [Declaration], + ) { + let Some(specificity) = specificity else { + return; + }; + for (declaration_order, declaration) in declarations.iter().enumerate() { + matched.push(( + CascadeKey { + bucket: bucket_of(origin, declaration.important), + inline: false, + specificity, + rule_order, + declaration_order, + }, + declaration, + )); + } + } + + // 槽位跨两个索引全局唯一:author 从 0 起,UA 偏移其后(去重 scratch) + let slot_count = author.selector_count + ua.map_or(0, |index| index.selector_count); + if scratch.seen.len() < slot_count { + scratch.seen.resize(slot_count, 0); + } + scratch.epoch = scratch.epoch.wrapping_add(1); + + // 逐桶收集候选选择器(epoch 去重:同一选择器可能同时命中多个 class 桶) + let mut test: Vec<(&Candidate<'a>, bool)> = Vec::new(); // (候选, 是否 UA) + if let Some(ua) = ua { + gather( + ua, + document, + element, + true, + author.selector_count, + scratch, + &mut test, + ); + } + gather(author, document, element, false, 0, scratch, &mut test); + + // 测试候选选择器:命中者按规则聚合最大特异度(与全量扫描一致: + // 声明的特异度取其匹配选择器中的最大值;UA 与 author 各自独立序号空间) + let mut author_specificity: Vec<Option<u32>> = vec![None; author.rules.len()]; + let mut ua_specificity = ua.map(|index| vec![None; index.rules.len()]); + for (candidate, is_ua) in &test { + if !match_element_selectors(std::slice::from_ref(candidate.selector), document, element) { + continue; + } + let slots = if *is_ua { + ua_specificity.as_mut().expect("ua slots sized") + } else { + &mut author_specificity + }; + let entry = &mut slots[candidate.rule_order]; + *entry = Some(entry.map_or(candidate.selector.specificity, |current| { + current.max(candidate.selector.specificity) + })); + } + + // 生成 matched:author 表 + UA 表 + 内联(声明全部按引用) + for &(rule_order, rule) in &author.rules { + push_rule( + matched, + Origin::Author, + rule_order, + author_specificity[rule_order], + rule.declarations(), + ); + } + if let (Some(ua), Some(slots)) = (ua, ua_specificity.as_ref()) { + for &(rule_order, rule) in &ua.rules { + push_rule( + matched, + Origin::Ua, + rule_order, + slots[rule_order], + rule.declarations(), + ); + } + } + if let Some(inline) = inline { + for (declaration_order, declaration) in inline.iter().enumerate() { + matched.push(( + CascadeKey { + bucket: bucket_of(Origin::Author, declaration.important), + inline: true, + specificity: 0, + rule_order: usize::MAX, + declaration_order, + }, + declaration, + )); + } + } +} + +/// 内联样式解析缓存(M5 ②):元素 →(style 属性原文, 解析结果)。 +/// +/// recascade 时按**属性原文**校验——原文未变直接复用解析结果,不重解析 +/// 字符串。以原文为键保证任意来源的属性变更都自动失效(校验是廉价的 +/// 字符串比较)。存方(如 chrome 的 `Page`)跨级联调用持有本缓存。 +#[derive(Default)] +pub struct InlineStyleCache { + entries: HashMap<NodeId, (String, Vec<Declaration>)>, +} + +impl InlineStyleCache { + /// 空缓存。 + #[must_use] + pub fn new() -> Self { + Self::default() + } + + /// 元素内联声明的借用:原文命中直接复用,未命中现解析并入库。 + /// 无 style 属性返回 `None`。 + fn declarations_of(&mut self, document: &Document, element: NodeId) -> Option<&[Declaration]> { + let Some(NodeKind::Element(data)) = document.node(element) else { + return None; + }; + let attribute = data + .attributes + .iter() + .find(|attr| attr.namespace == nexty_dom::Namespace::None && attr.name == "style")? + .value + .clone(); + // 快路径:原文未变直接复用(属性原文是解析结果失效的唯一来源) + if let Some((cached, _)) = self.entries.get(&element) + && *cached == attribute + { + return Some(&self.entries[&element].1); + } + let declarations = parse_inline_style(&attribute); + self.entries.insert(element, (attribute, declarations)); + Some(&self.entries[&element].1) + } +} + +/// 对单个元素做级联,产出 computed style。 +/// +/// `ua_sheet` 是 UA origin 样式表(浏览器默认样式),参与级联但优先级 +/// 低于 author 声明(UA `!important` 最高,见 [`OriginBucket`])。 +/// `parent` 是树序父元素的 computed style(元素没有元素祖先时为 `None`)。 +/// 各属性:级联胜者 → CSS-wide 关键字 → 继承 → initial。 +/// 无视口信息:视口单位原样保留(见 [`cascade_in`])。 +#[must_use] +pub fn cascade( + document: &Document, + element: NodeId, + stylesheets: &[&Stylesheet], + ua_sheet: Option<&Stylesheet>, + parent: Option<&ComputedStyle>, +) -> ComputedStyle { + cascade_in(document, element, stylesheets, ua_sheet, parent, None) +} + +/// [`cascade`] 的带视口版本:视口单位(vw/vh/vmin/vmax)在 computed 阶段 +/// 按给定视口折算为绝对 px(CSS Values 4 §6.2:1v* = 视口对应边的 1%)。 +/// 未提供视口时视口单位原样保留,由消费方按降级值处理。 +/// +/// 单元素入口每次调用重建一次规则桶索引(O(选择器总数),远小于逐元素 +/// 全量扫描);整文档入口走 [`compute_document_styles_in_with_cache`], +/// 索引只建一次。 +#[must_use] +pub fn cascade_in( + document: &Document, + element: NodeId, + stylesheets: &[&Stylesheet], + ua_sheet: Option<&Stylesheet>, + parent: Option<&ComputedStyle>, + viewport: Option<MediaViewport>, +) -> ComputedStyle { + let author = SheetIndex::build(stylesheets); + let ua = ua_sheet.map(|sheet| SheetIndex::build(std::slice::from_ref(&sheet))); + let mut scratch = GatherScratch::default(); + let mut cache = InlineStyleCache::new(); + let inline = cache.declarations_of(document, element); + let mut matched: Vec<(CascadeKey, &Declaration)> = Vec::new(); + collect_matched( + document, + element, + ua.as_ref(), + &author, + inline, + &mut scratch, + &mut matched, + ); + resolve_all(&matched, parent, viewport) +} + +/// 按树序计算整份文档的 computed style(父先于子)。 +/// +/// `<template>` 的内容子树是惰性片段,不参与级联,跳过。 +#[must_use] +pub fn compute_document_styles( + document: &Document, + stylesheets: &[&Stylesheet], + ua_sheet: Option<&Stylesheet>, +) -> HashMap<NodeId, ComputedStyle> { + compute_document_styles_in(document, stylesheets, ua_sheet, None) +} + +/// [`compute_document_styles`] 的带视口版本:视口单位(vw/vh/vmin/vmax) +/// 在 computed 阶段按给定视口折算为绝对 px(CSS Values 4 §6.2)。 +/// 未提供视口时视口单位原样保留,由消费方按降级值处理。 +/// +/// 规则桶索引本调用内构建一次;内联样式每次重解析(无跨调用缓存)。 +#[must_use] +pub fn compute_document_styles_in( + document: &Document, + stylesheets: &[&Stylesheet], + ua_sheet: Option<&Stylesheet>, + viewport: Option<MediaViewport>, +) -> HashMap<NodeId, ComputedStyle> { + let mut cache = InlineStyleCache::new(); + compute_document_styles_in_with_cache(document, stylesheets, ua_sheet, viewport, &mut cache) +} + +/// [`compute_document_styles_in`] 的带缓存版本(M5 ②):调用方跨调用持有 +/// [`InlineStyleCache`] 时,recascade 对未变化的 style 属性直接复用解析 +/// 结果,不重解析字符串。 +#[must_use] +pub fn compute_document_styles_in_with_cache( + document: &Document, + stylesheets: &[&Stylesheet], + ua_sheet: Option<&Stylesheet>, + viewport: Option<MediaViewport>, + cache: &mut InlineStyleCache, +) -> HashMap<NodeId, ComputedStyle> { + // 规则桶索引:构建一次(O(选择器总数)),全文档每元素复用 + let mut ctx = CascadeCtx { + ua: ua_sheet.map(|sheet| SheetIndex::build(std::slice::from_ref(&sheet))), + author: SheetIndex::build(stylesheets), + viewport, + cache, + scratch: GatherScratch::default(), + }; + let mut styles = HashMap::new(); + walk(document, document.root(), None, &mut ctx, &mut styles); + styles +} + +/// 整文档级联的共享上下文(M5):规则桶索引(构建一次)、视口、内联样式 +/// 缓存与去重 scratch,由 [`walk`] 全文档复用。 +struct CascadeCtx<'a, 'c> { + ua: Option<SheetIndex<'a>>, + author: SheetIndex<'a>, + viewport: Option<MediaViewport>, + cache: &'c mut InlineStyleCache, + scratch: GatherScratch, +} + +fn walk( + document: &Document, + node: NodeId, + parent: Option<&ComputedStyle>, + ctx: &mut CascadeCtx<'_, '_>, + out: &mut HashMap<NodeId, ComputedStyle>, +) { + for child in document.children(node) { + if matches!(document.node(child), Some(NodeKind::Element(_))) { + // matched 借用 cache 与索引,块结束即释放(递归前必须归还) + let style = { + let CascadeCtx { + ua, + author, + viewport, + cache, + scratch, + } = &mut *ctx; + let inline = cache.declarations_of(document, child); + let mut matched: Vec<(CascadeKey, &Declaration)> = Vec::new(); + collect_matched( + document, + child, + ua.as_ref(), + author, + inline, + scratch, + &mut matched, + ); + resolve_all(&matched, parent, *viewport) + }; + walk(document, child, Some(&style), ctx, out); + out.insert(child, style); + } + } +} + +/// 某属性在级联中的胜者声明。 +fn winner<'d>( + property: PropertyId, + matched: &[(CascadeKey, &'d Declaration)], +) -> Option<&'d Declaration> { + matched + .iter() + .filter(|(_, declaration)| declaration.property == property) + .max_by_key(|(key, _)| *key) + .map(|(_, declaration)| *declaration) +} + +/// 胜者决定该属性的来源。 +enum Decision<'a> { + /// 使用级联胜者的属性值。 + Use(&'a PropertyValue), + /// 取父元素的 computed value;无父元素则取 initial。 + Parent, + /// 取 initial 值。 + Initial, +} + +fn decide<'a>( + property: PropertyId, + winner: Option<&'a Declaration>, + parent: Option<&ComputedStyle>, +) -> Decision<'a> { + let has_parent = parent.is_some(); + match winner { + Some(Declaration { + value: DeclaredValue::Typed(value), + .. + }) => Decision::Use(value), + Some(Declaration { + value: DeclaredValue::CssWide(keyword), + .. + }) => match keyword { + // revert 回退到 UA origin;本层 UA 无声明,等价 initial + CssWideKeyword::Initial | CssWideKeyword::Revert => Decision::Initial, + CssWideKeyword::Inherit => Decision::Parent, + CssWideKeyword::Unset => { + if property.inherited() && has_parent { + Decision::Parent + } else { + Decision::Initial + } + } + }, + // 无声明:继承属性取父值,否则取 initial(CSS Cascade 5 §7) + None => { + if property.inherited() && has_parent { + Decision::Parent + } else { + Decision::Initial + } + } + } +} + +/// 视口单位折算为 px:1v* = 视口对应边的 1%(CSS Values 4 §6.2)。 +/// +/// 折算乘积同样过卫生钳:巨数量 × 视口基数不得产生 `inf`。 +fn viewport_px(amount: f32, unit: ViewportUnit, viewport: MediaViewport) -> f32 { + let base = match unit { + ViewportUnit::Vw => viewport.width, + ViewportUnit::Vh => viewport.height, + ViewportUnit::Vmin => viewport.width.min(viewport.height), + ViewportUnit::Vmax => viewport.width.max(viewport.height), + }; + clamp_computed(amount * base / 100.0) +} + +/// 计算出口的长度卫生:有限值 clamp 到上限;±inf 钳到边界;NaN 归 0 +/// (相对单位乘积可能越过解析期的钳值,计算值必须仍落在预算内)。 +fn clamp_computed(value: f32) -> f32 { + if value.is_nan() { + 0.0 + } else { + value.clamp(-MAX_CSS_LENGTH, MAX_CSS_LENGTH) + } +} + +macro_rules! resolve_viewport { + ($fn_name:ident, $enum:ident) => { + fn $fn_name(value: $enum, viewport: Option<MediaViewport>) -> $enum { + match value { + $enum::Viewport(amount, unit) => match viewport { + Some(vp) => $enum::Length(viewport_px(amount, unit, vp)), + None => $enum::Viewport(amount, unit), + }, + other => other, + } + } + }; +} + +resolve_viewport!(resolve_size, SizeValue); +resolve_viewport!(resolve_inset, InsetValue); +resolve_viewport!(resolve_margin, MarginValue); +resolve_viewport!(resolve_padding, PaddingValue); +resolve_viewport!(resolve_gap, GapValue); + +/// 逐属性解析出 computed style。 +fn resolve_all( + matched: &[(CascadeKey, &Declaration)], + parent: Option<&ComputedStyle>, + viewport: Option<MediaViewport>, +) -> ComputedStyle { + let initial = ComputedStyle::initial(); + let mut style = initial.clone(); + let parent_font_size = parent.map_or(MEDIUM_FONT_SIZE, |p| p.font_size); + let parent_font_weight = parent.map_or(400.0, |p| p.font_weight); + + for property in PROPERTY_ORDER { + let decision = decide(property, winner(property, matched), parent); + match (property, decision) { + (PropertyId::Display, Decision::Use(PropertyValue::Display(value))) => { + style.display = *value; + } + (PropertyId::TextAlign, Decision::Use(PropertyValue::TextAlign(value))) => { + style.text_align = *value; + } + (PropertyId::FontStyle, Decision::Use(PropertyValue::FontStyle(value))) => { + style.font_style = *value; + } + (PropertyId::Color, Decision::Use(PropertyValue::Color(value))) => { + style.color = *value; + } + (PropertyId::BackgroundColor, Decision::Use(PropertyValue::Color(value))) => { + style.background_color = *value; + } + (PropertyId::FontSize, Decision::Use(PropertyValue::FontSize(value))) => { + style.font_size = compute_font_size(value, parent_font_size); + } + (PropertyId::FontWeight, Decision::Use(PropertyValue::FontWeight(value))) => { + style.font_weight = compute_font_weight(value, parent_font_weight); + } + (PropertyId::FontFamily, Decision::Use(PropertyValue::FontFamily(value))) => { + style.font_family = value.clone(); + } + (PropertyId::LineHeight, Decision::Use(PropertyValue::LineHeight(value))) => { + // CSS 2.1 §10.8.1:百分比/em 的 computed 值为绝对长度 + //(按本元素自身 font-size,已在 PROPERTY_ORDER 中先求) + style.line_height = match *value { + LineHeightValue::Percent(fraction) => { + LineHeightValue::Length(clamp_computed(style.font_size * fraction)) + } + LineHeightValue::Em(em) => { + LineHeightValue::Length(clamp_computed(style.font_size * em)) + } + other => other, + }; + } + (PropertyId::WhiteSpace, Decision::Use(PropertyValue::WhiteSpace(value))) => { + style.white_space = *value; + } + (PropertyId::OverflowWrap, Decision::Use(PropertyValue::OverflowWrap(value))) => { + style.overflow_wrap = *value; + } + (PropertyId::WordBreak, Decision::Use(PropertyValue::WordBreak(value))) => { + style.word_break = *value; + } + (PropertyId::LetterSpacing, Decision::Use(PropertyValue::LetterSpacing(value))) => { + // CSS Text 3 §8.1:normal 的 used value 与 0 同义 + style.letter_spacing = match *value { + SpacingValue::Normal => 0.0, + SpacingValue::Length(px) => px, + SpacingValue::Em(em) => clamp_computed(style.font_size * em), + }; + } + (PropertyId::WordSpacing, Decision::Use(PropertyValue::WordSpacing(value))) => { + // normal 的语义保留给 layout 判读(CSS Text 3 §8.2) + style.word_spacing = match *value { + SpacingValue::Normal => SpacingValue::Normal, + SpacingValue::Length(px) => SpacingValue::Length(px), + SpacingValue::Em(em) => { + SpacingValue::Length(clamp_computed(style.font_size * em)) + } + }; + } + (PropertyId::TextIndent, Decision::Use(PropertyValue::TextIndent(value))) => { + style.text_indent = match *value { + TextIndentValue::Em(em) => { + TextIndentValue::Length(clamp_computed(style.font_size * em)) + } + other => other, + }; + } + (PropertyId::TabSize, Decision::Use(PropertyValue::TabSize(value))) => { + style.tab_size = match *value { + // 整数形态依赖空格 advance(字体度量),保留给 layout + TabSizeValue::Em(em) => { + TabSizeValue::Length(clamp_computed(style.font_size * em)) + } + other => other, + }; + } + (PropertyId::Width, Decision::Use(PropertyValue::Size(value))) => { + style.width = resolve_size(*value, viewport); + } + (PropertyId::Height, Decision::Use(PropertyValue::Size(value))) => { + style.height = resolve_size(*value, viewport); + } + (PropertyId::MinWidth, Decision::Use(PropertyValue::Size(value))) => { + style.min_width = resolve_size(*value, viewport); + } + (PropertyId::MaxWidth, Decision::Use(PropertyValue::Size(value))) => { + style.max_width = resolve_size(*value, viewport); + } + (PropertyId::MinHeight, Decision::Use(PropertyValue::Size(value))) => { + style.min_height = resolve_size(*value, viewport); + } + (PropertyId::MaxHeight, Decision::Use(PropertyValue::Size(value))) => { + style.max_height = resolve_size(*value, viewport); + } + (PropertyId::BoxSizing, Decision::Use(PropertyValue::BoxSizing(value))) => { + style.box_sizing = *value; + } + (PropertyId::Overflow, Decision::Use(PropertyValue::Overflow(value))) => { + style.overflow = *value; + } + (PropertyId::FlexGrow, Decision::Use(PropertyValue::FlexGrow(value))) => { + style.flex_grow = *value; + } + (PropertyId::FlexBasis, Decision::Use(PropertyValue::FlexBasis(value))) => { + style.flex_basis = *value; + } + (PropertyId::Position, Decision::Use(PropertyValue::Position(value))) => { + style.position = *value; + } + (PropertyId::Float, Decision::Use(PropertyValue::Float(value))) => { + style.float = *value; + } + (PropertyId::Clear, Decision::Use(PropertyValue::Clear(value))) => { + style.clear = *value; + } + (PropertyId::Top, Decision::Use(PropertyValue::Inset(value))) => { + style.inset.top = resolve_inset(*value, viewport); + } + (PropertyId::Right, Decision::Use(PropertyValue::Inset(value))) => { + style.inset.right = resolve_inset(*value, viewport); + } + (PropertyId::Bottom, Decision::Use(PropertyValue::Inset(value))) => { + style.inset.bottom = resolve_inset(*value, viewport); + } + (PropertyId::Left, Decision::Use(PropertyValue::Inset(value))) => { + style.inset.left = resolve_inset(*value, viewport); + } + (PropertyId::FlexDirection, Decision::Use(PropertyValue::FlexDirection(value))) => { + style.flex_direction = *value; + } + (PropertyId::FlexWrap, Decision::Use(PropertyValue::FlexWrap(value))) => { + style.flex_wrap = *value; + } + (PropertyId::FlexShrink, Decision::Use(PropertyValue::FlexShrink(value))) => { + style.flex_shrink = *value; + } + (PropertyId::AlignItems, Decision::Use(PropertyValue::AlignItems(value))) => { + style.align_items = *value; + } + (PropertyId::JustifyContent, Decision::Use(PropertyValue::JustifyContent(value))) => { + style.justify_content = *value; + } + (PropertyId::AlignSelf, Decision::Use(PropertyValue::AlignSelf(value))) => { + style.align_self = *value; + } + (PropertyId::GridTemplateColumns, Decision::Use(PropertyValue::GridTrack(value))) => { + style.grid_template_columns = value.clone(); + } + (PropertyId::GridTemplateRows, Decision::Use(PropertyValue::GridTrack(value))) => { + style.grid_template_rows = value.clone(); + } + (PropertyId::RowGap, Decision::Use(PropertyValue::Gap(value))) => { + style.row_gap = resolve_gap(*value, viewport); + } + (PropertyId::ColumnGap, Decision::Use(PropertyValue::Gap(value))) => { + style.column_gap = resolve_gap(*value, viewport); + } + (PropertyId::GridAutoFlow, Decision::Use(PropertyValue::GridAutoFlow(value))) => { + style.grid_auto_flow = *value; + } + (PropertyId::MarginTop, Decision::Use(PropertyValue::Margin(value))) => { + style.margin.top = resolve_margin(*value, viewport); + } + (PropertyId::MarginRight, Decision::Use(PropertyValue::Margin(value))) => { + style.margin.right = resolve_margin(*value, viewport); + } + (PropertyId::MarginBottom, Decision::Use(PropertyValue::Margin(value))) => { + style.margin.bottom = resolve_margin(*value, viewport); + } + (PropertyId::MarginLeft, Decision::Use(PropertyValue::Margin(value))) => { + style.margin.left = resolve_margin(*value, viewport); + } + (PropertyId::PaddingTop, Decision::Use(PropertyValue::Padding(value))) => { + style.padding.top = resolve_padding(*value, viewport); + } + (PropertyId::PaddingRight, Decision::Use(PropertyValue::Padding(value))) => { + style.padding.right = resolve_padding(*value, viewport); + } + (PropertyId::PaddingBottom, Decision::Use(PropertyValue::Padding(value))) => { + style.padding.bottom = resolve_padding(*value, viewport); + } + (PropertyId::PaddingLeft, Decision::Use(PropertyValue::Padding(value))) => { + style.padding.left = resolve_padding(*value, viewport); + } + (PropertyId::BorderTopStyle, Decision::Use(PropertyValue::BorderStyle(value))) => { + style.border_style.top = *value; + } + (PropertyId::BorderRightStyle, Decision::Use(PropertyValue::BorderStyle(value))) => { + style.border_style.right = *value; + } + (PropertyId::BorderBottomStyle, Decision::Use(PropertyValue::BorderStyle(value))) => { + style.border_style.bottom = *value; + } + (PropertyId::BorderLeftStyle, Decision::Use(PropertyValue::BorderStyle(value))) => { + style.border_style.left = *value; + } + (PropertyId::BorderTopWidth, Decision::Use(PropertyValue::BorderWidth(value))) => { + style.border_width.top = used_border_width(*value, style.border_style.top); + } + (PropertyId::BorderRightWidth, Decision::Use(PropertyValue::BorderWidth(value))) => { + style.border_width.right = used_border_width(*value, style.border_style.right); + } + (PropertyId::BorderBottomWidth, Decision::Use(PropertyValue::BorderWidth(value))) => { + style.border_width.bottom = used_border_width(*value, style.border_style.bottom); + } + (PropertyId::BorderLeftWidth, Decision::Use(PropertyValue::BorderWidth(value))) => { + style.border_width.left = used_border_width(*value, style.border_style.left); + } + (PropertyId::BorderTopColor, Decision::Use(PropertyValue::BorderColor(value))) => { + style.border_color.top = resolve_border_color(*value, style.color); + } + (PropertyId::BorderRightColor, Decision::Use(PropertyValue::BorderColor(value))) => { + style.border_color.right = resolve_border_color(*value, style.color); + } + (PropertyId::BorderBottomColor, Decision::Use(PropertyValue::BorderColor(value))) => { + style.border_color.bottom = resolve_border_color(*value, style.color); + } + (PropertyId::BorderLeftColor, Decision::Use(PropertyValue::BorderColor(value))) => { + style.border_color.left = resolve_border_color(*value, style.color); + } + // 关键字与继承:按属性回退 + (property, decision @ (Decision::Parent | Decision::Initial)) => { + let source = match decision { + Decision::Parent => parent.unwrap_or(&initial), + _ => &initial, + }; + match property { + PropertyId::Display => style.display = source.display, + PropertyId::Color => style.color = source.color, + PropertyId::BackgroundColor => style.background_color = source.background_color, + PropertyId::FontSize => style.font_size = source.font_size, + PropertyId::FontWeight => style.font_weight = source.font_weight, + PropertyId::FontStyle => style.font_style = source.font_style, + PropertyId::FontFamily => style.font_family = source.font_family.clone(), + PropertyId::TextAlign => style.text_align = source.text_align, + PropertyId::LineHeight => style.line_height = source.line_height, + PropertyId::WhiteSpace => style.white_space = source.white_space, + PropertyId::OverflowWrap => style.overflow_wrap = source.overflow_wrap, + PropertyId::WordBreak => style.word_break = source.word_break, + PropertyId::LetterSpacing => style.letter_spacing = source.letter_spacing, + PropertyId::WordSpacing => style.word_spacing = source.word_spacing, + PropertyId::TextIndent => style.text_indent = source.text_indent, + PropertyId::TabSize => style.tab_size = source.tab_size, + PropertyId::Width => style.width = source.width, + PropertyId::Height => style.height = source.height, + PropertyId::MinWidth => style.min_width = source.min_width, + PropertyId::MaxWidth => style.max_width = source.max_width, + PropertyId::MinHeight => style.min_height = source.min_height, + PropertyId::MaxHeight => style.max_height = source.max_height, + PropertyId::BoxSizing => style.box_sizing = source.box_sizing, + PropertyId::Overflow => style.overflow = source.overflow, + PropertyId::FlexGrow => style.flex_grow = source.flex_grow, + PropertyId::FlexBasis => style.flex_basis = source.flex_basis, + PropertyId::Position => style.position = source.position, + PropertyId::Float => style.float = source.float, + PropertyId::Clear => style.clear = source.clear, + PropertyId::Top => style.inset.top = source.inset.top, + PropertyId::Right => style.inset.right = source.inset.right, + PropertyId::Bottom => style.inset.bottom = source.inset.bottom, + PropertyId::Left => style.inset.left = source.inset.left, + PropertyId::FlexDirection => style.flex_direction = source.flex_direction, + PropertyId::FlexWrap => style.flex_wrap = source.flex_wrap, + PropertyId::FlexShrink => style.flex_shrink = source.flex_shrink, + PropertyId::AlignItems => style.align_items = source.align_items, + PropertyId::JustifyContent => style.justify_content = source.justify_content, + PropertyId::AlignSelf => style.align_self = source.align_self, + PropertyId::GridTemplateColumns => { + style.grid_template_columns = source.grid_template_columns.clone() + } + PropertyId::GridTemplateRows => { + style.grid_template_rows = source.grid_template_rows.clone() + } + PropertyId::RowGap => style.row_gap = source.row_gap, + PropertyId::ColumnGap => style.column_gap = source.column_gap, + PropertyId::GridAutoFlow => style.grid_auto_flow = source.grid_auto_flow, + PropertyId::MarginTop => style.margin.top = source.margin.top, + PropertyId::MarginRight => style.margin.right = source.margin.right, + PropertyId::MarginBottom => style.margin.bottom = source.margin.bottom, + PropertyId::MarginLeft => style.margin.left = source.margin.left, + PropertyId::PaddingTop => style.padding.top = source.padding.top, + PropertyId::PaddingRight => style.padding.right = source.padding.right, + PropertyId::PaddingBottom => style.padding.bottom = source.padding.bottom, + PropertyId::PaddingLeft => style.padding.left = source.padding.left, + PropertyId::BorderTopStyle => style.border_style.top = source.border_style.top, + PropertyId::BorderRightStyle => { + style.border_style.right = source.border_style.right; + } + PropertyId::BorderBottomStyle => { + style.border_style.bottom = source.border_style.bottom; + } + PropertyId::BorderLeftStyle => { + style.border_style.left = source.border_style.left; + } + PropertyId::BorderTopWidth => style.border_width.top = source.border_width.top, + PropertyId::BorderRightWidth => { + style.border_width.right = source.border_width.right; + } + PropertyId::BorderBottomWidth => { + style.border_width.bottom = source.border_width.bottom; + } + PropertyId::BorderLeftWidth => { + style.border_width.left = source.border_width.left; + } + PropertyId::BorderTopColor => style.border_color.top = source.border_color.top, + PropertyId::BorderRightColor => { + style.border_color.right = source.border_color.right; + } + PropertyId::BorderBottomColor => { + style.border_color.bottom = source.border_color.bottom; + } + PropertyId::BorderLeftColor => { + style.border_color.left = source.border_color.left; + } + } + } + // 声明值与属性不匹配只可能来自程序错误;保持 initial 值 + _ => {} + } + } + style +} + +/// border-*-width 的 computed 值:style 为 none/hidden 时为 0 +/// (CSS 2.1 §8.5.4)。 +fn used_border_width(value: BorderWidthValue, border_style: BorderStyle) -> f32 { + if border_style.visible() { + value.px() + } else { + 0.0 + } +} + +/// border-*-color 的 computed 值:currentcolor 按本元素 color 解析。 +fn resolve_border_color(value: BorderColorValue, color: Rgba) -> Rgba { + match value { + BorderColorValue::Rgba(rgba) => rgba, + BorderColorValue::CurrentColor => color, + } +} + +/// `font-size` 计算值(CSS Fonts 4 §2.5:长度/百分比相对父元素计算字号)。 +/// +/// 相对单位乘积过卫生钳:继承链上的巨数 em/百分比不得算出 `inf`。 +fn compute_font_size(value: &FontSizeValue, parent_font_size: f32) -> f32 { + clamp_computed(match value { + FontSizeValue::Px(px) => *px, + FontSizeValue::Em(em) => parent_font_size * em, + FontSizeValue::Percent(fraction) => parent_font_size * fraction, + FontSizeValue::Absolute(size) => MEDIUM_FONT_SIZE * size.factor(), + FontSizeValue::Larger => adjacent_size(parent_font_size, true), + FontSizeValue::Smaller => adjacent_size(parent_font_size, false), + }) +} + +/// `larger` / `smaller`:父字号恰为绝对尺寸表项时取相邻项 +/// (CSS Fonts 4 §2.5),否则按规范允许的简单比例 1.2 缩放。 +fn adjacent_size(parent_font_size: f32, larger: bool) -> f32 { + const TOLERANCE: f32 = 0.01; + let index = AbsoluteSize::ORDERED + .iter() + .position(|size| (MEDIUM_FONT_SIZE * size.factor() - parent_font_size).abs() <= TOLERANCE); + match index { + Some(index) if larger && index + 1 < AbsoluteSize::ORDERED.len() => { + MEDIUM_FONT_SIZE * AbsoluteSize::ORDERED[index + 1].factor() + } + Some(index) if !larger && index > 0 => { + MEDIUM_FONT_SIZE * AbsoluteSize::ORDERED[index - 1].factor() + } + // 表外或已到表端:简单比例 + _ => { + if larger { + parent_font_size * 1.2 + } else { + parent_font_size / 1.2 + } + } + } +} + +/// `font-weight` 计算值(CSS Fonts 4 §2.2)。 +fn compute_font_weight(value: &FontWeightValue, parent_font_weight: f32) -> f32 { + match value { + FontWeightValue::Weight(weight) => weight.clamp(1.0, 1000.0), + FontWeightValue::Bolder => relative_weight(parent_font_weight, true), + FontWeightValue::Lighter => relative_weight(parent_font_weight, false), + } +} + +/// bolder / lighter 相对映射表(CSS Fonts 4 §2.2.1)。 +fn relative_weight(parent_weight: f32, bolder: bool) -> f32 { + if parent_weight < 100.0 { + if bolder { 400.0 } else { parent_weight } + } else if parent_weight < 350.0 { + if bolder { 400.0 } else { 100.0 } + } else if parent_weight < 550.0 { + if bolder { 700.0 } else { 100.0 } + } else if parent_weight < 750.0 { + if bolder { 900.0 } else { 400.0 } + } else if parent_weight < 900.0 { + if bolder { 900.0 } else { 700.0 } + } else { + // bolder:无更粗字重,保持不变;lighter:700 + if bolder { parent_weight } else { 700.0 } + } +} + +#[cfg(test)] +mod tests { + use super::*; + use crate::html_ua_stylesheet; + use crate::test_support::{build_document, find_first_by_name}; + use crate::value::GridTrack; + + fn style_of(html: &str, sheets: &[&str], name: &str) -> ComputedStyle { + let document = build_document(html); + let parsed: Vec<Stylesheet> = sheets.iter().map(|css| Stylesheet::parse(css)).collect(); + let refs: Vec<&Stylesheet> = parsed.iter().collect(); + let element = find_first_by_name(&document, name).expect("element"); + cascade(&document, element, &refs, None, None) + } + + /// 视口 800×600:vw/vh/vmin/vmax 按对应边 1% 折算为绝对 px。 + #[test] + fn viewport_units_resolve_against_viewport() { + let document = build_document("<div></div>"); + let sheet = Stylesheet::parse( + "div { width: 50vw; min-height: 10vh; margin: 1vmin auto; \ + padding: 1vmax; top: 2vw; row-gap: 3vh }", + ); + let refs = vec![&sheet]; + let div = find_first_by_name(&document, "div").expect("div"); + let viewport = MediaViewport { + width: 800.0, + height: 600.0, + }; + let style = cascade_in(&document, div, &refs, None, None, Some(viewport)); + assert_eq!(style.width, SizeValue::Length(400.0), "50vw = 400px"); + assert_eq!(style.min_height, SizeValue::Length(60.0), "10vh = 60px"); + assert_eq!( + style.margin.top, + MarginValue::Length(6.0), + "1vmin = 6px(短边 600)" + ); + assert_eq!(style.margin.left, MarginValue::Auto, "非视口成分不受影响"); + assert_eq!( + style.padding.top, + PaddingValue::Length(8.0), + "1vmax = 8px(长边 800)" + ); + assert_eq!(style.inset.top, InsetValue::Length(16.0), "2vw = 16px"); + assert_eq!(style.row_gap, GapValue::Length(18.0), "3vh = 18px"); + } + + /// 无视口信息:视口单位原样保留在 computed style 里(消费方降级)。 + #[test] + fn viewport_units_stay_unresolved_without_viewport() { + let style = style_of( + "<div></div>", + &["div { width: 50vw; margin-top: 2vh }"], + "div", + ); + assert_eq!(style.width, SizeValue::Viewport(50.0, ViewportUnit::Vw)); + assert_eq!( + style.margin.top, + MarginValue::Viewport(2.0, ViewportUnit::Vh) + ); + } + + #[test] + fn no_declarations_fall_back_to_inheritance_and_initial() { + let document = build_document("<div style=\"color: red\"><p>x</p></div>"); + let refs: Vec<&Stylesheet> = vec![]; + let div = find_first_by_name(&document, "div").expect("div"); + let div_style = cascade(&document, div, &refs, None, None); + assert_eq!(div_style.color, Rgba::opaque(255, 0, 0), "内联样式生效"); + assert_eq!( + div_style.background_color, + Rgba::transparent(), + "非继承属性取 initial" + ); + + let p = find_first_by_name(&document, "p").expect("p"); + let p_style = cascade(&document, p, &refs, None, Some(&div_style)); + assert_eq!(p_style.color, Rgba::opaque(255, 0, 0), "继承属性取父值"); + assert_eq!(p_style.background_color, Rgba::transparent()); + assert_eq!(p_style.font_size, 16.0); + } + + #[test] + fn specificity_beats_source_order() { + let style = style_of( + "<p class=\"a\">x</p>", + &["p { color: red } .a { color: blue }"], + "p", + ); + assert_eq!(style.color, Rgba::opaque(0, 0, 255)); + } + + #[test] + fn source_order_breaks_ties() { + let style = style_of( + "<p class=\"a\">x</p>", + &[".a { color: blue } p.a { color: red }"], + "p", + ); + assert_eq!(style.color, Rgba::opaque(255, 0, 0)); + } + + #[test] + fn important_beats_specificity() { + let style = style_of( + "<p class=\"a\">x</p>", + &["p.a { color: red } p { color: blue !important }"], + "p", + ); + assert_eq!(style.color, Rgba::opaque(0, 0, 255)); + } + + #[test] + fn inline_style_ordering() { + // 内联普通声明压过样式表普通声明 + let style = style_of("<p style=\"color: red\">x</p>", &["p { color: blue }"], "p"); + assert_eq!(style.color, Rgba::opaque(255, 0, 0)); + + // 样式表 !important 压过内联普通声明 + let style = style_of( + "<p style=\"color: red\">x</p>", + &["p { color: blue !important }"], + "p", + ); + assert_eq!(style.color, Rgba::opaque(0, 0, 255)); + + // 内联 !important 压过样式表 !important + let style = style_of( + "<p style=\"color: red !important\">x</p>", + &["p { color: blue !important }"], + "p", + ); + assert_eq!(style.color, Rgba::opaque(255, 0, 0)); + } + + #[test] + fn matching_rule_selectors_use_max_specificity() { + let style = style_of( + "<p class=\"x\">x</p>", + &["p, .x { color: red } p { color: blue }"], + "p", + ); + assert_eq!(style.color, Rgba::opaque(255, 0, 0)); + } + + #[test] + fn font_size_resolves_against_parent() { + // em / 百分比相对父元素计算字号 + let mut document = build_document( + "<div style=\"font-size: 20px\"><p style=\"font-size: 1.5em\">x</p></div>", + ); + let parsed = Stylesheet::parse(""); + let div = find_first_by_name(&document, "div").expect("div"); + let div_style = cascade(&document, div, &[&parsed], None, None); + assert_eq!(div_style.font_size, 20.0); + let p = find_first_by_name(&document, "p").expect("p"); + let p_style = cascade(&document, p, &[&parsed], None, Some(&div_style)); + assert_eq!(p_style.font_size, 30.0); + + // 继承的是计算值:孙辈再乘 em 时基于 30px + let span = document.create_node(nexty_dom::NodeKind::Element(nexty_dom::ElementData { + name: "span".into(), + namespace: nexty_dom::Namespace::Html, + attributes: Vec::new(), + })); + document.insert_node(span, p, None); + let span_style = cascade(&document, span, &[&parsed], None, Some(&p_style)); + assert_eq!(span_style.font_size, 30.0, "继承计算字号而非声明值"); + } + + #[test] + fn huge_relative_font_size_and_line_height_stay_finite() { + // 巨数 em 的解析值已钳到上限,计算乘积再钳一次:inf 不得进入布局 + let style = style_of( + "<p style=\"font-size: 1e30em; line-height: 1.5em\">x</p>", + &[], + "p", + ); + assert_eq!(style.font_size, MAX_CSS_LENGTH, "16 × 1e30 → 钳到上限"); + let LineHeightValue::Length(line_height) = style.line_height else { + panic!("em 行高应折算为绝对长度"); + }; + assert_eq!(line_height, MAX_CSS_LENGTH, "1.5 × 1e7 → 钳到上限"); + // 负字号钳到下界 + let style = style_of("<p style=\"font-size: -1e30em\">x</p>", &[], "p"); + assert_eq!(style.font_size, -MAX_CSS_LENGTH); + } + + #[test] + fn font_size_keywords_and_relative() { + let style = style_of("<p>x</p>", &["p { font-size: x-large }"], "p"); + assert_eq!(style.font_size, 24.0); + + // larger:父字号在表内时取下一项 + let document = build_document( + "<div style=\"font-size: large\"><p style=\"font-size: larger\">x</p></div>", + ); + let parsed = Stylesheet::parse(""); + let div_style = cascade( + &document, + find_first_by_name(&document, "div").unwrap(), + &[&parsed], + None, + None, + ); + let p_style = cascade( + &document, + find_first_by_name(&document, "p").unwrap(), + &[&parsed], + None, + Some(&div_style), + ); + assert_eq!( + p_style.font_size, + MEDIUM_FONT_SIZE * 1.5, + "large(1.2) → larger(1.5)" + ); + + // 表外字号用 1.2 比例 + let document = build_document( + "<div style=\"font-size: 100px\"><p style=\"font-size: smaller\">x</p></div>", + ); + let div_style = cascade( + &document, + find_first_by_name(&document, "div").unwrap(), + &[&parsed], + None, + None, + ); + let p_style = cascade( + &document, + find_first_by_name(&document, "p").unwrap(), + &[&parsed], + None, + Some(&div_style), + ); + assert!((p_style.font_size - 100.0 / 1.2).abs() < 1e-4); + } + + #[test] + fn font_weight_relative_table() { + // CSS Fonts 4 §2.2.1 映射表 + let cases: [(f32, &str, f32); 6] = [ + (50.0, "bolder", 400.0), + (200.0, "bolder", 400.0), + (400.0, "bolder", 700.0), + (600.0, "bolder", 900.0), + (950.0, "bolder", 950.0), + (950.0, "lighter", 700.0), + ]; + for (parent_weight, keyword, expected) in cases { + let document = build_document(&format!( + "<div style=\"font-weight: {parent_weight}\"><p style=\"font-weight: {keyword}\">x</p></div>" + )); + let parsed = Stylesheet::parse(""); + let div_style = cascade( + &document, + find_first_by_name(&document, "div").unwrap(), + &[&parsed], + None, + None, + ); + assert_eq!(div_style.font_weight, parent_weight); + let p_style = cascade( + &document, + find_first_by_name(&document, "p").unwrap(), + &[&parsed], + None, + Some(&div_style), + ); + assert_eq!( + p_style.font_weight, expected, + "{keyword} from {parent_weight}" + ); + } + } + + #[test] + fn css_wide_keywords() { + // inherit:无父元素 → initial + let style = style_of("<p style=\"color: inherit\">x</p>", &[], "p"); + assert_eq!(style.color, Rgba::opaque(0, 0, 0)); + + // unset:继承属性取父值 + let document = + build_document("<div style=\"color: red\"><p style=\"color: unset\">x</p></div>"); + let parsed = Stylesheet::parse(""); + let div_style = cascade( + &document, + find_first_by_name(&document, "div").unwrap(), + &[&parsed], + None, + None, + ); + let p_style = cascade( + &document, + find_first_by_name(&document, "p").unwrap(), + &[&parsed], + None, + Some(&div_style), + ); + assert_eq!(p_style.color, Rgba::opaque(255, 0, 0)); + + // unset:非继承属性取 initial + let style = style_of( + "<p style=\"background-color: unset\" class=\"x\">x</p>", + &["p.x { background-color: red }"], + "p", + ); + assert_eq!(style.background_color, Rgba::transparent()); + + // initial:显式回到 initial + let style = style_of( + "<p style=\"color: initial\">x</p>", + &["p { color: red }"], + "p", + ); + assert_eq!(style.color, Rgba::opaque(0, 0, 0)); + + // revert:回退到 UA origin(本层无 UA 声明 → initial) + let style = style_of( + "<p style=\"color: revert\">x</p>", + &["p { color: red }"], + "p", + ); + assert_eq!(style.color, Rgba::opaque(0, 0, 0)); + } + + #[test] + fn document_styles_walk_parents_first() { + let document = + build_document("<body><div style=\"color: red\"><p><em>x</em></p></div></body>"); + let sheet = Stylesheet::parse("em { font-style: italic }"); + let styles = compute_document_styles(&document, &[&sheet], None); + + let div = find_first_by_name(&document, "div").expect("div"); + let p = find_first_by_name(&document, "p").expect("p"); + let em = find_first_by_name(&document, "em").expect("em"); + + assert_eq!(styles[&div].color, Rgba::opaque(255, 0, 0)); + assert_eq!(styles[&p].color, Rgba::opaque(255, 0, 0), "p 继承 div"); + assert_eq!(styles[&em].color, Rgba::opaque(255, 0, 0), "em 继承 p"); + assert_eq!( + styles[&em].font_style, + FontStyleValue::Italic, + "样式表命中 em" + ); + // body 自身也在结果里 + let body = find_first_by_name(&document, "body").expect("body"); + assert_eq!(styles[&body].font_style, FontStyleValue::Normal); + } + + #[test] + fn multiple_stylesheets_cascade_in_order() { + let document = build_document("<p>x</p>"); + let first = Stylesheet::parse("p { color: red }"); + let second = Stylesheet::parse("p { color: blue }"); + let style = cascade( + &document, + find_first_by_name(&document, "p").unwrap(), + &[&first, &second], + None, + None, + ); + assert_eq!(style.color, Rgba::opaque(0, 0, 255), "后传入的样式表胜出"); + } + + #[test] + fn where_has_zero_specificity_is_takes_argument_max() { + // Selectors 4::where() 特异度为 0;:is() 取参数中的最大特异度 + let document = build_document("<p id=\"a\" class=\"x\">x</p>"); + let sheet = Stylesheet::parse( + "p { color: red } :where(p.x) { color: blue } :is(#a) { color: green }", + ); + let style = cascade( + &document, + find_first_by_name(&document, "p").unwrap(), + &[&sheet], + None, + None, + ); + // :is(#a) 特异度 (1,0,0) 压过其余两条 + assert_eq!(style.color, Rgba::opaque(0, 128, 0)); + + let sheet = Stylesheet::parse("p { color: red } :where(p.x) { color: blue }"); + let style = cascade( + &document, + find_first_by_name(&document, "p").unwrap(), + &[&sheet], + None, + None, + ); + // :where(p.x) 特异度为 0,p (0,0,1) 按源顺序在后仍胜出 + assert_eq!(style.color, Rgba::opaque(255, 0, 0)); + } + + #[test] + fn ua_origin_ordering_matches_cascade_5() { + let ua_block = Stylesheet::parse("div { display: block }"); + let ua_important_none = Stylesheet::parse("div { display: none !important }"); + let div = || build_document("<div>x</div>"); + + // UA normal < author normal + let document = div(); + let author = Stylesheet::parse("div { display: inline }"); + let style = cascade( + &document, + find_first_by_name(&document, "div").unwrap(), + &[], + Some(&ua_block), + None, + ); + assert_eq!( + style.display, + DisplayValue::Block, + "无 author 声明时 UA 生效" + ); + let style = cascade( + &document, + find_first_by_name(&document, "div").unwrap(), + &[&author], + Some(&ua_block), + None, + ); + assert_eq!( + style.display, + DisplayValue::Inline, + "author normal 压过 UA normal" + ); + + // author normal < author important < UA important + let document = div(); + let author_normal = Stylesheet::parse("div { display: block }"); + let style = cascade( + &document, + find_first_by_name(&document, "div").unwrap(), + &[&author_normal], + Some(&ua_important_none), + None, + ); + assert_eq!( + style.display, + DisplayValue::None, + "UA !important 压过 author normal" + ); + + let document = div(); + let author_important = Stylesheet::parse("div { display: block !important }"); + let style = cascade( + &document, + find_first_by_name(&document, "div").unwrap(), + &[&author_important], + Some(&ua_important_none), + None, + ); + assert_eq!( + style.display, + DisplayValue::None, + "UA !important 压过 author !important" + ); + } + + #[test] + fn html_ua_stylesheet_provides_rendering_defaults() { + let document = + build_document("<div><p>x</p></div><head></head><ul><li>item</li></ul><b>bold</b>"); + let styles = compute_document_styles(&document, &[], Some(html_ua_stylesheet())); + let display_of = |name: &str| { + let node = find_first_by_name(&document, name).expect(name); + styles[&node].display + }; + assert_eq!(display_of("div"), DisplayValue::Block); + assert_eq!(display_of("p"), DisplayValue::Block); + assert_eq!(display_of("head"), DisplayValue::None); + assert_eq!(display_of("li"), DisplayValue::ListItem); + assert_eq!( + display_of("b"), + DisplayValue::Inline, + "未列入 UA 表的元素保持 initial" + ); + + // author normal 声明覆盖 UA 默认 margin + let sheet = Stylesheet::parse("body { margin: 0 }"); + let styles = compute_document_styles(&document, &[&sheet], Some(html_ua_stylesheet())); + let body = find_first_by_name(&document, "body").expect("body"); + assert_eq!( + styles[&body].margin, + crate::Edges::splat(MarginValue::Length(0.0)) + ); + } + + #[test] + fn border_width_folds_style_and_currentcolor_resolves() { + // style 缺省为 none → computed 宽度 0(CSS 2.1 §8.5.4) + let style = style_of("<p>x</p>", &["p { border: 4px }"], "p"); + assert_eq!(style.border_width, Edges::splat(0.0)); + assert_eq!(style.border_style, Edges::splat(BorderStyle::None)); + + // style 可见 → 宽度生效;currentcolor 按本元素 color 解析 + let style = style_of( + "<p>x</p>", + &[ + "p { border: 2px solid; color: red; border-top-color: currentcolor; border-left-color: green }", + ], + "p", + ); + assert_eq!(style.border_width, Edges::splat(2.0)); + assert_eq!(style.border_style.top, BorderStyle::Solid); + assert_eq!( + style.border_color.top, + Rgba::opaque(255, 0, 0), + "currentcolor" + ); + assert_eq!(style.border_color.left, Rgba::opaque(0, 128, 0)); + assert_eq!( + style.border_color.bottom, + Rgba::opaque(255, 0, 0), + "border 简写缺省 color = currentcolor" + ); + } + + #[test] + fn line_height_computes_percent_and_em_to_absolute() { + let style = style_of( + "<p>x</p>", + &["p { font-size: 20px; line-height: 150% }"], + "p", + ); + assert_eq!(style.line_height, LineHeightValue::Length(30.0)); + + let style = style_of( + "<p>x</p>", + &["p { font-size: 20px; line-height: 1.2em }"], + "p", + ); + assert_eq!(style.line_height, LineHeightValue::Length(24.0)); + + // 数值保持数值:无单位数值按数值继承 + let document = build_document( + "<div style=\"font-size: 10px; line-height: 2\"><p style=\"font-size: 20px\">x</p></div>", + ); + let parsed = Stylesheet::parse(""); + let div = find_first_by_name(&document, "div").expect("div"); + let div_style = cascade(&document, div, &[&parsed], None, None); + let p = find_first_by_name(&document, "p").expect("p"); + let p_style = cascade(&document, p, &[&parsed], None, Some(&div_style)); + assert_eq!(div_style.line_height, LineHeightValue::Number(2.0)); + assert_eq!( + p_style.line_height, + LineHeightValue::Number(2.0), + "数值 line-height 以数值继承,不随父字号折算" + ); + } + + #[test] + fn box_model_properties_reach_computed_style() { + let style = style_of( + "<p style=\"margin: 10px 20%; padding: 5px; width: 300px; height: 50%\">x</p>", + &[], + "p", + ); + assert_eq!( + style.margin, + Edges { + top: MarginValue::Length(10.0), + right: MarginValue::Percent(0.2), + bottom: MarginValue::Length(10.0), + left: MarginValue::Percent(0.2), + } + ); + assert_eq!(style.padding, Edges::splat(PaddingValue::Length(5.0))); + assert_eq!(style.width, SizeValue::Length(300.0)); + assert_eq!(style.height, SizeValue::Percent(0.5)); + } + + #[test] + fn layout_properties_reach_computed_style() { + let style = style_of( + "<div style=\"position: absolute; top: 10px; right: 20%; bottom: auto; left: 5px;\ + flex-direction: column; flex-wrap: wrap; flex-shrink: 2;\ + align-items: center; justify-content: space-between; align-self: flex-end;\ + row-gap: 8px; column-gap: 4px; grid-auto-flow: row dense;\ + grid-template-columns: 100px 1fr; grid-template-rows: auto\">x</div>", + &[], + "div", + ); + assert_eq!(style.position, PositionValue::Absolute); + assert_eq!( + style.inset, + Edges { + top: InsetValue::Length(10.0), + right: InsetValue::Percent(0.2), + bottom: InsetValue::Auto, + left: InsetValue::Length(5.0), + } + ); + assert_eq!(style.flex_direction, FlexDirectionValue::Column); + assert_eq!(style.flex_wrap, FlexWrapValue::Wrap); + assert_eq!(style.flex_shrink, 2.0); + assert_eq!(style.align_items, AlignItemsValue::Center); + assert_eq!(style.justify_content, JustifyContentValue::SpaceBetween); + assert_eq!(style.align_self, AlignSelfValue::FlexEnd); + assert_eq!(style.row_gap, GapValue::Length(8.0)); + assert_eq!(style.column_gap, GapValue::Length(4.0)); + assert_eq!(style.grid_auto_flow, GridAutoFlowValue::RowDense); + assert_eq!( + style.grid_template_columns, + GridTrackList { + tracks: vec![GridTrack::Length(100.0), GridTrack::Fr(1.0)] + } + ); + assert_eq!( + style.grid_template_rows, + GridTrackList { + tracks: vec![GridTrack::Auto] + } + ); + } + + /// `white-space` / `overflow-wrap` / `word-break` 均继承,initial 为 `normal`。 + #[test] + fn text_breaking_properties_inherit() { + let document = build_document( + "<div style=\"white-space: nowrap; overflow-wrap: break-word; word-break: break-all\">\ + <p>x</p></div><span>y</span>", + ); + let parsed = Stylesheet::parse(""); + let div_style = cascade( + &document, + find_first_by_name(&document, "div").unwrap(), + &[&parsed], + None, + None, + ); + assert_eq!(div_style.white_space, WhiteSpaceValue::Nowrap); + assert_eq!(div_style.overflow_wrap, OverflowWrapValue::BreakWord); + assert_eq!(div_style.word_break, WordBreakValue::BreakAll); + + let p_style = cascade( + &document, + find_first_by_name(&document, "p").unwrap(), + &[&parsed], + None, + Some(&div_style), + ); + assert_eq!( + p_style.white_space, + WhiteSpaceValue::Nowrap, + "子继承 nowrap" + ); + assert_eq!(p_style.overflow_wrap, OverflowWrapValue::BreakWord); + assert_eq!(p_style.word_break, WordBreakValue::BreakAll); + + // 无声明:initial 为 normal + let style = style_of("<span>y</span>", &[], "span"); + assert_eq!(style.white_space, WhiteSpaceValue::Normal); + assert_eq!(style.overflow_wrap, OverflowWrapValue::Normal); + assert_eq!(style.word_break, WordBreakValue::Normal); + } + + /// UA 表给 `<pre>` 系元素 `white-space: pre`,author 声明可覆盖。 + #[test] + fn ua_stylesheet_sets_white_space_pre() { + let document = build_document("<pre>a\nb</pre><div>c</div>"); + let styles = compute_document_styles(&document, &[], Some(html_ua_stylesheet())); + let pre = find_first_by_name(&document, "pre").expect("pre"); + assert_eq!(styles[&pre].white_space, WhiteSpaceValue::Pre); + let div = find_first_by_name(&document, "div").expect("div"); + assert_eq!(styles[&div].white_space, WhiteSpaceValue::Normal); + + // author 普通声明压过 UA + let sheet = Stylesheet::parse("pre { white-space: pre-wrap }"); + let styles = compute_document_styles(&document, &[&sheet], Some(html_ua_stylesheet())); + assert_eq!(styles[&pre].white_space, WhiteSpaceValue::PreWrap); + } + + /// CSS Text 3 四属性:initial、em 按自身字号折算、percentage 保留原值、 + /// 继承(四属性均 inherited)。 + #[test] + fn css_text_spacing_properties_compute_and_inherit() { + // initial 值:letter-spacing 0(normal 折算)、word-spacing normal、 + // text-indent 0、tab-size 整数 8(CSS Text 3 §5 initial) + let style = style_of("<span>x</span>", &[], "span"); + assert_eq!(style.letter_spacing, 0.0); + assert_eq!(style.word_spacing, SpacingValue::Normal); + assert_eq!(style.text_indent, TextIndentValue::Length(0.0)); + assert_eq!(style.tab_size, TabSizeValue::Integer(8)); + + // em 按本元素 font-size 折算(先于自身求值的 FontSize,PROPERTY_ORDER) + let style = style_of( + "<div style=\"font-size: 20px; letter-spacing: 0.5em; word-spacing: 2em;\ + text-indent: 1.5em; tab-size: 2em\">x</div>", + &[], + "div", + ); + assert_eq!(style.letter_spacing, 10.0); + assert_eq!(style.word_spacing, SpacingValue::Length(40.0)); + assert_eq!(style.text_indent, TextIndentValue::Length(30.0)); + assert_eq!(style.tab_size, TabSizeValue::Length(40.0)); + + // percentage 保留原值(text-indent 由 layout 按包含块宽度解析) + let style = style_of("<div style=\"text-indent: 10%\">x</div>", &[], "div"); + assert_eq!(style.text_indent, TextIndentValue::Percent(0.1)); + + // 负 letter-spacing 合法 + let style = style_of("<div style=\"letter-spacing: -2px\">x</div>", &[], "div"); + assert_eq!(style.letter_spacing, -2.0); + + // 四属性均继承:子元素无声明时取父值 + let document = build_document( + "<div style=\"letter-spacing: 4px; word-spacing: 8px; text-indent: 40px; tab-size: 4\">\ + <p>x</p></div>", + ); + let parsed = Stylesheet::parse(""); + let div_style = cascade( + &document, + find_first_by_name(&document, "div").unwrap(), + &[&parsed], + None, + None, + ); + let p_style = cascade( + &document, + find_first_by_name(&document, "p").unwrap(), + &[&parsed], + None, + Some(&div_style), + ); + assert_eq!(p_style.letter_spacing, 4.0); + assert_eq!(p_style.word_spacing, SpacingValue::Length(8.0)); + assert_eq!(p_style.text_indent, TextIndentValue::Length(40.0)); + assert_eq!(p_style.tab_size, TabSizeValue::Integer(4)); + } + + /// 全量扫描的参照实现(桶化前的语义):每元素测试全部规则与选择器。 + /// 桶索引(M5 ④)的正确性判据:两条路径产出的 computed style 逐元素 + /// 一致——跳过的选择器只可能是「必要条件已失败、本就不可能匹配」的。 + fn cascade_unbucketed_in( + document: &Document, + element: NodeId, + stylesheets: &[&Stylesheet], + ua_sheet: Option<&Stylesheet>, + parent: Option<&ComputedStyle>, + viewport: Option<MediaViewport>, + ) -> ComputedStyle { + let mut matched: Vec<(CascadeKey, &Declaration)> = Vec::new(); + if let Some(ua) = ua_sheet { + for (rule_order, rule) in ua.rules().iter().enumerate() { + let specificity = rule + .selectors() + .iter() + .filter(|parsed| { + match_element_selectors(std::slice::from_ref(parsed), document, element) + }) + .map(|parsed| parsed.specificity) + .max(); + if let Some(specificity) = specificity { + for (declaration_order, declaration) in rule.declarations().iter().enumerate() { + matched.push(( + CascadeKey { + bucket: bucket_of(Origin::Ua, declaration.important), + inline: false, + specificity, + rule_order, + declaration_order, + }, + declaration, + )); + } + } + } + } + for (rule_order, rule) in stylesheets + .iter() + .flat_map(|sheet| sheet.rules()) + .enumerate() + { + let specificity = rule + .selectors() + .iter() + .filter(|parsed| { + match_element_selectors(std::slice::from_ref(parsed), document, element) + }) + .map(|parsed| parsed.specificity) + .max(); + if let Some(specificity) = specificity { + for (declaration_order, declaration) in rule.declarations().iter().enumerate() { + matched.push(( + CascadeKey { + bucket: bucket_of(Origin::Author, declaration.important), + inline: false, + specificity, + rule_order, + declaration_order, + }, + declaration, + )); + } + } + } + let style_attribute = document.node(element).and_then(|node| match node { + NodeKind::Element(data) => data + .attributes + .iter() + .find(|attr| attr.namespace == nexty_dom::Namespace::None && attr.name == "style") + .map(|attr| attr.value.clone()), + _ => None, + }); + // 内联声明提升到函数作用域:matched 按引用持有直到 resolve_all + let inline_declarations = style_attribute.map(|attr| parse_inline_style(&attr)); + if let Some(inline_declarations) = &inline_declarations { + for (declaration_order, declaration) in inline_declarations.iter().enumerate() { + matched.push(( + CascadeKey { + bucket: bucket_of(Origin::Author, declaration.important), + inline: true, + specificity: 0, + rule_order: usize::MAX, + declaration_order, + }, + declaration, + )); + } + } + resolve_all(&matched, parent, viewport) + } + + /// 全量扫描的整文档版本(参照路径)。 + fn walk_unbucketed( + document: &Document, + node: NodeId, + parent: Option<&ComputedStyle>, + stylesheets: &[&Stylesheet], + ua_sheet: Option<&Stylesheet>, + viewport: Option<MediaViewport>, + out: &mut HashMap<NodeId, ComputedStyle>, + ) { + for child in document.children(node) { + if matches!(document.node(child), Some(NodeKind::Element(_))) { + let style = + cascade_unbucketed_in(document, child, stylesheets, ua_sheet, parent, viewport); + walk_unbucketed( + document, + child, + Some(&style), + stylesheets, + ua_sheet, + viewport, + out, + ); + out.insert(child, style); + } + } + } + + /// 桶化前后逐元素一致:覆盖类/标签/id/组合器/:is/属性选择器/通配/ + /// 多选择器规则/大小写/内联样式/important 的语料,逐页对比两条路径 + /// 的整文档 computed style。 + #[test] + fn bucketed_cascade_matches_full_scan() { + const CASES: &[(&str, &str)] = &[ + // 类桶:单类、多类元素命中其一、类不存在 + ( + "<div class=a>x</div><p class=\"a b\">y</p><span>z</span>", + ".a { color: rgb(1 2 3) } .b { color: rgb(4 5 6) } .c { color: red }", + ), + // 标签桶 + 类优先于标签的选择器 + ( + "<p class=lead>text</p><div>other</div>", + "p { margin: 2px } .lead { margin: 9px } div { padding: 1px }", + ), + // id 桶:命中与未命中 + ( + "<div id=main>x</div><div id=other>y</div>", + "#main { color: blue } #missing { color: red }", + ), + // 组合器(Always 桶):后代 / 子代 / 兄弟 + ( + "<div><p>deep</p></div><div><section><p>nested</p></section></div><h1>a</h1><p>b</p>", + "div p { color: green } div > p { margin: 1px } h1 + p { color: red }", + ), + // :is() / :where():内部是备选分支,不得作为必要条件 + ( + "<em class=a>x</em><strong id=special>y</strong><b>z</b>", + ":is(.a, #special) { color: purple } b:is(.a, .b) { color: red } :where(p, div) { margin: 2px }", + ), + // 属性选择器与通配(无可提取必要条件) + ( + "<a href=x>link</a><code>c</code>", + "[href] { color: blue } * { line-height: 1.4 }", + ), + // 一条规则多个选择器:各自分桶,命中其一即整规则生效 + ( + "<i class=x>i</i><div>d</div><u>u</u>", + ".x, div, #nope { color: teal }", + ), + // 大小写:HTML 标签大小写不敏感,类名敏感——两条路径必须一致 + ( + "<DIV CLASS=keep>case</DIV><span CLASS=Keep>x</span>", + "div { color: brown } .Keep { color: pink } .keep { color: olive }", + ), + // 内联样式 + important 交错 + ( + "<p style=\"color: red\">inline</p><b style=\"color: red\">b</b>", + "p { color: green !important } b { color: green }", + ), + // 无样式表 / 空规则:退化路径 + ("<div>x</div>", ""), + // 特异度混合:tag < class < id,important 反超 + ( + "<div id=t class=c>x</div>", + "div { color: black } .c { color: gray } #t { color: white } div { color: red !important }", + ), + ]; + let ua_sheet = crate::ua::html_ua_stylesheet(); + for (index, (html, css)) in CASES.iter().enumerate() { + let document = build_document(html); + let sheet = Stylesheet::parse(css); + let bucketed = compute_document_styles(&document, &[&sheet], Some(ua_sheet)); + let mut full = HashMap::new(); + walk_unbucketed( + &document, + document.root(), + None, + &[&sheet], + Some(ua_sheet), + None, + &mut full, + ); + assert_eq!(bucketed.len(), full.len(), "case {index}: 元素数一致"); + for (node, style) in &bucketed { + assert_eq!( + style, &full[node], + "case {index}: node {node:?} 桶化与全量扫描不一致" + ); + } + } + } + + /// 内联样式缓存(M5 ②):原文未变复用解析结果(同元素两次级联第 + /// 二次命中),原文变化自动失效重解析。 + #[test] + fn inline_style_cache_reuses_and_invalidates() { + let mut cache = InlineStyleCache::new(); + let document = build_document("<p style=\"color: red\">x</p>"); + let p = find_first_by_name(&document, "p").unwrap(); + let first = cache.declarations_of(&document, p).expect("style attr"); + assert_eq!(first.len(), 1); + // 复用:同一元素再次请求命中(声明存储位置相同) + let first_ptr = first.as_ptr(); + let second_ptr = cache + .declarations_of(&document, p) + .expect("style attr") + .as_ptr(); + assert!(std::ptr::eq(first_ptr, second_ptr), "原文未变应复用"); + } +} diff --git a/crates/nexty-css/.mimosa/hook-state/sess_593b0e04-d177-44d2-b3cc-247d233520f7.mvw2dq8j-91568-cc032940c8.baseline/be1c878c753064b7eaddf4a10ba4215a93dd1817d31e6788691cdb29752fd612.source b/crates/nexty-css/.mimosa/hook-state/sess_593b0e04-d177-44d2-b3cc-247d233520f7.mvw2dq8j-91568-cc032940c8.baseline/be1c878c753064b7eaddf4a10ba4215a93dd1817d31e6788691cdb29752fd612.source new file mode 100644 index 0000000..0cff10f --- /dev/null +++ b/crates/nexty-css/.mimosa/hook-state/sess_593b0e04-d177-44d2-b3cc-247d233520f7.mvw2dq8j-91568-cc032940c8.baseline/be1c878c753064b7eaddf4a10ba4215a93dd1817d31e6788691cdb29752fd612.source @@ -0,0 +1,3534 @@ +//! 属性值模型与逐属性解析。 +//! +//! 行为 ground truth: +//! - CSS-wide 关键字:[CSS Cascading and Inheritance Level 5 §6](https://drafts.csswg.org/css-cascade-5/#defaulting-keywords) +//! - 颜色:[CSS Color Module Level 4](https://drafts.csswg.org/css-color-4/)(hex / rgb() / hsl() / 命名色) +//! - 字号:[CSS Fonts Module Level 4 §2.5](https://drafts.csswg.org/css-fonts-4/#font-size-prop) +//! - 字重:[CSS Fonts Module Level 4 §2.2](https://drafts.csswg.org/css-fonts-4/#font-weight-numeric) +//! - 字体族:[CSS Fonts Module Level 4 §2.3](https://drafts.csswg.org/css-fonts-4/#font-family-prop) +//! - font 简写:[CSS Fonts Module Level 4 §3.3](https://drafts.csswg.org/css-fonts-4/#font-prop) +//! - display:[CSS Display Module Level 3](https://drafts.csswg.org/css-display-3/#the-display-properties) +//! - text-align:[CSS Text Module Level 4](https://drafts.csswg.org/css-text-4/#text-align-property) +//! +//! 已知偏差(按需再补,见本轮 goal.md 非目标):`rem` / `ex` / `ch` 等 +//! 相对单位、`currentcolor`、`color-mix()` 等函数色、`display` 的多关键字 +//! 语法与 ruby 内部盒、`var()` 均视为无效声明(浏览器会接受其中的合法值)。 +//! 视口单位(`vw`/`vh`/`vmin`/`vmax`)只在盒级长度属性(width/height/min/max、 +//! inset、margin、padding、gap)上接受;`font-size` / `border-width` / +//! `line-height` 上的视口单位视为无效声明。 +//! `font` 简写里无对应 longhand 的成分——`<font-variant-css2>`(`small-caps`) +//! 与 `<font-width-css3>`(宽度关键字/百分比)——按语法接受后丢弃(无渲染 +//! 效果但声明不整体失效);系统字体关键字(`caption` / `menu` 等)整条无效。 +//! +//! **Feature**:本模块受 `values` feature 控制(由 lib.rs 装配)。其中的 +//! `parse_*` 逐属性解析函数供 `parser` / `cascade` 模块消费,故当上层 feature +//! 关闭时这些内部函数没有调用方——此时按模块整体抑制 dead_code。 + +#![cfg_attr(not(feature = "stylesheets"), allow(dead_code))] + +use cssparser::{ParseError, Parser, Token, parse_important}; + +/// 非预乘 sRGB 颜色。 +/// +/// 对应 CSS Color 4 的 [`<color>`](https://drafts.csswg.org/css-color-4/#color-syntax) +/// 解析结果;alpha 与各通道均量化到 8bit。 +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +pub struct Rgba { + /// 红通道。 + pub r: u8, + /// 绿通道。 + pub g: u8, + /// 蓝通道。 + pub b: u8, + /// alpha 通道。 + pub a: u8, +} + +impl Rgba { + /// 不透明颜色。 + #[must_use] + pub const fn opaque(r: u8, g: u8, b: u8) -> Self { + Self { r, g, b, a: 0xff } + } + + /// 全透明黑,即 CSS 关键字 `transparent` + /// ([CSS Color 4 §5.5](https://drafts.csswg.org/css-color-4/#transparent-color))。 + #[must_use] + pub const fn transparent() -> Self { + Self { + r: 0, + g: 0, + b: 0, + a: 0, + } + } +} + +/// 级联引擎认识的最小属性集合。 +/// +/// 只覆盖当前管线需要的属性;新属性随消费方(layout / text / paint)落地时加入, +/// 不预先铺满。属性元数据(inherited / initial)见 `cascade` 模块。 +#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)] +pub enum PropertyId { + /// `display`。 + Display, + /// `color`。 + Color, + /// `background-color`。 + BackgroundColor, + /// `font-size`。 + FontSize, + /// `font-weight`。 + FontWeight, + /// `font-style`。 + FontStyle, + /// `font-family`。 + FontFamily, + /// `text-align`。 + TextAlign, + /// `line-height`。 + LineHeight, + /// `white-space`。 + WhiteSpace, + /// `overflow-wrap`。 + OverflowWrap, + /// `word-break`。 + WordBreak, + /// `letter-spacing`。 + LetterSpacing, + /// `word-spacing`。 + WordSpacing, + /// `text-indent`。 + TextIndent, + /// `tab-size`。 + TabSize, + /// `width`。 + Width, + /// `height`。 + Height, + /// `min-width`。 + MinWidth, + /// `max-width`。 + MaxWidth, + /// `min-height`。 + MinHeight, + /// `max-height`。 + MaxHeight, + /// `box-sizing`。 + BoxSizing, + /// `overflow`。 + Overflow, + /// `flex-grow`。 + FlexGrow, + /// `flex-basis`。 + FlexBasis, + /// `position`。 + Position, + /// `float`。 + Float, + /// `clear`。 + Clear, + /// `top`。 + Top, + /// `right`。 + Right, + /// `bottom`。 + Bottom, + /// `left`。 + Left, + /// `flex-direction`。 + FlexDirection, + /// `flex-wrap`。 + FlexWrap, + /// `flex-shrink`。 + FlexShrink, + /// `align-items`。 + AlignItems, + /// `justify-content`。 + JustifyContent, + /// `align-self`。 + AlignSelf, + /// `grid-template-columns`。 + GridTemplateColumns, + /// `grid-template-rows`。 + GridTemplateRows, + /// `row-gap`。 + RowGap, + /// `column-gap`。 + ColumnGap, + /// `grid-auto-flow`。 + GridAutoFlow, + /// `margin-top`。 + MarginTop, + /// `margin-right`。 + MarginRight, + /// `margin-bottom`。 + MarginBottom, + /// `margin-left`。 + MarginLeft, + /// `padding-top`。 + PaddingTop, + /// `padding-right`。 + PaddingRight, + /// `padding-bottom`。 + PaddingBottom, + /// `padding-left`。 + PaddingLeft, + /// `border-top-style`。 + BorderTopStyle, + /// `border-right-style`。 + BorderRightStyle, + /// `border-bottom-style`。 + BorderBottomStyle, + /// `border-left-style`。 + BorderLeftStyle, + /// `border-top-width`。 + BorderTopWidth, + /// `border-right-width`。 + BorderRightWidth, + /// `border-bottom-width`。 + BorderBottomWidth, + /// `border-left-width`。 + BorderLeftWidth, + /// `border-top-color`。 + BorderTopColor, + /// `border-right-color`。 + BorderRightColor, + /// `border-bottom-color`。 + BorderBottomColor, + /// `border-left-color`。 + BorderLeftColor, +} + +impl PropertyId { + /// 属性的规范名(小写)。 + #[must_use] + pub fn as_str(self) -> &'static str { + match self { + PropertyId::Display => "display", + PropertyId::Color => "color", + PropertyId::BackgroundColor => "background-color", + PropertyId::FontSize => "font-size", + PropertyId::FontWeight => "font-weight", + PropertyId::FontStyle => "font-style", + PropertyId::FontFamily => "font-family", + PropertyId::TextAlign => "text-align", + PropertyId::LineHeight => "line-height", + PropertyId::WhiteSpace => "white-space", + PropertyId::OverflowWrap => "overflow-wrap", + PropertyId::WordBreak => "word-break", + PropertyId::LetterSpacing => "letter-spacing", + PropertyId::WordSpacing => "word-spacing", + PropertyId::TextIndent => "text-indent", + PropertyId::TabSize => "tab-size", + PropertyId::Width => "width", + PropertyId::Height => "height", + PropertyId::MinWidth => "min-width", + PropertyId::MaxWidth => "max-width", + PropertyId::MinHeight => "min-height", + PropertyId::MaxHeight => "max-height", + PropertyId::BoxSizing => "box-sizing", + PropertyId::Overflow => "overflow", + PropertyId::FlexGrow => "flex-grow", + PropertyId::FlexBasis => "flex-basis", + PropertyId::Position => "position", + PropertyId::Float => "float", + PropertyId::Clear => "clear", + PropertyId::Top => "top", + PropertyId::Right => "right", + PropertyId::Bottom => "bottom", + PropertyId::Left => "left", + PropertyId::FlexDirection => "flex-direction", + PropertyId::FlexWrap => "flex-wrap", + PropertyId::FlexShrink => "flex-shrink", + PropertyId::AlignItems => "align-items", + PropertyId::JustifyContent => "justify-content", + PropertyId::AlignSelf => "align-self", + PropertyId::GridTemplateColumns => "grid-template-columns", + PropertyId::GridTemplateRows => "grid-template-rows", + PropertyId::RowGap => "row-gap", + PropertyId::ColumnGap => "column-gap", + PropertyId::GridAutoFlow => "grid-auto-flow", + PropertyId::MarginTop => "margin-top", + PropertyId::MarginRight => "margin-right", + PropertyId::MarginBottom => "margin-bottom", + PropertyId::MarginLeft => "margin-left", + PropertyId::PaddingTop => "padding-top", + PropertyId::PaddingRight => "padding-right", + PropertyId::PaddingBottom => "padding-bottom", + PropertyId::PaddingLeft => "padding-left", + PropertyId::BorderTopStyle => "border-top-style", + PropertyId::BorderRightStyle => "border-right-style", + PropertyId::BorderBottomStyle => "border-bottom-style", + PropertyId::BorderLeftStyle => "border-left-style", + PropertyId::BorderTopWidth => "border-top-width", + PropertyId::BorderRightWidth => "border-right-width", + PropertyId::BorderBottomWidth => "border-bottom-width", + PropertyId::BorderLeftWidth => "border-left-width", + PropertyId::BorderTopColor => "border-top-color", + PropertyId::BorderRightColor => "border-right-color", + PropertyId::BorderBottomColor => "border-bottom-color", + PropertyId::BorderLeftColor => "border-left-color", + } + } + + /// 按属性名查 [`PropertyId`],ASCII case-insensitive + /// (CSS Syntax:声明名匹配大小写不敏感)。 + #[must_use] + pub fn from_name(name: &str) -> Option<Self> { + const ALL: [PropertyId; 64] = [ + PropertyId::Display, + PropertyId::Color, + PropertyId::BackgroundColor, + PropertyId::FontSize, + PropertyId::FontWeight, + PropertyId::FontStyle, + PropertyId::FontFamily, + PropertyId::TextAlign, + PropertyId::LineHeight, + PropertyId::WhiteSpace, + PropertyId::OverflowWrap, + PropertyId::WordBreak, + PropertyId::LetterSpacing, + PropertyId::WordSpacing, + PropertyId::TextIndent, + PropertyId::TabSize, + PropertyId::Width, + PropertyId::Height, + PropertyId::MinWidth, + PropertyId::MaxWidth, + PropertyId::MinHeight, + PropertyId::MaxHeight, + PropertyId::BoxSizing, + PropertyId::Overflow, + PropertyId::FlexGrow, + PropertyId::FlexBasis, + PropertyId::Position, + PropertyId::Float, + PropertyId::Clear, + PropertyId::Top, + PropertyId::Right, + PropertyId::Bottom, + PropertyId::Left, + PropertyId::FlexDirection, + PropertyId::FlexWrap, + PropertyId::FlexShrink, + PropertyId::AlignItems, + PropertyId::JustifyContent, + PropertyId::AlignSelf, + PropertyId::GridTemplateColumns, + PropertyId::GridTemplateRows, + PropertyId::RowGap, + PropertyId::ColumnGap, + PropertyId::GridAutoFlow, + PropertyId::MarginTop, + PropertyId::MarginRight, + PropertyId::MarginBottom, + PropertyId::MarginLeft, + PropertyId::PaddingTop, + PropertyId::PaddingRight, + PropertyId::PaddingBottom, + PropertyId::PaddingLeft, + PropertyId::BorderTopStyle, + PropertyId::BorderRightStyle, + PropertyId::BorderBottomStyle, + PropertyId::BorderLeftStyle, + PropertyId::BorderTopWidth, + PropertyId::BorderRightWidth, + PropertyId::BorderBottomWidth, + PropertyId::BorderLeftWidth, + PropertyId::BorderTopColor, + PropertyId::BorderRightColor, + PropertyId::BorderBottomColor, + PropertyId::BorderLeftColor, + ]; + ALL.into_iter() + .find(|id| id.as_str().eq_ignore_ascii_case(name)) + } +} + +/// CSS-wide 关键字 +/// ([CSS Cascade 5 §6.1](https://drafts.csswg.org/css-cascade-5/#defaulting-keywords))。 +/// +/// 对任何属性都合法,求值语义由 cascade 模块实现。 +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +pub enum CssWideKeyword { + /// `initial`。 + Initial, + /// `inherit`。 + Inherit, + /// `unset`。 + Unset, + /// `revert`。 + Revert, +} + +/// 一条声明按属性解析后的值。 +#[derive(Debug, Clone, PartialEq)] +pub enum DeclaredValue { + /// CSS-wide 关键字(对任意属性合法)。 + CssWide(CssWideKeyword), + /// 按属性语法解析出的值。 + Typed(PropertyValue), +} + +/// 各属性解析后的值。 +/// +/// 每个变体对应 [`PropertyId`] 中一个属性的可接受语法;不在集合内的值按 +/// 无效声明处理(整体丢弃,声明级恢复,见 CSS Syntax §5.5)。 +#[derive(Debug, Clone, PartialEq)] +pub enum PropertyValue { + /// `display` 关键字。 + Display(DisplayValue), + /// `text-align` 关键字。 + TextAlign(TextAlignValue), + /// `font-style` 关键字。 + FontStyle(FontStyleValue), + /// 颜色值。 + Color(Rgba), + /// `font-size` 值。 + FontSize(FontSizeValue), + /// `font-weight` 值。 + FontWeight(FontWeightValue), + /// `font-family` 字体族列表。 + FontFamily(Vec<FontFamilyValue>), + /// `line-height` 值。 + LineHeight(LineHeightValue), + /// `white-space` 关键字。 + WhiteSpace(WhiteSpaceValue), + /// `overflow-wrap` 关键字。 + OverflowWrap(OverflowWrapValue), + /// `word-break` 关键字。 + WordBreak(WordBreakValue), + /// `letter-spacing` 值。 + LetterSpacing(SpacingValue), + /// `word-spacing` 值。 + WordSpacing(SpacingValue), + /// `text-indent` 值。 + TextIndent(TextIndentValue), + /// `tab-size` 值。 + TabSize(TabSizeValue), + /// `width` / `height` 值(min-width / max-width / min-height / max-height + /// 复用同一语法)。 + Size(SizeValue), + /// `box-sizing` 关键字。 + BoxSizing(BoxSizingValue), + /// `overflow` 关键字。 + Overflow(OverflowValue), + /// `flex-grow` 数值。 + FlexGrow(f32), + /// `flex-basis` 值(auto | <length-percentage>)。 + FlexBasis(SizeValue), + /// `position` 关键字。 + Position(PositionValue), + /// `float` 关键字。 + Float(FloatValue), + /// `clear` 关键字。 + Clear(ClearValue), + /// `top` / `right` / `bottom` / `left` 值。 + Inset(InsetValue), + /// `flex-direction` 关键字。 + FlexDirection(FlexDirectionValue), + /// `flex-wrap` 关键字。 + FlexWrap(FlexWrapValue), + /// `flex-shrink` 数值。 + FlexShrink(f32), + /// `align-items` 关键字。 + AlignItems(AlignItemsValue), + /// `justify-content` 关键字。 + JustifyContent(JustifyContentValue), + /// `align-self` 关键字。 + AlignSelf(AlignSelfValue), + /// `grid-template-columns` / `grid-template-rows` 轨道列表。 + GridTrack(GridTrackList), + /// `row-gap` / `column-gap` 值。 + Gap(GapValue), + /// `grid-auto-flow` 关键字。 + GridAutoFlow(GridAutoFlowValue), + /// margin 值(四边共用)。 + Margin(MarginValue), + /// padding 值(四边共用)。 + Padding(PaddingValue), + /// border-*-width 值。 + BorderWidth(BorderWidthValue), + /// border-*-style 关键字。 + BorderStyle(BorderStyle), + /// border-*-color 值。 + BorderColor(BorderColorValue), +} + +/// `display` 的单关键字值 +/// ([CSS Display 3 §2](https://drafts.csswg.org/css-display-3/#the-display-properties))。 +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +pub enum DisplayValue { + /// `inline`(initial)。 + Inline, + /// `block`。 + Block, + /// `list-item`。 + ListItem, + /// `inline-block`。 + InlineBlock, + /// `flow-root`。 + FlowRoot, + /// `flex`。 + Flex, + /// `inline-flex`。 + InlineFlex, + /// `grid`。 + Grid, + /// `inline-grid`。 + InlineGrid, + /// `table`。 + Table, + /// `inline-table`。 + InlineTable, + /// 表格内部盒(`table-row-group` / `table-header-group` / + /// `table-footer-group` / `table-row` / `table-cell` / + /// `table-column-group` / `table-column` / `table-caption`)。 + TableInternal(&'static str), + /// `contents`。 + Contents, + /// `none`。 + None, +} + +/// `text-align` 值 +/// ([CSS Text 4](https://drafts.csswg.org/css-text-4/#text-align-property))。 +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +pub enum TextAlignValue { + /// `start`(initial)。 + Start, + /// `end`。 + End, + /// `left`。 + Left, + /// `right`。 + Right, + /// `center`。 + Center, + /// `justify`。 + Justify, + /// `match-parent`。 + MatchParent, + /// `justify-all`。 + JustifyAll, +} + +/// `white-space` 值 +/// ([CSS Text 3 §3.1](https://drafts.csswg.org/css-text-3/#white-space-property))。 +/// +/// 本层按单属性实现(CSS Text 4 的 `white-space-collapse` + `text-wrap-mode` +/// 拆分记为偏差)。语义: +/// +/// | 值 | 空白 | 软换行 | +/// | --- | --- | --- | +/// | `normal`(initial) | 折叠 | 允许 | +/// | `nowrap` | 折叠 | 禁止 | +/// | `pre` | 保留(`\n` 强断) | 禁止 | +/// | `pre-wrap` | 保留(`\n` 强断) | 允许 | +/// | `pre-line` | 折叠空格、保留 `\n`(强断) | 允许 | +/// | `break-spaces` | 保留(含行尾,`\n` 强断) | 允许(每个空格后) | +#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)] +pub enum WhiteSpaceValue { + /// `normal`(initial)。 + #[default] + Normal, + /// `nowrap`。 + Nowrap, + /// `pre`。 + Pre, + /// `pre-wrap`。 + PreWrap, + /// `pre-line`。 + PreLine, + /// `break-spaces`。 + BreakSpaces, +} + +impl WhiteSpaceValue { + /// 是否折叠可折叠空白(空格 / 制表 / 段内换行)。 + #[must_use] + pub fn collapses(self) -> bool { + matches!(self, Self::Normal | Self::Nowrap | Self::PreLine) + } + + /// 是否保留段内换行(`\n` 作为强断行)。 + #[must_use] + pub fn preserves_newlines(self) -> bool { + !matches!(self, Self::Normal | Self::Nowrap) + } + + /// 是否允许软换行(UAX#14 断点)。 + #[must_use] + pub fn wraps(self) -> bool { + !matches!(self, Self::Nowrap | Self::Pre) + } +} + +/// `overflow-wrap` 值 +/// ([CSS Text 3 §5.4](https://drafts.csswg.org/css-text-3/#overflow-wrap-property))。 +#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)] +pub enum OverflowWrapValue { + /// `normal`(initial):只在 UAX#14 允许的位置断行。 + #[default] + Normal, + /// `break-word`:溢出时可在任意字形簇之间断行;不参与 min-content。 + BreakWord, + /// `anywhere`:溢出时可断,且断点参与 min-content。 + Anywhere, +} + +/// `word-break` 值 +/// ([CSS Text 3 §5.1](https://drafts.csswg.org/css-text-3/#word-break-property))。 +#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)] +pub enum WordBreakValue { + /// `normal`(initial)。 + #[default] + Normal, + /// `break-all`:在相邻 typographic letter unit 之间允许断行 + /// (不切开字形簇)。 + BreakAll, + /// `keep-all`:禁止 CJK 等词内部断行。 + KeepAll, +} + +/// `letter-spacing` / `word-spacing` 值 +/// ([CSS Text 3 §8](https://drafts.csswg.org/css-text-3/#spacing-props))。 +/// +/// `normal` 的语义两属性不同:letter-spacing 折算为 0(无附加字距), +/// word-spacing 的 normal 保留给 layout 层判读。视口单位不接受(与 +/// `font-size` / `border-width` / `line-height` 的既有口径一致,见模块偏差)。 +#[derive(Debug, Clone, Copy, PartialEq)] +pub enum SpacingValue { + /// `normal`(initial)。 + Normal, + /// 绝对长度(CSS px;负值合法)。 + Length(f32), + /// em(computed 阶段按本元素 font-size 折算为绝对 px)。 + Em(f32), +} + +/// `text-indent` 值 +/// ([CSS Text 3 §4](https://drafts.csswg.org/css-text-3/#text-indent-property))。 +/// +/// 百分比按包含块宽度解析,保留原值给 layout;`each-line` / `hanging` +/// 关键字未实现(记为偏差)。 +#[derive(Debug, Clone, Copy, PartialEq)] +pub enum TextIndentValue { + /// 绝对长度(CSS px;负值合法)。 + Length(f32), + /// em(computed 阶段按本元素 font-size 折算为绝对 px)。 + Em(f32), + /// 百分比(小数存储;相对包含块宽度,layout 解析)。 + Percent(f32), +} + +/// `tab-size` 值 +/// ([CSS Text 3 §5](https://drafts.csswg.org/css-text-3/#tab-size-property))。 +/// +/// 整数形态表示按 U+0020 advance 的 N 倍推进,依赖字体度量,由 layout +/// 在放置期解析;长度形态的 em 在 computed 阶段按本元素 font-size 折算。 +#[derive(Debug, Clone, Copy, PartialEq)] +pub enum TabSizeValue { + /// 整数:制表位按空格 advance 的 N 倍(initial 8)。 + Integer(u32), + /// 绝对长度(CSS px)。 + Length(f32), + /// em(computed 阶段按本元素 font-size 折算为绝对 px)。 + Em(f32), +} + +/// `font-style` 值 +/// ([CSS Fonts 4 §2.1](https://drafts.csswg.org/css-fonts-4/#font-style-prop))。 +#[derive(Debug, Clone, Copy, PartialEq)] +pub enum FontStyleValue { + /// `normal`(initial)。 + Normal, + /// `italic`。 + Italic, + /// `oblique`,可选倾斜角(角度制;`oblique none` 为 `None`)。 + Oblique(Option<f32>), +} + +/// `font-size` 的绝对尺寸关键字及其缩放系数 +/// ([CSS Fonts 4 §2.5.1](https://drafts.csswg.org/css-fonts-4/#absolute-size-mapping): +/// medium 为基准 1,其余为规范给出的 scaling factor)。 +#[derive(Debug, Clone, Copy, PartialEq)] +pub enum AbsoluteSize { + /// `xx-small`(3/5)。 + XxSmall, + /// `x-small`(3/4)。 + XSmall, + /// `small`(8/9)。 + Small, + /// `medium`(1)。 + Medium, + /// `large`(6/5)。 + Large, + /// `x-large`(3/2)。 + XLarge, + /// `xx-large`(2/1)。 + XxLarge, + /// `xxx-large`(3/1)。 + XxxLarge, +} + +impl AbsoluteSize { + /// 相对 medium 的缩放系数。 + #[must_use] + pub fn factor(self) -> f32 { + match self { + AbsoluteSize::XxSmall => 3.0 / 5.0, + AbsoluteSize::XSmall => 3.0 / 4.0, + AbsoluteSize::Small => 8.0 / 9.0, + AbsoluteSize::Medium => 1.0, + AbsoluteSize::Large => 6.0 / 5.0, + AbsoluteSize::XLarge => 1.5, + AbsoluteSize::XxLarge => 2.0, + AbsoluteSize::XxxLarge => 3.0, + } + } + + /// 绝对尺寸关键字的有序表,供 `larger` / `smaller` 取相邻项。 + pub const ORDERED: [AbsoluteSize; 8] = [ + AbsoluteSize::XxSmall, + AbsoluteSize::XSmall, + AbsoluteSize::Small, + AbsoluteSize::Medium, + AbsoluteSize::Large, + AbsoluteSize::XLarge, + AbsoluteSize::XxLarge, + AbsoluteSize::XxxLarge, + ]; +} + +/// `font-size` 值 +/// ([CSS Fonts 4 §2.5](https://drafts.csswg.org/css-fonts-4/#font-size-prop))。 +#[derive(Debug, Clone, Copy, PartialEq)] +pub enum FontSizeValue { + /// 绝对长度(已折算为 CSS px)。 + Px(f32), + /// 相对父元素计算字号的 em。 + Em(f32), + /// 相对父元素计算字号的百分比,以小数存储(`120%` → `1.2`)。 + Percent(f32), + /// 绝对尺寸关键字。 + Absolute(AbsoluteSize), + /// `larger`。 + Larger, + /// `smaller`。 + Smaller, +} + +/// `font-weight` 值 +/// ([CSS Fonts 4 §2.2](https://drafts.csswg.org/css-fonts-4/#font-weight-numeric))。 +#[derive(Debug, Clone, Copy, PartialEq)] +pub enum FontWeightValue { + /// 数值字重,1–1000(`normal` = 400、`bold` = 700 已在解析期折算)。 + Weight(f32), + /// `bolder`:相对继承值。 + Bolder, + /// `lighter`:相对继承值。 + Lighter, +} + +/// 字体族列表中的一项 +/// ([CSS Fonts 4 §2.3](https://drafts.csswg.org/css-fonts-4/#font-family-prop))。 +/// +/// 带引号的 `"serif"` 是名为 serif 的普通字体族,只有不带引号的 +/// generic 关键字才映射到 [`FontFamilyValue`] 的 generic 变体。 +#[derive(Debug, Clone, PartialEq, Eq)] +pub enum FontFamilyValue { + /// generic 族(`serif` / `sans-serif` / `cursive` / `fantasy` / + /// `monospace` / `system-ui` / `ui-serif` / `ui-sans-serif` / + /// `ui-monospace` / `ui-rounded` / `math` / `emoji` / `fangsong`)。 + Generic(&'static str), + /// 具名字体族。 + Family(String), +} + +/// `line-height` 值 +/// ([CSS 2.1 §10.8.1](https://www.w3.org/TR/CSS21/visudet.html#line-height))。 +/// +/// 数值保持数值(以自身数值继承,子元素按自身 font-size 求值); +/// 百分比与 em 在 computed 阶段按元素自身 font-size 折算(cascade 模块)。 +#[derive(Debug, Clone, Copy, PartialEq)] +pub enum LineHeightValue { + /// `normal`(initial,约 1.2,具体由 UA 决定)。 + Normal, + /// 无单位数值(可为 0,不可为负)。 + Number(f32), + /// 绝对长度(已折算为 CSS px)。 + Length(f32), + /// 相对自身 font-size 的 em。 + Em(f32), + /// 百分比(以小数存储,`150%` → `1.5`;computed 阶段乘 font-size)。 + Percent(f32), +} + +/// `width` / `height` 值 +/// ([CSS 2.1 §10.2](https://www.w3.org/TR/CSS21/visudet.html#the-width-property)、 +/// [§10.5](https://www.w3.org/TR/CSS21/visudet.html#the-height-property))。 +/// +/// 百分比由 layout 相对包含块宽度解析;负值非法(声明无效)。 +#[derive(Debug, Clone, Copy, PartialEq)] +pub enum SizeValue { + /// `auto`(initial)。 + Auto, + /// 绝对长度(CSS px)。 + Length(f32), + /// 百分比(以小数存储)。 + Percent(f32), + /// 视口单位(`50vw` → `Viewport(50.0, Vw)`);cascade 在 computed 阶段 + /// 按视口尺寸折算为 [`SizeValue::Length`],无视口信息时原样保留。 + Viewport(f32, ViewportUnit), +} + +/// `box-sizing` 值 +/// ([CSS Sizing 4 §5.3](https://drafts.csswg.org/css-sizing-4/#box-sizing))。 +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +pub enum BoxSizingValue { + /// `content-box`(initial):width/height 指内容盒。 + ContentBox, + /// `border-box`:width/height 指边框盒。 + BorderBox, +} + +/// `overflow` 值 +/// ([CSS Overflow 3 §3](https://drafts.csswg.org/css-overflow-3/#overflow-control))。 +/// +/// 本层只建模 visible / hidden 的裁剪标记;`auto` / `scroll` / `clip` +/// 暂按无效声明丢弃(回退 initial `visible`,见模块偏差)。 +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +pub enum OverflowValue { + /// `visible`(initial):内容溢出可见。 + Visible, + /// `hidden`:内容裁剪标记(裁剪实现待 paint/layout 接入)。 + Hidden, +} + +/// `position` 值 +/// ([CSS Position 3 §2](https://drafts.csswg.org/css-position-3/#position-properties))。 +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +pub enum PositionValue { + /// `static`(initial):常规流,不建立包含块。 + Static, + /// `relative`:相对自身偏移,仍占常规流空间。 + Relative, + /// `absolute`:相对最近定位祖先(无则视口)定位,脱离常规流。 + Absolute, + /// `fixed`:相对视口定位(本布局层按 absolute 处理)。 + Fixed, +} + +/// `float` 值 +/// ([CSS 2.1 §9.5.1](https://www.w3.org/TR/CSS21/visuren.html#float-position))。 +/// +/// 逻辑值 `inline-start` / `inline-end` 不做,记偏差(本层仅 LTR)。 +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +pub enum FloatValue { + /// `none`(initial):不浮动。 + None, + /// `left`:左浮动。 + Left, + /// `right`:右浮动。 + Right, +} + +/// `clear` 值 +/// ([CSS 2.1 §9.5.2](https://www.w3.org/TR/CSS21/visuren.html#flow-control))。 +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +pub enum ClearValue { + /// `none`(initial):允许两侧有浮动。 + None, + /// `left`:下移到左侧浮动之下。 + Left, + /// `right`:下移到右侧浮动之下。 + Right, + /// `both`:下移到任一侧浮动之下。 + Both, +} + +/// `top` / `right` / `bottom` / `left` 值(inset) +/// ([CSS Position 3 §3](https://drafts.csswg.org/css-position-3/#insets))。 +#[derive(Debug, Clone, Copy, PartialEq)] +pub enum InsetValue { + /// 绝对长度(CSS px)。 + Length(f32), + /// 百分比(相对包含块对应轴尺寸;本层仅垂直相对高度,水平相对宽度, + /// 由 layout 解析)。 + Percent(f32), + /// `auto`(initial)。 + Auto, + /// 视口单位;cascade 在 computed 阶段折算(同 [`SizeValue::Viewport`])。 + Viewport(f32, ViewportUnit), +} + +/// `flex-direction` 值 +/// ([CSS Flexbox §8.3.1](https://drafts.csswg.org/css-flexbox/#flex-direction-property))。 +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +pub enum FlexDirectionValue { + /// `row`(initial)。 + Row, + /// `row-reverse`。 + RowReverse, + /// `column`。 + Column, + /// `column-reverse`。 + ColumnReverse, +} + +/// `flex-wrap` 值 +/// ([CSS Flexbox §8.4.1](https://drafts.csswg.org/css-flexbox/#flex-wrap-property))。 +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +pub enum FlexWrapValue { + /// `nowrap`(initial):单行。 + NoWrap, + /// `wrap`:多行。 + Wrap, + /// `wrap-reverse`:多行反向。 + WrapReverse, +} + +/// `align-items` / `align-self` 的 cross-axis 对齐值 +/// ([CSS Box Alignment §7](https://drafts.csswg.org/css-align-3/#align-items-property))。 +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +pub enum AlignItemsValue { + /// `stretch`(initial)。 + Stretch, + /// `flex-start` / `start`。 + FlexStart, + /// `flex-end` / `end`。 + FlexEnd, + /// `center`。 + Center, + /// `baseline`。 + Baseline, +} + +/// `justify-content` 的主轴对齐值 +/// ([CSS Box Alignment §8](https://drafts.csswg.org/css-align-3/#justify-content-property))。 +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +pub enum JustifyContentValue { + /// `flex-start` / `start`(initial)。 + FlexStart, + /// `flex-end` / `end`。 + FlexEnd, + /// `center`。 + Center, + /// `space-between`。 + SpaceBetween, + /// `space-around`。 + SpaceAround, + /// `space-evenly`。 + SpaceEvenly, +} + +/// `align-self` 值(在 `align-items` 基础上多一个 `auto` 回退父值)。 +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +pub enum AlignSelfValue { + /// `auto`(initial):回退到父 `align-items`。 + Auto, + /// 同 [`AlignItemsValue::Stretch`]。 + Stretch, + /// 同 [`AlignItemsValue::FlexStart`]。 + FlexStart, + /// 同 [`AlignItemsValue::FlexEnd`]。 + FlexEnd, + /// 同 [`AlignItemsValue::Center`]。 + Center, + /// 同 [`AlignItemsValue::Baseline`]。 + Baseline, +} + +/// `gap` 值 +/// ([CSS Box Alignment §6](https://drafts.csswg.org/css-align-3/#gap-shorthand))。 +#[derive(Debug, Clone, Copy, PartialEq)] +pub enum GapValue { + /// 绝对长度(CSS px)。 + Length(f32), + /// 百分比(相对包含块对应轴尺寸)。 + Percent(f32), + /// `normal`(initial):退化为 0。 + Normal, + /// 视口单位;cascade 在 computed 阶段折算(同 [`SizeValue::Viewport`])。 + Viewport(f32, ViewportUnit), +} + +/// `grid-auto-flow` 值 +/// ([CSS Grid §7.7](https://drafts.csswg.org/css-grid/#grid-auto-flow-property))。 +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +pub enum GridAutoFlowValue { + /// `row`(initial)。 + Row, + /// `column`。 + Column, + /// `row dense`。 + RowDense, + /// `column dense`。 + ColumnDense, +} + +/// 一条 grid 轨道的轨道尺寸函数(简化版)。 +/// +/// 仅覆盖布局几何需要的子集:固定长度、百分比、弹性系数 `fr`、自适应 +/// `auto`、以及两段式 `minmax(a, b)`(a/b 各为长度/百分比/fr/auto)。 +#[derive(Debug, Clone, PartialEq)] +pub enum GridTrack { + /// 固定长度(CSS px)。 + Length(f32), + /// 百分比(相对网格容器尺寸)。 + Percent(f32), + /// 弹性系数 `fr`(参与剩余空间分配)。 + Fr(f32), + /// `auto`:内容驱动尺寸。 + Auto, + /// `minmax(a, b)`。 + MinMax(Box<GridTrack>, Box<GridTrack>), +} + +/// `grid-template-columns` / `grid-template-rows` 的轨道列表。 +#[derive(Debug, Clone, PartialEq, Default)] +pub struct GridTrackList { + /// 轨道序列;空表示未显式指定(用隐式轨道)。 + pub tracks: Vec<GridTrack>, +} + +/// `margin-*` 值 +/// ([CSS 2.1 §8.3](https://www.w3.org/TR/CSS21/box.html#margin-properties))。 +/// +/// 可为负;百分比由 layout 相对包含块宽度解析。 +#[derive(Debug, Clone, Copy, PartialEq)] +pub enum MarginValue { + /// 绝对长度(CSS px,可负)。 + Length(f32), + /// 百分比(以小数存储)。 + Percent(f32), + /// `auto`(initial;块级布局中解析为 0 或剩余空间)。 + Auto, + /// 视口单位;cascade 在 computed 阶段折算(同 [`SizeValue::Viewport`])。 + Viewport(f32, ViewportUnit), +} + +/// `padding-*` 值 +/// ([CSS 2.1 §8.4](https://www.w3.org/TR/CSS21/box.html#padding-properties))。 +/// +/// 不接受 auto,负值非法;百分比由 layout 相对包含块宽度解析。 +#[derive(Debug, Clone, Copy, PartialEq)] +pub enum PaddingValue { + /// 绝对长度(CSS px,非负)。 + Length(f32), + /// 百分比(以小数存储)。 + Percent(f32), + /// 视口单位;cascade 在 computed 阶段折算(同 [`SizeValue::Viewport`])。 + Viewport(f32, ViewportUnit), +} + +/// `border-*-width` 值 +/// ([CSS 2.1 §8.5.4](https://www.w3.org/TR/CSS21/box.html#border-width-properties))。 +/// +/// 关键字在解析期折算(thin 1px / medium 3px / thick 5px,与浏览器默认一致); +/// computed 阶段 style 为 none/hidden 时归零(cascade 模块)。 +#[derive(Debug, Clone, Copy, PartialEq)] +pub enum BorderWidthValue { + /// 绝对长度(CSS px,非负)。 + Length(f32), + /// `thin`(1px)。 + Thin, + /// `medium`(initial,3px)。 + Medium, + /// `thick`(5px)。 + Thick, +} + +impl BorderWidthValue { + /// 关键字/长度 → CSS px。 + #[must_use] + pub fn px(self) -> f32 { + match self { + BorderWidthValue::Length(px) => px, + BorderWidthValue::Thin => 1.0, + BorderWidthValue::Medium => 3.0, + BorderWidthValue::Thick => 5.0, + } + } +} + +/// `border-*-style` 关键字 +/// ([CSS 2.1 §8.5.3](https://www.w3.org/TR/CSS21/box.html#border-style-properties))。 +/// +/// 全部 10 个关键字都按规范接受;绘制端当前只区分 none/hidden 与可见边框 +/// (`solid` 语义),其余样式的绘制待 paint 层扩展。 +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +pub enum BorderStyle { + /// `none`(initial)。 + None, + /// `hidden`。 + Hidden, + /// `solid`。 + Solid, + /// `dashed`。 + Dashed, + /// `dotted`。 + Dotted, + /// `double`。 + Double, + /// `groove`。 + Groove, + /// `ridge`。 + Ridge, + /// `inset`。 + Inset, + /// `outset`。 + Outset, +} + +impl BorderStyle { + /// 是否画出可见边框(none/hidden 之外)。 + #[must_use] + pub fn visible(self) -> bool { + !matches!(self, BorderStyle::None | BorderStyle::Hidden) + } +} + +/// `border-*-color` 值 +/// ([CSS 2.1 §8.5.2](https://www.w3.org/TR/CSS21/box.html#border-color-properties))。 +/// +/// `currentcolor` 在 computed 阶段按本元素 `color` 解析(cascade 模块)。 +#[derive(Debug, Clone, Copy, PartialEq)] +pub enum BorderColorValue { + /// 具体颜色。 + Rgba(Rgba), + /// `currentcolor`。 + CurrentColor, +} + +/// 把声明值解析为 [`DeclaredValue`]:先识别 CSS-wide 关键字,再按属性语法解析。 +/// +/// `input` 已由调用方限定在本条声明的值范围内(分号 / 块尾之前)。 +/// 返回值连同该声明是否带 `!important`(CSS Cascade 5 §5.1);返回 `Err` +/// 表示整条声明无效。 +pub(crate) fn parse_declared_value( + property: PropertyId, + input: &mut Parser<'_>, +) -> Result<(DeclaredValue, bool), ()> { + if let Ok(keyword) = input.try_parse(parse_css_wide_keyword) { + let important = input.try_parse(parse_important).is_ok(); + // CSS-wide 关键字不允许再拼接其他值 + // (CSS Cascade 5:关键字是完整的 <declaration-value>)。 + if input.expect_exhausted().is_err() { + return Err(()); + } + return Ok((DeclaredValue::CssWide(keyword), important)); + } + let value = parse_property_value(property, input)?; + let important = input.try_parse(parse_important).is_ok(); + if input.expect_exhausted().is_err() { + return Err(()); + } + Ok((DeclaredValue::Typed(value), important)) +} + +/// 解析 CSS-wide 关键字(ASCII case-insensitive)。 +pub(crate) fn parse_css_wide_keyword(input: &mut Parser<'_>) -> Result<CssWideKeyword, ()> { + let Token::Ident(name) = input.next().map_err(|_| ())? else { + return Err(()); + }; + if name.eq_ignore_ascii_case("initial") { + Ok(CssWideKeyword::Initial) + } else if name.eq_ignore_ascii_case("inherit") { + Ok(CssWideKeyword::Inherit) + } else if name.eq_ignore_ascii_case("unset") { + Ok(CssWideKeyword::Unset) + } else if name.eq_ignore_ascii_case("revert") { + Ok(CssWideKeyword::Revert) + } else { + Err(()) + } +} + +/// 按属性语法解析值。 +fn parse_property_value(property: PropertyId, input: &mut Parser<'_>) -> Result<PropertyValue, ()> { + match property { + PropertyId::Display => parse_display(input).map(PropertyValue::Display), + PropertyId::TextAlign => parse_text_align(input).map(PropertyValue::TextAlign), + PropertyId::FontStyle => parse_font_style(input).map(PropertyValue::FontStyle), + PropertyId::Color => parse_color(input).map(PropertyValue::Color), + PropertyId::FontSize => parse_font_size(input).map(PropertyValue::FontSize), + PropertyId::FontWeight => parse_font_weight(input).map(PropertyValue::FontWeight), + PropertyId::FontFamily => parse_font_family(input).map(PropertyValue::FontFamily), + PropertyId::BackgroundColor => parse_color(input).map(PropertyValue::Color), + PropertyId::LineHeight => parse_line_height(input).map(PropertyValue::LineHeight), + PropertyId::WhiteSpace => parse_white_space(input).map(PropertyValue::WhiteSpace), + PropertyId::OverflowWrap => parse_overflow_wrap(input).map(PropertyValue::OverflowWrap), + PropertyId::WordBreak => parse_word_break(input).map(PropertyValue::WordBreak), + PropertyId::LetterSpacing => parse_spacing(input).map(PropertyValue::LetterSpacing), + PropertyId::WordSpacing => parse_spacing(input).map(PropertyValue::WordSpacing), + PropertyId::TextIndent => parse_text_indent(input).map(PropertyValue::TextIndent), + PropertyId::TabSize => parse_tab_size(input).map(PropertyValue::TabSize), + PropertyId::Width + | PropertyId::Height + | PropertyId::MinWidth + | PropertyId::MaxWidth + | PropertyId::MinHeight + | PropertyId::MaxHeight => parse_size(input).map(PropertyValue::Size), + PropertyId::BoxSizing => parse_box_sizing(input).map(PropertyValue::BoxSizing), + PropertyId::Overflow => parse_overflow(input).map(PropertyValue::Overflow), + PropertyId::FlexGrow => parse_flex_grow(input).map(PropertyValue::FlexGrow), + PropertyId::FlexBasis => parse_size(input).map(PropertyValue::FlexBasis), + PropertyId::Position => parse_position(input).map(PropertyValue::Position), + PropertyId::Float => parse_float(input).map(PropertyValue::Float), + PropertyId::Clear => parse_clear(input).map(PropertyValue::Clear), + PropertyId::Top | PropertyId::Right | PropertyId::Bottom | PropertyId::Left => { + parse_inset(input).map(PropertyValue::Inset) + } + PropertyId::FlexDirection => parse_flex_direction(input).map(PropertyValue::FlexDirection), + PropertyId::FlexWrap => parse_flex_wrap(input).map(PropertyValue::FlexWrap), + PropertyId::FlexShrink => parse_flex_shrink(input).map(PropertyValue::FlexShrink), + PropertyId::AlignItems => parse_align_items(input).map(PropertyValue::AlignItems), + PropertyId::JustifyContent => { + parse_justify_content(input).map(PropertyValue::JustifyContent) + } + PropertyId::AlignSelf => parse_align_self(input).map(PropertyValue::AlignSelf), + PropertyId::GridTemplateColumns | PropertyId::GridTemplateRows => { + parse_grid_track_list(input).map(PropertyValue::GridTrack) + } + PropertyId::RowGap | PropertyId::ColumnGap => parse_gap(input).map(PropertyValue::Gap), + PropertyId::GridAutoFlow => parse_grid_auto_flow(input).map(PropertyValue::GridAutoFlow), + PropertyId::MarginTop + | PropertyId::MarginRight + | PropertyId::MarginBottom + | PropertyId::MarginLeft => parse_margin(input).map(PropertyValue::Margin), + PropertyId::PaddingTop + | PropertyId::PaddingRight + | PropertyId::PaddingBottom + | PropertyId::PaddingLeft => parse_padding(input).map(PropertyValue::Padding), + PropertyId::BorderTopWidth + | PropertyId::BorderRightWidth + | PropertyId::BorderBottomWidth + | PropertyId::BorderLeftWidth => parse_border_width(input).map(PropertyValue::BorderWidth), + PropertyId::BorderTopStyle + | PropertyId::BorderRightStyle + | PropertyId::BorderBottomStyle + | PropertyId::BorderLeftStyle => parse_border_style(input).map(PropertyValue::BorderStyle), + PropertyId::BorderTopColor + | PropertyId::BorderRightColor + | PropertyId::BorderBottomColor + | PropertyId::BorderLeftColor => parse_border_color(input).map(PropertyValue::BorderColor), + } +} + +/// `line-height`:normal | <number [0,∞]> | <length> | <percentage> +/// (CSS 2.1 §10.8.1)。 +fn parse_line_height(input: &mut Parser<'_>) -> Result<LineHeightValue, ()> { + match input.next().map_err(|_| ())? { + Token::Ident(name) if name.eq_ignore_ascii_case("normal") => Ok(LineHeightValue::Normal), + Token::Number { value, .. } => sanitize_number(*value) + .filter(|value| *value >= 0.0) + .map(LineHeightValue::Number) + .ok_or(()), + Token::Percentage { unit_value, .. } => sanitize_number(*unit_value) + .map(LineHeightValue::Percent) + .ok_or(()), + Token::Dimension { value, unit, .. } => { + if unit.eq_ignore_ascii_case("em") { + sanitize_number(*value).map(LineHeightValue::Em).ok_or(()) + } else { + length_to_px(*value, unit) + .map(LineHeightValue::Length) + .ok_or(()) + } + } + _ => Err(()), + } +} + +/// `letter-spacing` / `word-spacing`:normal | <length>(CSS Text 3 §8)。 +/// 负值合法;`0` 无单位合法(CSS Values 4);视口单位与百分比不接受。 +fn parse_spacing(input: &mut Parser<'_>) -> Result<SpacingValue, ()> { + match input.next().map_err(|_| ())? { + Token::Ident(name) if name.eq_ignore_ascii_case("normal") => Ok(SpacingValue::Normal), + Token::Number { value: 0.0, .. } => Ok(SpacingValue::Length(0.0)), + Token::Dimension { value, unit, .. } => { + if unit.eq_ignore_ascii_case("em") { + sanitize_number(*value).map(SpacingValue::Em).ok_or(()) + } else { + length_to_px(*value, unit) + .map(SpacingValue::Length) + .ok_or(()) + } + } + _ => Err(()), + } +} + +/// `text-indent`:<length-percentage>(CSS Text 3 §4)。负值合法。 +fn parse_text_indent(input: &mut Parser<'_>) -> Result<TextIndentValue, ()> { + match input.next().map_err(|_| ())? { + Token::Number { value: 0.0, .. } => Ok(TextIndentValue::Length(0.0)), + Token::Percentage { unit_value, .. } => sanitize_number(*unit_value) + .map(TextIndentValue::Percent) + .ok_or(()), + Token::Dimension { value, unit, .. } => { + if unit.eq_ignore_ascii_case("em") { + sanitize_number(*value).map(TextIndentValue::Em).ok_or(()) + } else { + length_to_px(*value, unit) + .map(TextIndentValue::Length) + .ok_or(()) + } + } + _ => Err(()), + } +} + +/// `tab-size`:<integer [0,∞]> | <length [0,∞]>(CSS Text 3 §5)。 +/// 整数 token 之外的 Number(小数 / 负数)按无效处理。 +fn parse_tab_size(input: &mut Parser<'_>) -> Result<TabSizeValue, ()> { + match input.next().map_err(|_| ())? { + Token::Number { + int_value: Some(int), + .. + } if *int >= 0 => Ok(TabSizeValue::Integer(*int as u32)), + Token::Number { .. } => Err(()), + Token::Dimension { value, unit, .. } => { + if *value < 0.0 { + return Err(()); + } + if unit.eq_ignore_ascii_case("em") { + sanitize_number(*value).map(TabSizeValue::Em).ok_or(()) + } else { + length_to_px(*value, unit) + .map(TabSizeValue::Length) + .ok_or(()) + } + } + _ => Err(()), + } +} + +/// `white-space`:CSS Text 3 §3.1 的六个关键字。 +/// +/// Level 4 拆分的 `white-space-collapse` / `text-wrap-mode` 未实现;两个关键字 +/// 连写(如 `pre nowrap`)按非法值整条丢弃。 +fn parse_white_space(input: &mut Parser<'_>) -> Result<WhiteSpaceValue, ()> { + let Token::Ident(name) = input.next().map_err(|_| ())? else { + return Err(()); + }; + if name.eq_ignore_ascii_case("normal") { + Ok(WhiteSpaceValue::Normal) + } else if name.eq_ignore_ascii_case("nowrap") { + Ok(WhiteSpaceValue::Nowrap) + } else if name.eq_ignore_ascii_case("pre") { + Ok(WhiteSpaceValue::Pre) + } else if name.eq_ignore_ascii_case("pre-wrap") { + Ok(WhiteSpaceValue::PreWrap) + } else if name.eq_ignore_ascii_case("pre-line") { + Ok(WhiteSpaceValue::PreLine) + } else if name.eq_ignore_ascii_case("break-spaces") { + Ok(WhiteSpaceValue::BreakSpaces) + } else { + Err(()) + } +} + +/// `overflow-wrap`:normal | break-word | anywhere(CSS Text 3 §5.4)。 +fn parse_overflow_wrap(input: &mut Parser<'_>) -> Result<OverflowWrapValue, ()> { + let Token::Ident(name) = input.next().map_err(|_| ())? else { + return Err(()); + }; + if name.eq_ignore_ascii_case("normal") { + Ok(OverflowWrapValue::Normal) + } else if name.eq_ignore_ascii_case("break-word") { + Ok(OverflowWrapValue::BreakWord) + } else if name.eq_ignore_ascii_case("anywhere") { + Ok(OverflowWrapValue::Anywhere) + } else { + Err(()) + } +} + +/// `word-break`:normal | break-all | keep-all(CSS Text 3 §5.1)。 +fn parse_word_break(input: &mut Parser<'_>) -> Result<WordBreakValue, ()> { + let Token::Ident(name) = input.next().map_err(|_| ())? else { + return Err(()); + }; + if name.eq_ignore_ascii_case("normal") { + Ok(WordBreakValue::Normal) + } else if name.eq_ignore_ascii_case("break-all") { + Ok(WordBreakValue::BreakAll) + } else if name.eq_ignore_ascii_case("keep-all") { + Ok(WordBreakValue::KeepAll) + } else { + Err(()) + } +} + +/// `width` / `height`:<length> | <percentage> | auto,负值非法。 +fn parse_size(input: &mut Parser<'_>) -> Result<SizeValue, ()> { + match input.next().map_err(|_| ())? { + Token::Ident(name) if name.eq_ignore_ascii_case("auto") => Ok(SizeValue::Auto), + Token::Number { value: 0.0, .. } => Ok(SizeValue::Length(0.0)), + Token::Percentage { unit_value, .. } => sanitize_number(*unit_value) + .map(SizeValue::Percent) + .ok_or(()), + Token::Dimension { value, unit, .. } => { + if *value < 0.0 { + return Err(()); + } + if let Some((amount, unit)) = viewport_length(*value, unit) { + return sanitize_number(amount) + .map(|amount| SizeValue::Viewport(amount, unit)) + .ok_or(()); + } + length_to_px(*value, unit).map(SizeValue::Length).ok_or(()) + } + _ => Err(()), + } +} + +/// `box-sizing`:content-box | border-box(ASCII case-insensitive)。 +fn parse_box_sizing(input: &mut Parser<'_>) -> Result<BoxSizingValue, ()> { + match input.next().map_err(|_| ())? { + Token::Ident(name) if name.eq_ignore_ascii_case("content-box") => { + Ok(BoxSizingValue::ContentBox) + } + Token::Ident(name) if name.eq_ignore_ascii_case("border-box") => { + Ok(BoxSizingValue::BorderBox) + } + _ => Err(()), + } +} + +/// `overflow`:visible | hidden(偏差:auto/scroll/clip 暂按无效丢弃)。 +fn parse_overflow(input: &mut Parser<'_>) -> Result<OverflowValue, ()> { + match input.next().map_err(|_| ())? { + Token::Ident(name) if name.eq_ignore_ascii_case("visible") => Ok(OverflowValue::Visible), + Token::Ident(name) if name.eq_ignore_ascii_case("hidden") => Ok(OverflowValue::Hidden), + _ => Err(()), + } +} + +/// `flex-grow`:<number [0,∞]>(CSS Flexbox §7.1;负数非法)。 +fn parse_flex_grow(input: &mut Parser<'_>) -> Result<f32, ()> { + match input.next().map_err(|_| ())? { + Token::Number { value, .. } if *value >= 0.0 => sanitize_number(*value).ok_or(()), + _ => Err(()), + } +} + +/// `position`:static | relative | absolute | fixed(ASCII case-insensitive)。 +/// +/// `fixed` 在本布局层按 `absolute` 处理(相对视口定位的包含块由 layout 提供)。 +fn parse_position(input: &mut Parser<'_>) -> Result<PositionValue, ()> { + let Token::Ident(name) = input.next().map_err(|_| ())? else { + return Err(()); + }; + if name.eq_ignore_ascii_case("static") { + Ok(PositionValue::Static) + } else if name.eq_ignore_ascii_case("relative") { + Ok(PositionValue::Relative) + } else if name.eq_ignore_ascii_case("absolute") { + Ok(PositionValue::Absolute) + } else if name.eq_ignore_ascii_case("fixed") { + Ok(PositionValue::Fixed) + } else { + Err(()) + } +} + +/// `float`:none | left | right(ASCII case-insensitive,CSS 2.1 §9.5.1)。 +fn parse_float(input: &mut Parser<'_>) -> Result<FloatValue, ()> { + let Token::Ident(name) = input.next().map_err(|_| ())? else { + return Err(()); + }; + if name.eq_ignore_ascii_case("none") { + Ok(FloatValue::None) + } else if name.eq_ignore_ascii_case("left") { + Ok(FloatValue::Left) + } else if name.eq_ignore_ascii_case("right") { + Ok(FloatValue::Right) + } else { + Err(()) + } +} + +/// `clear`:none | left | right | both(ASCII case-insensitive,CSS 2.1 §9.5.2)。 +fn parse_clear(input: &mut Parser<'_>) -> Result<ClearValue, ()> { + let Token::Ident(name) = input.next().map_err(|_| ())? else { + return Err(()); + }; + if name.eq_ignore_ascii_case("none") { + Ok(ClearValue::None) + } else if name.eq_ignore_ascii_case("left") { + Ok(ClearValue::Left) + } else if name.eq_ignore_ascii_case("right") { + Ok(ClearValue::Right) + } else if name.eq_ignore_ascii_case("both") { + Ok(ClearValue::Both) + } else { + Err(()) + } +} +fn parse_inset(input: &mut Parser<'_>) -> Result<InsetValue, ()> { + match input.next().map_err(|_| ())? { + Token::Ident(name) if name.eq_ignore_ascii_case("auto") => Ok(InsetValue::Auto), + Token::Number { value: 0.0, .. } => Ok(InsetValue::Length(0.0)), + Token::Percentage { unit_value, .. } => sanitize_number(*unit_value) + .map(InsetValue::Percent) + .ok_or(()), + Token::Dimension { value, unit, .. } => { + if let Some((amount, unit)) = viewport_length(*value, unit) { + return sanitize_number(amount) + .map(|amount| InsetValue::Viewport(amount, unit)) + .ok_or(()); + } + length_to_px(*value, unit).map(InsetValue::Length).ok_or(()) + } + _ => Err(()), + } +} + +/// `flex-direction`:row | row-reverse | column | column-reverse。 +fn parse_flex_direction(input: &mut Parser<'_>) -> Result<FlexDirectionValue, ()> { + let Token::Ident(name) = input.next().map_err(|_| ())? else { + return Err(()); + }; + if name.eq_ignore_ascii_case("row") { + Ok(FlexDirectionValue::Row) + } else if name.eq_ignore_ascii_case("row-reverse") { + Ok(FlexDirectionValue::RowReverse) + } else if name.eq_ignore_ascii_case("column") { + Ok(FlexDirectionValue::Column) + } else if name.eq_ignore_ascii_case("column-reverse") { + Ok(FlexDirectionValue::ColumnReverse) + } else { + Err(()) + } +} + +/// `flex-wrap`:nowrap | wrap | wrap-reverse。 +fn parse_flex_wrap(input: &mut Parser<'_>) -> Result<FlexWrapValue, ()> { + let Token::Ident(name) = input.next().map_err(|_| ())? else { + return Err(()); + }; + if name.eq_ignore_ascii_case("nowrap") { + Ok(FlexWrapValue::NoWrap) + } else if name.eq_ignore_ascii_case("wrap") { + Ok(FlexWrapValue::Wrap) + } else if name.eq_ignore_ascii_case("wrap-reverse") { + Ok(FlexWrapValue::WrapReverse) + } else { + Err(()) + } +} + +/// `flex-shrink`:<number [0,∞]>(CSS Flexbox §7.2;负数非法)。 +fn parse_flex_shrink(input: &mut Parser<'_>) -> Result<f32, ()> { + match input.next().map_err(|_| ())? { + Token::Number { value, .. } if *value >= 0.0 => sanitize_number(*value).ok_or(()), + _ => Err(()), + } +} + +/// `align-items`:stretch | flex-start | flex-end | center | baseline +/// (兼容 `start` / `end` 取 flex-* 语义;CSS Box Alignment §7)。 +fn parse_align_items(input: &mut Parser<'_>) -> Result<AlignItemsValue, ()> { + let Token::Ident(name) = input.next().map_err(|_| ())? else { + return Err(()); + }; + if name.eq_ignore_ascii_case("stretch") { + Ok(AlignItemsValue::Stretch) + } else if name.eq_ignore_ascii_case("flex-start") || name.eq_ignore_ascii_case("start") { + Ok(AlignItemsValue::FlexStart) + } else if name.eq_ignore_ascii_case("flex-end") || name.eq_ignore_ascii_case("end") { + Ok(AlignItemsValue::FlexEnd) + } else if name.eq_ignore_ascii_case("center") { + Ok(AlignItemsValue::Center) + } else if name.eq_ignore_ascii_case("baseline") { + Ok(AlignItemsValue::Baseline) + } else { + Err(()) + } +} + +/// `justify-content`:flex-start | flex-end | center | space-between | +/// space-around | space-evenly(兼容 `start` / `end`)。 +fn parse_justify_content(input: &mut Parser<'_>) -> Result<JustifyContentValue, ()> { + let Token::Ident(name) = input.next().map_err(|_| ())? else { + return Err(()); + }; + if name.eq_ignore_ascii_case("flex-start") || name.eq_ignore_ascii_case("start") { + Ok(JustifyContentValue::FlexStart) + } else if name.eq_ignore_ascii_case("flex-end") || name.eq_ignore_ascii_case("end") { + Ok(JustifyContentValue::FlexEnd) + } else if name.eq_ignore_ascii_case("center") { + Ok(JustifyContentValue::Center) + } else if name.eq_ignore_ascii_case("space-between") { + Ok(JustifyContentValue::SpaceBetween) + } else if name.eq_ignore_ascii_case("space-around") { + Ok(JustifyContentValue::SpaceAround) + } else if name.eq_ignore_ascii_case("space-evenly") { + Ok(JustifyContentValue::SpaceEvenly) + } else { + Err(()) + } +} + +/// `align-self`:auto | stretch | flex-start | flex-end | center | baseline。 +fn parse_align_self(input: &mut Parser<'_>) -> Result<AlignSelfValue, ()> { + let Token::Ident(name) = input.next().map_err(|_| ())? else { + return Err(()); + }; + if name.eq_ignore_ascii_case("auto") { + Ok(AlignSelfValue::Auto) + } else if name.eq_ignore_ascii_case("stretch") { + Ok(AlignSelfValue::Stretch) + } else if name.eq_ignore_ascii_case("flex-start") || name.eq_ignore_ascii_case("start") { + Ok(AlignSelfValue::FlexStart) + } else if name.eq_ignore_ascii_case("flex-end") || name.eq_ignore_ascii_case("end") { + Ok(AlignSelfValue::FlexEnd) + } else if name.eq_ignore_ascii_case("center") { + Ok(AlignSelfValue::Center) + } else if name.eq_ignore_ascii_case("baseline") { + Ok(AlignSelfValue::Baseline) + } else { + Err(()) + } +} + +/// `row-gap` / `column-gap`:<length> | <percentage> | normal +/// (CSS Box Alignment §6;`auto` 不是合法 gap 值,按无效声明丢弃)。 +fn parse_gap(input: &mut Parser<'_>) -> Result<GapValue, ()> { + match input.next().map_err(|_| ())? { + Token::Ident(name) if name.eq_ignore_ascii_case("normal") => Ok(GapValue::Normal), + Token::Number { value: 0.0, .. } => Ok(GapValue::Length(0.0)), + Token::Percentage { unit_value, .. } => sanitize_number(*unit_value) + .map(GapValue::Percent) + .ok_or(()), + Token::Dimension { value, unit, .. } => { + if let Some((amount, unit)) = viewport_length(*value, unit) { + return sanitize_number(amount) + .map(|amount| GapValue::Viewport(amount, unit)) + .ok_or(()); + } + length_to_px(*value, unit).map(GapValue::Length).ok_or(()) + } + _ => Err(()), + } +} + +/// `grid-auto-flow`:row | column | row dense | column dense。 +fn parse_grid_auto_flow(input: &mut Parser<'_>) -> Result<GridAutoFlowValue, ()> { + let first = match input.next().map_err(|_| ())? { + Token::Ident(name) if name.eq_ignore_ascii_case("row") => GridAutoFlowValue::Row, + Token::Ident(name) if name.eq_ignore_ascii_case("column") => GridAutoFlowValue::Column, + _ => return Err(()), + }; + // 可选 `dense` 后缀 + if input + .try_parse(|i| i.expect_ident_matching("dense").map(|_| ())) + .is_ok() + { + if input.expect_exhausted().is_err() { + return Err(()); + } + return Ok(match first { + GridAutoFlowValue::Row => GridAutoFlowValue::RowDense, + GridAutoFlowValue::Column => GridAutoFlowValue::ColumnDense, + _ => unreachable!(), + }); + } + if input.expect_exhausted().is_err() { + return Err(()); + } + Ok(first) +} + +/// `grid-template-columns` / `grid-template-rows` 的轨道列表解析 +/// (CSS Grid §7.2/§7.3;空白分隔轨道,支持 `minmax()`)。 +fn parse_grid_track_list(input: &mut Parser<'_>) -> Result<GridTrackList, ()> { + let mut tracks = Vec::new(); + let mut first = true; + while !input.is_exhausted() { + if !first && input.try_parse(|i| i.expect_whitespace()).is_err() { + return Err(()); + } + first = false; + tracks.push(parse_grid_track(input)?); + } + Ok(GridTrackList { tracks }) +} + +/// 单条 grid 轨道尺寸函数。 +fn parse_grid_track(input: &mut Parser<'_>) -> Result<GridTrack, ()> { + if input + .try_parse(|i| i.expect_function_matching("minmax").map(|_| ())) + .is_ok() + { + return input + .parse_nested_block(|i| { + let a = + parse_grid_track_size(i).map_err(|_| ParseError::<()>::unexpected_token())?; + i.expect_comma() + .map_err(|_| ParseError::<()>::unexpected_token())?; + let b = + parse_grid_track_size(i).map_err(|_| ParseError::<()>::unexpected_token())?; + i.expect_exhausted() + .map_err(|_| ParseError::<()>::unexpected_token())?; + Ok(GridTrack::MinMax(Box::new(a), Box::new(b))) + }) + .map_err(|_| ()); + } + parse_grid_track_size(input) +} + +/// 单段轨道尺寸(`minmax` 内的一段):<length> | <percentage> | <flex> | auto。 +fn parse_grid_track_size(input: &mut Parser<'_>) -> Result<GridTrack, ()> { + match input.next().map_err(|_| ())? { + Token::Ident(name) if name.eq_ignore_ascii_case("auto") => Ok(GridTrack::Auto), + Token::Number { value: 0.0, .. } => Ok(GridTrack::Length(0.0)), + Token::Percentage { unit_value, .. } => sanitize_number(*unit_value) + .map(GridTrack::Percent) + .ok_or(()), + Token::Dimension { value, unit, .. } => { + if unit.eq_ignore_ascii_case("fr") { + sanitize_number(*value).map(GridTrack::Fr).ok_or(()) + } else { + length_to_px(*value, unit).map(GridTrack::Length).ok_or(()) + } + } + _ => Err(()), + } +} + +/// `margin-*`:<length> | <percentage> | auto,长度可负。 +fn parse_margin(input: &mut Parser<'_>) -> Result<MarginValue, ()> { + match input.next().map_err(|_| ())? { + Token::Ident(name) if name.eq_ignore_ascii_case("auto") => Ok(MarginValue::Auto), + Token::Number { value: 0.0, .. } => Ok(MarginValue::Length(0.0)), + Token::Percentage { unit_value, .. } => sanitize_number(*unit_value) + .map(MarginValue::Percent) + .ok_or(()), + Token::Dimension { value, unit, .. } => { + if let Some((amount, unit)) = viewport_length(*value, unit) { + return sanitize_number(amount) + .map(|amount| MarginValue::Viewport(amount, unit)) + .ok_or(()); + } + length_to_px(*value, unit) + .map(MarginValue::Length) + .ok_or(()) + } + _ => Err(()), + } +} + +/// `padding-*`:<length> | <percentage>,不接受 auto、负值非法。 +fn parse_padding(input: &mut Parser<'_>) -> Result<PaddingValue, ()> { + match input.next().map_err(|_| ())? { + Token::Number { value: 0.0, .. } => Ok(PaddingValue::Length(0.0)), + Token::Percentage { unit_value, .. } => sanitize_number(*unit_value) + .map(PaddingValue::Percent) + .ok_or(()), + Token::Dimension { value, unit, .. } => { + if *value < 0.0 { + return Err(()); + } + if let Some((amount, unit)) = viewport_length(*value, unit) { + return sanitize_number(amount) + .map(|amount| PaddingValue::Viewport(amount, unit)) + .ok_or(()); + } + length_to_px(*value, unit) + .map(PaddingValue::Length) + .ok_or(()) + } + _ => Err(()), + } +} + +/// `border-*-width`:<line-width>(<length [0,∞]> | thin | medium | thick)。 +fn parse_border_width(input: &mut Parser<'_>) -> Result<BorderWidthValue, ()> { + match input.next().map_err(|_| ())? { + Token::Ident(name) if name.eq_ignore_ascii_case("thin") => Ok(BorderWidthValue::Thin), + Token::Ident(name) if name.eq_ignore_ascii_case("medium") => Ok(BorderWidthValue::Medium), + Token::Ident(name) if name.eq_ignore_ascii_case("thick") => Ok(BorderWidthValue::Thick), + Token::Number { value: 0.0, .. } => Ok(BorderWidthValue::Length(0.0)), + Token::Dimension { value, unit, .. } => { + if *value < 0.0 { + return Err(()); + } + length_to_px(*value, unit) + .map(BorderWidthValue::Length) + .ok_or(()) + } + _ => Err(()), + } +} + +/// `border-*-style`:<line-style>(10 个关键字)。 +fn parse_border_style(input: &mut Parser<'_>) -> Result<BorderStyle, ()> { + let Token::Ident(name) = input.next().map_err(|_| ())? else { + return Err(()); + }; + const STYLES: [(&str, BorderStyle); 10] = [ + ("none", BorderStyle::None), + ("hidden", BorderStyle::Hidden), + ("solid", BorderStyle::Solid), + ("dashed", BorderStyle::Dashed), + ("dotted", BorderStyle::Dotted), + ("double", BorderStyle::Double), + ("groove", BorderStyle::Groove), + ("ridge", BorderStyle::Ridge), + ("inset", BorderStyle::Inset), + ("outset", BorderStyle::Outset), + ]; + STYLES + .into_iter() + .find(|(keyword, _)| keyword.eq_ignore_ascii_case(name)) + .map(|(_, style)| style) + .ok_or(()) +} + +/// `border-*-color`:<color> | currentcolor。 +fn parse_border_color(input: &mut Parser<'_>) -> Result<BorderColorValue, ()> { + if let Ok(rgba) = input.try_parse(parse_color) { + return Ok(BorderColorValue::Rgba(rgba)); + } + match input.next().map_err(|_| ())? { + Token::Ident(name) if name.eq_ignore_ascii_case("currentcolor") => { + Ok(BorderColorValue::CurrentColor) + } + _ => Err(()), + } +} + +/// 以下为简写展开(parser 模块)复用的单值解析入口。 +pub(crate) fn parse_margin_value(input: &mut Parser<'_>) -> Result<MarginValue, ()> { + parse_margin(input) +} + +pub(crate) fn parse_padding_value(input: &mut Parser<'_>) -> Result<PaddingValue, ()> { + parse_padding(input) +} + +pub(crate) fn parse_border_width_value(input: &mut Parser<'_>) -> Result<BorderWidthValue, ()> { + parse_border_width(input) +} + +pub(crate) fn parse_border_style_value(input: &mut Parser<'_>) -> Result<BorderStyle, ()> { + parse_border_style(input) +} + +pub(crate) fn parse_border_color_value(input: &mut Parser<'_>) -> Result<BorderColorValue, ()> { + parse_border_color(input) +} + +/// `inset` 简写复用单值解析入口。 +pub(crate) fn parse_inset_value(input: &mut Parser<'_>) -> Result<InsetValue, ()> { + parse_inset(input) +} + +/// `gap` 简写复用单值解析入口。 +pub(crate) fn parse_gap_value(input: &mut Parser<'_>) -> Result<GapValue, ()> { + parse_gap(input) +} + +fn parse_display(input: &mut Parser<'_>) -> Result<DisplayValue, ()> { + let Token::Ident(name) = input.next().map_err(|_| ())? else { + return Err(()); + }; + if name.eq_ignore_ascii_case("inline") { + return Ok(DisplayValue::Inline); + } + if name.eq_ignore_ascii_case("block") { + return Ok(DisplayValue::Block); + } + if name.eq_ignore_ascii_case("list-item") { + return Ok(DisplayValue::ListItem); + } + if name.eq_ignore_ascii_case("inline-block") { + return Ok(DisplayValue::InlineBlock); + } + if name.eq_ignore_ascii_case("flow-root") { + return Ok(DisplayValue::FlowRoot); + } + if name.eq_ignore_ascii_case("flex") { + return Ok(DisplayValue::Flex); + } + if name.eq_ignore_ascii_case("inline-flex") { + return Ok(DisplayValue::InlineFlex); + } + if name.eq_ignore_ascii_case("grid") { + return Ok(DisplayValue::Grid); + } + if name.eq_ignore_ascii_case("inline-grid") { + return Ok(DisplayValue::InlineGrid); + } + if name.eq_ignore_ascii_case("table") { + return Ok(DisplayValue::Table); + } + if name.eq_ignore_ascii_case("inline-table") { + return Ok(DisplayValue::InlineTable); + } + if name.eq_ignore_ascii_case("contents") { + return Ok(DisplayValue::Contents); + } + if name.eq_ignore_ascii_case("none") { + return Ok(DisplayValue::None); + } + const INTERNAL: [(&str, &str); 8] = [ + ("table-row-group", "table-row-group"), + ("table-header-group", "table-header-group"), + ("table-footer-group", "table-footer-group"), + ("table-row", "table-row"), + ("table-cell", "table-cell"), + ("table-column-group", "table-column-group"), + ("table-column", "table-column"), + ("table-caption", "table-caption"), + ]; + for (keyword, label) in INTERNAL { + if name.eq_ignore_ascii_case(keyword) { + return Ok(DisplayValue::TableInternal(label)); + } + } + Err(()) +} + +fn parse_text_align(input: &mut Parser<'_>) -> Result<TextAlignValue, ()> { + let Token::Ident(name) = input.next().map_err(|_| ())? else { + return Err(()); + }; + if name.eq_ignore_ascii_case("start") { + return Ok(TextAlignValue::Start); + } + if name.eq_ignore_ascii_case("end") { + return Ok(TextAlignValue::End); + } + if name.eq_ignore_ascii_case("left") { + return Ok(TextAlignValue::Left); + } + if name.eq_ignore_ascii_case("right") { + return Ok(TextAlignValue::Right); + } + if name.eq_ignore_ascii_case("center") { + return Ok(TextAlignValue::Center); + } + if name.eq_ignore_ascii_case("justify") { + return Ok(TextAlignValue::Justify); + } + if name.eq_ignore_ascii_case("match-parent") { + return Ok(TextAlignValue::MatchParent); + } + if name.eq_ignore_ascii_case("justify-all") { + return Ok(TextAlignValue::JustifyAll); + } + Err(()) +} + +fn parse_font_style(input: &mut Parser<'_>) -> Result<FontStyleValue, ()> { + let Token::Ident(name) = input.next().map_err(|_| ())? else { + return Err(()); + }; + if name.eq_ignore_ascii_case("normal") { + return Ok(FontStyleValue::Normal); + } + if name.eq_ignore_ascii_case("italic") { + return Ok(FontStyleValue::Italic); + } + if name.eq_ignore_ascii_case("oblique") { + // oblique [ <angle> | none ]? + let angle = input.try_parse(parse_angle).ok(); + if angle.is_none() + && (input.try_parse(|i| i.expect_ident_matching("none").map_err(|_| ()))).is_err() + && input.expect_exhausted().is_err() + { + return Err(()); + } + return Ok(FontStyleValue::Oblique(angle)); + } + Err(()) +} + +/// 解析角度并折算为角度制。 +fn parse_angle(input: &mut Parser<'_>) -> Result<f32, ()> { + match input.next().map_err(|_| ())? { + Token::Dimension { value, unit, .. } => { + if unit.eq_ignore_ascii_case("deg") { + Ok(*value) + } else if unit.eq_ignore_ascii_case("grad") { + Ok(*value * 360.0 / 400.0) + } else if unit.eq_ignore_ascii_case("rad") { + Ok(value.to_degrees()) + } else if unit.eq_ignore_ascii_case("turn") { + Ok(*value * 360.0) + } else { + Err(()) + } + } + _ => Err(()), + } +} + +/// 长度类数值的卫生上限(CSS px)。 +/// +/// 不可信输入里的巨数 token(`1e40px` 在 f32 中溢出为 `inf`)与相对单位 +/// 乘积在解析/计算出口被钳到该量级(与 Chromium 的传统长度上限同量级; +/// 超出按 UA clamp 记偏差),`inf`/`NaN` 直接拒绝——非有限值一旦进入 +/// 布局会沿几何扩散污染整页坐标。 +pub const MAX_CSS_LENGTH: f32 = 1.0e7; + +/// 解析出口的数值卫生:非有限值拒绝(整条声明按无效处理),有限值 clamp +/// 到 `[-MAX_CSS_LENGTH, MAX_CSS_LENGTH]`。 +pub(crate) fn sanitize_number(value: f32) -> Option<f32> { + value + .is_finite() + .then(|| value.clamp(-MAX_CSS_LENGTH, MAX_CSS_LENGTH)) +} + +/// `<length-percentage>` 折算为 px;返回 `None` 表示该单位不受支持或数值 +/// 非有限。 +fn length_to_px(value: f32, unit: &str) -> Option<f32> { + let px = if unit.eq_ignore_ascii_case("px") { + Some(value) + } else if unit.eq_ignore_ascii_case("pt") { + // 1pt = 1/72in,1in = 96px(CSS Values 4 绝对长度定义) + Some(value * 96.0 / 72.0) + } else if unit.eq_ignore_ascii_case("pc") { + Some(value * 16.0) + } else if unit.eq_ignore_ascii_case("in") { + Some(value * 96.0) + } else if unit.eq_ignore_ascii_case("cm") { + Some(value * 96.0 / 2.54) + } else if unit.eq_ignore_ascii_case("mm") { + Some(value * 96.0 / 25.4) + } else if unit.eq_ignore_ascii_case("q") { + Some(value * 96.0 / 101.6) + } else { + None + }?; + sanitize_number(px) +} + +/// 视口单位([CSS Values 4 §6.2](https://drafts.csswg.org/css-values-4/#viewport-relative-units)): +/// 相对初始包含块(视口)对应边的小数百分比基数。 +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +pub enum ViewportUnit { + /// `vw`:视口宽的 1%。 + Vw, + /// `vh`:视口高的 1%。 + Vh, + /// `vmin`:视口短边的 1%。 + Vmin, + /// `vmax`:视口长边的 1%。 + Vmax, +} + +/// 维度 token 的单位是否为视口单位;是则返回 `(数量, 单位)`。 +fn viewport_length(value: f32, unit: &str) -> Option<(f32, ViewportUnit)> { + let unit = if unit.eq_ignore_ascii_case("vw") { + ViewportUnit::Vw + } else if unit.eq_ignore_ascii_case("vh") { + ViewportUnit::Vh + } else if unit.eq_ignore_ascii_case("vmin") { + ViewportUnit::Vmin + } else if unit.eq_ignore_ascii_case("vmax") { + ViewportUnit::Vmax + } else { + return None; + }; + Some((value, unit)) +} + +fn parse_font_size(input: &mut Parser<'_>) -> Result<FontSizeValue, ()> { + match input.next().map_err(|_| ())? { + // <length> 为 0 时单位可省略(CSS Values 4) + Token::Number { value: 0.0, .. } => Ok(FontSizeValue::Px(0.0)), + Token::Number { .. } => Err(()), + Token::Percentage { unit_value, .. } => sanitize_number(*unit_value) + .map(FontSizeValue::Percent) + .ok_or(()), + Token::Dimension { value, unit, .. } => { + if unit.eq_ignore_ascii_case("em") { + sanitize_number(*value).map(FontSizeValue::Em).ok_or(()) + } else { + length_to_px(*value, unit).map(FontSizeValue::Px).ok_or(()) + } + } + Token::Ident(name) => { + if name.eq_ignore_ascii_case("xx-small") { + Ok(FontSizeValue::Absolute(AbsoluteSize::XxSmall)) + } else if name.eq_ignore_ascii_case("x-small") { + Ok(FontSizeValue::Absolute(AbsoluteSize::XSmall)) + } else if name.eq_ignore_ascii_case("small") { + Ok(FontSizeValue::Absolute(AbsoluteSize::Small)) + } else if name.eq_ignore_ascii_case("medium") { + Ok(FontSizeValue::Absolute(AbsoluteSize::Medium)) + } else if name.eq_ignore_ascii_case("large") { + Ok(FontSizeValue::Absolute(AbsoluteSize::Large)) + } else if name.eq_ignore_ascii_case("x-large") { + Ok(FontSizeValue::Absolute(AbsoluteSize::XLarge)) + } else if name.eq_ignore_ascii_case("xx-large") { + Ok(FontSizeValue::Absolute(AbsoluteSize::XxLarge)) + } else if name.eq_ignore_ascii_case("xxx-large") { + Ok(FontSizeValue::Absolute(AbsoluteSize::XxxLarge)) + } else if name.eq_ignore_ascii_case("larger") { + Ok(FontSizeValue::Larger) + } else if name.eq_ignore_ascii_case("smaller") { + Ok(FontSizeValue::Smaller) + } else { + Err(()) + } + } + _ => Err(()), + } +} + +fn parse_font_weight(input: &mut Parser<'_>) -> Result<FontWeightValue, ()> { + match input.next().map_err(|_| ())? { + Token::Number { value, .. } => { + // CSS Fonts 4:<number [1,1000]>,越界无效 + if (1.0..=1000.0).contains(value) { + Ok(FontWeightValue::Weight(*value)) + } else { + Err(()) + } + } + Token::Ident(name) => { + if name.eq_ignore_ascii_case("normal") { + Ok(FontWeightValue::Weight(400.0)) + } else if name.eq_ignore_ascii_case("bold") { + Ok(FontWeightValue::Weight(700.0)) + } else if name.eq_ignore_ascii_case("bolder") { + Ok(FontWeightValue::Bolder) + } else if name.eq_ignore_ascii_case("lighter") { + Ok(FontWeightValue::Lighter) + } else { + Err(()) + } + } + _ => Err(()), + } +} + +fn parse_font_family(input: &mut Parser<'_>) -> Result<Vec<FontFamilyValue>, ()> { + let mut families = Vec::new(); + loop { + families.push(parse_family_item(input)?); + // 逗号 → 还有下一项;`!`(!important 前缀)、其他终止符或 EOF → + // 族名列表结束,后续交给调用方(parse_important / 耗尽校验)。 + // 注意逗号是独立的 Token::Comma,不是 Delim。 + if input.try_parse(|i| i.expect_comma()).is_err() { + break; + } + } + Ok(families) +} + +/// 解析一个字体族名:`<string>` 或一串 `<custom-ident>`(以空白分隔)。 +/// +/// 遇到终止符(逗号、`!`、EOF)即停止且不消费,留给调用方——它们经 +/// `try_parse` 的 `Err` 返回,位置已还原;其他无法归入族名语法的 token +/// (数字、不匹配的括号等)照常消费并由 [`family_from_tokens`] 判为无效。 +fn parse_family_item(input: &mut Parser<'_>) -> Result<FontFamilyValue, ()> { + let mut tokens = Vec::new(); + loop { + let peeked = input.try_parse(|i| match i.next_including_whitespace() { + Ok(Token::Comma) | Ok(Token::Delim('!')) => Err(()), + Ok(token) => Ok(token.clone()), + Err(_) => Err(()), + }); + match peeked { + Ok(token) => tokens.push(token), + Err(()) => break, + } + } + family_from_tokens(&tokens) +} + +/// 把族名的 token 序列归一化为 [`FontFamilyValue`]:去首尾空白、中部空白 +/// 折叠为单个空格;无引号的单词族名映射 generic。 +fn family_from_tokens(tokens: &[Token<'_>]) -> Result<FontFamilyValue, ()> { + let mut parts: Vec<String> = Vec::new(); + let mut current: Option<String> = None; + let mut quoted = false; + for token in tokens { + match token { + Token::WhiteSpace(_) => { + if let Some(word) = current.take() { + parts.push(word); + } + } + Token::Ident(name) => { + current.get_or_insert_with(String::new).push_str(name); + } + Token::QuotedString(text) => { + if current.is_some() || !parts.is_empty() { + // 字符串只能单独成族名(CSS Fonts 4 §2.3 语法) + return Err(()); + } + quoted = true; + parts.push(text.to_string()); + } + _ => return Err(()), + } + } + if let Some(word) = current.take() { + parts.push(word); + } + + if parts.is_empty() { + return Err(()); + } + // 带引号的 "serif" 是名为 serif 的普通族名,不映射 generic + if parts.len() == 1 + && !quoted + && let Some(generic) = generic_family(&parts[0]) + { + return Ok(FontFamilyValue::Generic(generic)); + } + Ok(FontFamilyValue::Family(parts.join(" "))) +} + +/// `font` 简写值解析并展开为 longhand(CSS Fonts 4 §3.3)。 +/// +/// 语法:`[ <'font-style'> || <font-variant-css2> || <'font-weight'> || +/// <font-width-css3> ]? <'font-size'> [ / <'line-height'> ]? <'font-family'>#`—— +/// `||` 成分任意顺序、每项至多一次;缺省成分按简写语义重置为 initial。 +/// 偏差:`font-variant-css2`(`small-caps`)与 `<font-width-css3>`(宽度 +/// 关键字/百分比)无对应 longhand,按语法接受后丢弃;系统字体关键字 +/// (`caption` 等)整条无效。 +pub(crate) fn parse_font_shorthand( + input: &mut Parser<'_>, +) -> Result<Vec<(PropertyId, PropertyValue)>, ()> { + if is_system_family_name(input) { + return Err(()); + } + let mut style: Option<FontStyleValue> = None; + let mut weight: Option<FontWeightValue> = None; + let mut small_caps_seen = false; + let mut width_seen = false; + // `normal` 可出现在 style / variant / weight / width 四个槽位,统一计数 + // (各槽初值均为 normal,无需区分归属)。 + let mut normals = 0usize; + loop { + if normals < 4 && try_parse_ident(input, "normal") { + normals += 1; + continue; + } + if style.is_none() + && let Ok(value) = input.try_parse(parse_font_style_shorthand) + { + style = Some(value); + continue; + } + if weight.is_none() + && let Ok(value) = input.try_parse(parse_font_weight) + { + weight = Some(value); + continue; + } + if !small_caps_seen && try_parse_ident(input, "small-caps") { + small_caps_seen = true; + continue; + } + if !width_seen && try_parse_font_width(input) { + width_seen = true; + continue; + } + break; + } + + let size = parse_font_size(input)?; + let line_height = if input.try_parse(|i| i.expect_delim('/')).is_ok() { + Some(parse_line_height(input)?) + } else { + None + }; + let families = parse_font_family(input)?; + + Ok(vec![ + ( + PropertyId::FontStyle, + PropertyValue::FontStyle(style.unwrap_or(FontStyleValue::Normal)), + ), + ( + PropertyId::FontWeight, + PropertyValue::FontWeight(weight.unwrap_or(FontWeightValue::Weight(400.0))), + ), + (PropertyId::FontSize, PropertyValue::FontSize(size)), + ( + PropertyId::LineHeight, + PropertyValue::LineHeight(line_height.unwrap_or(LineHeightValue::Normal)), + ), + (PropertyId::FontFamily, PropertyValue::FontFamily(families)), + ]) +} + +/// 简写前缀里的 `<font-style>`:`italic | oblique [ <angle> | none ]?`。 +/// 与 longhand [`parse_font_style`] 的差别:裸 `oblique` 合法——简写中 +/// 其后还有 size 等成分,不能要求耗尽。 +fn parse_font_style_shorthand(input: &mut Parser<'_>) -> Result<FontStyleValue, ()> { + let Token::Ident(name) = input.next().map_err(|_| ())? else { + return Err(()); + }; + if name.eq_ignore_ascii_case("italic") { + return Ok(FontStyleValue::Italic); + } + if name.eq_ignore_ascii_case("oblique") { + let angle = input.try_parse(parse_angle).ok(); + if angle.is_none() + && input + .try_parse(|i| i.expect_ident_matching("none").map_err(|_| ())) + .is_ok() + { + return Ok(FontStyleValue::Oblique(None)); + } + return Ok(FontStyleValue::Oblique(angle)); + } + Err(()) +} + +/// `font` 简写的系统字体关键字(CSS Fonts 4 §3.3 `<system-family-name>`): +/// 依赖 UA 系统设置且要求重置全部子属性,本层不支持。 +fn is_system_family_name(input: &mut Parser<'_>) -> bool { + const SYSTEM: [&str; 6] = [ + "caption", + "icon", + "menu", + "message-box", + "small-caption", + "status-bar", + ]; + input + .try_parse(|i| match i.next() { + Ok(Token::Ident(name)) if SYSTEM.iter().any(|k| name.eq_ignore_ascii_case(k)) => Ok(()), + _ => Err(()), + }) + .is_ok() +} + +/// 尝试消费一个指定关键字(ASCII case-insensitive),命中则消费并返回真。 +fn try_parse_ident(input: &mut Parser<'_>, expected: &str) -> bool { + input + .try_parse(|i| match i.next() { + Ok(Token::Ident(name)) if name.eq_ignore_ascii_case(expected) => Ok(()), + _ => Err(()), + }) + .is_ok() +} + +/// `<font-width-css3>`:宽度关键字或非负百分比。本层无 font-stretch +/// longhand,按语法接受后丢弃(返回是否命中)。 +fn try_parse_font_width(input: &mut Parser<'_>) -> bool { + const KEYWORDS: [&str; 8] = [ + "ultra-condensed", + "extra-condensed", + "condensed", + "semi-condensed", + "semi-expanded", + "expanded", + "extra-expanded", + "ultra-expanded", + ]; + input + .try_parse(|i| match i.next() { + Ok(Token::Ident(name)) if KEYWORDS.iter().any(|k| name.eq_ignore_ascii_case(k)) => { + Ok(()) + } + Ok(Token::Percentage { unit_value, .. }) if *unit_value >= 0.0 => Ok(()), + _ => Err(()), + }) + .is_ok() +} + +/// 无引号的 generic 族关键字 +/// (CSS Fonts 4 §2.3:serif、sans-serif、cursive、fantasy、monospace、 +/// system-ui、math、emoji、fangsong、ui-serif、ui-sans-serif、ui-monospace、 +/// ui-rounded)。 +fn generic_family(name: &str) -> Option<&'static str> { + const GENERICS: [&str; 13] = [ + "serif", + "sans-serif", + "cursive", + "fantasy", + "monospace", + "system-ui", + "math", + "emoji", + "fangsong", + "ui-serif", + "ui-sans-serif", + "ui-monospace", + "ui-rounded", + ]; + GENERICS + .into_iter() + .find(|generic| generic.eq_ignore_ascii_case(name)) +} + +/// 解析 `<color>`([CSS Color 4 §5](https://drafts.csswg.org/css-color-4/#color-syntax)): +/// hex、`rgb()` / `rgba()`、`hsl()` / `hsla()`(现代与 legacy 逗号语法)、 +/// 命名色与 `transparent`。 +pub(crate) fn parse_color(input: &mut Parser<'_>) -> Result<Rgba, ()> { + let token = input.next().map_err(|_| ())?; + match token { + // `#fff` 这类合法标识符形式的 hash 会词法为 IDHash,与 Hash 同义 + Token::Hash(hash) | Token::IDHash(hash) => parse_hex(hash), + Token::Ident(name) => { + if name.eq_ignore_ascii_case("transparent") { + Ok(Rgba::transparent()) + } else if name.eq_ignore_ascii_case("currentcolor") { + // 依赖元素上下文,本轮不支持(见模块文档偏差) + Err(()) + } else { + named_color(name).ok_or(()) + } + } + Token::Function(name) => { + if name.eq_ignore_ascii_case("rgb") || name.eq_ignore_ascii_case("rgba") { + input + .parse_nested_block(|input| { + parse_rgb_arguments(input).map_err(|_| ParseError::<()>::unexpected_token()) + }) + .map_err(|_| ()) + } else if name.eq_ignore_ascii_case("hsl") || name.eq_ignore_ascii_case("hsla") { + input + .parse_nested_block(|input| { + parse_hsl_arguments(input).map_err(|_| ParseError::<()>::unexpected_token()) + }) + .map_err(|_| ()) + } else { + Err(()) + } + } + _ => Err(()), + } +} + +/// CSS Color 4 §6.1 命名色表(148 项,由规范表格生成)。 +const NAMED_COLORS: [(&str, u8, u8, u8); 148] = [ + ("aliceblue", 0xf0, 0xf8, 0xff), + ("antiquewhite", 0xfa, 0xeb, 0xd7), + ("aqua", 0x00, 0xff, 0xff), + ("aquamarine", 0x7f, 0xff, 0xd4), + ("azure", 0xf0, 0xff, 0xff), + ("beige", 0xf5, 0xf5, 0xdc), + ("bisque", 0xff, 0xe4, 0xc4), + ("black", 0x00, 0x00, 0x00), + ("blanchedalmond", 0xff, 0xeb, 0xcd), + ("blue", 0x00, 0x00, 0xff), + ("blueviolet", 0x8a, 0x2b, 0xe2), + ("brown", 0xa5, 0x2a, 0x2a), + ("burlywood", 0xde, 0xb8, 0x87), + ("cadetblue", 0x5f, 0x9e, 0xa0), + ("chartreuse", 0x7c, 0xfc, 0x00), + ("chocolate", 0xd2, 0x69, 0x1e), + ("coral", 0xff, 0x7f, 0x50), + ("cornflowerblue", 0x64, 0x95, 0xed), + ("cornsilk", 0xff, 0xf8, 0xdc), + ("crimson", 0xdc, 0x14, 0x3c), + ("cyan", 0x00, 0xff, 0xff), + ("darkblue", 0x00, 0x00, 0x8b), + ("darkcyan", 0x00, 0x8b, 0x8b), + ("darkgoldenrod", 0xb8, 0x86, 0x0b), + ("darkgray", 0xa9, 0xa9, 0xa9), + ("darkgreen", 0x00, 0x80, 0x00), + ("darkgrey", 0xa9, 0xa9, 0xa9), + ("darkkhaki", 0xbd, 0xb7, 0x6b), + ("darkmagenta", 0x8b, 0x00, 0x8b), + ("darkolivegreen", 0x55, 0x6b, 0x2f), + ("darkorange", 0xff, 0x8c, 0x00), + ("darkorchid", 0x99, 0x32, 0xcc), + ("darkred", 0x8b, 0x00, 0x00), + ("darksalmon", 0xe9, 0x96, 0x7a), + ("darkseagreen", 0x8f, 0xbc, 0x8f), + ("darkslateblue", 0x48, 0x3d, 0x8b), + ("darkslategray", 0x2f, 0x4f, 0x4f), + ("darkslategrey", 0x2f, 0x4f, 0x4f), + ("darkturquoise", 0x00, 0xce, 0xd1), + ("darkviolet", 0x94, 0x00, 0xd3), + ("deeppink", 0xff, 0x14, 0x93), + ("deepskyblue", 0x00, 0xbf, 0xff), + ("dimgray", 0x69, 0x69, 0x69), + ("dimgrey", 0x69, 0x69, 0x69), + ("dodgerblue", 0x1e, 0x90, 0xff), + ("firebrick", 0xb2, 0x22, 0x22), + ("floralwhite", 0xff, 0xfa, 0xf0), + ("forestgreen", 0x22, 0x8b, 0x22), + ("fuchsia", 0xff, 0x00, 0xff), + ("gainsboro", 0xdc, 0xdc, 0xdc), + ("ghostwhite", 0xf8, 0xf8, 0xff), + ("gold", 0xff, 0xd7, 0x00), + ("goldenrod", 0xda, 0xa5, 0x20), + ("gray", 0x80, 0x80, 0x80), + ("green", 0x00, 0x80, 0x00), + ("greenyellow", 0xad, 0xff, 0x2f), + ("grey", 0x80, 0x80, 0x80), + ("honeydew", 0xf0, 0xff, 0xf0), + ("hotpink", 0xff, 0x69, 0xb4), + ("indianred", 0xcd, 0x5c, 0x5c), + ("indigo", 0x4b, 0x00, 0x82), + ("ivory", 0xff, 0xff, 0xf0), + ("khaki", 0xf0, 0xe6, 0x8c), + ("lavender", 0xe6, 0xe6, 0xfa), + ("lavenderblush", 0xff, 0xf0, 0xf5), + ("lawngreen", 0x7c, 0xfc, 0x00), + ("lemonchiffon", 0xff, 0xfa, 0xcd), + ("lightblue", 0xad, 0xd8, 0xe6), + ("lightcoral", 0xf0, 0x80, 0x80), + ("lightcyan", 0xe0, 0xff, 0xff), + ("lightgoldenrodyellow", 0xfa, 0xfa, 0xd2), + ("lightgray", 0xd3, 0xd3, 0xd3), + ("lightgreen", 0x90, 0xee, 0x90), + ("lightgrey", 0xd3, 0xd3, 0xd3), + ("lightpink", 0xff, 0xb6, 0xc1), + ("lightsalmon", 0xff, 0xa0, 0x7a), + ("lightseagreen", 0x20, 0xb2, 0xaa), + ("lightskyblue", 0x87, 0xce, 0xfa), + ("lightslategray", 0x77, 0x88, 0x99), + ("lightslategrey", 0x77, 0x88, 0x99), + ("lightsteelblue", 0xb0, 0xc4, 0xde), + ("lightyellow", 0xff, 0xff, 0xe0), + ("lime", 0x00, 0xff, 0x00), + ("limegreen", 0x32, 0xcd, 0x32), + ("linen", 0xfa, 0xf0, 0xe6), + ("magenta", 0xff, 0x00, 0xff), + ("maroon", 0x80, 0x00, 0x00), + ("mediumaquamarine", 0x66, 0xcd, 0xaa), + ("mediumblue", 0x00, 0x00, 0xcd), + ("mediumorchid", 0xba, 0x55, 0xd3), + ("mediumpurple", 0x93, 0x70, 0xdb), + ("mediumseagreen", 0x3c, 0xb3, 0x71), + ("mediumslateblue", 0x7b, 0x68, 0xee), + ("mediumspringgreen", 0x00, 0xfa, 0x9a), + ("mediumturquoise", 0x48, 0xd1, 0xcc), + ("mediumvioletred", 0xc7, 0x15, 0x85), + ("midnightblue", 0x19, 0x19, 0x70), + ("mintcream", 0xf5, 0xff, 0xfa), + ("mistyrose", 0xff, 0xe4, 0xe1), + ("moccasin", 0xff, 0xe4, 0xb5), + ("navajowhite", 0xff, 0xde, 0xad), + ("navy", 0x00, 0x00, 0x80), + ("oldlace", 0xfd, 0xf5, 0xe6), + ("olive", 0x80, 0x80, 0x00), + ("olivedrab", 0x6b, 0x8e, 0x23), + ("orange", 0xff, 0xa5, 0x00), + ("orangered", 0xff, 0x45, 0x00), + ("orchid", 0xda, 0x70, 0xd6), + ("palegoldenrod", 0xee, 0xe8, 0xaa), + ("palegreen", 0x98, 0xfb, 0x98), + ("paleturquoise", 0xaf, 0xee, 0xee), + ("palevioletred", 0xdb, 0x70, 0x93), + ("papayawhip", 0xff, 0xef, 0xd5), + ("peachpuff", 0xff, 0xda, 0xb9), + ("peru", 0xcd, 0x85, 0x3f), + ("pink", 0xff, 0xc0, 0xcb), + ("plum", 0xdd, 0xa0, 0xdd), + ("powderblue", 0xb0, 0xe0, 0xe6), + ("purple", 0x80, 0x00, 0x80), + ("rebeccapurple", 0x66, 0x33, 0x99), + ("red", 0xff, 0x00, 0x00), + ("rosybrown", 0xbc, 0x8f, 0x8f), + ("royalblue", 0x41, 0x69, 0xe1), + ("saddlebrown", 0x8b, 0x45, 0x13), + ("salmon", 0xfa, 0x80, 0x72), + ("sandybrown", 0xf4, 0xa4, 0x60), + ("seagreen", 0x2e, 0x8b, 0x57), + ("seashell", 0xff, 0xf5, 0xee), + ("sienna", 0xa0, 0x52, 0x2d), + ("silver", 0xc0, 0xc0, 0xc0), + ("skyblue", 0x87, 0xce, 0xeb), + ("slateblue", 0x6a, 0x5a, 0xcd), + ("slategray", 0x70, 0x80, 0x90), + ("slategrey", 0x70, 0x80, 0x90), + ("snow", 0xff, 0xfa, 0xfa), + ("springgreen", 0x00, 0xff, 0x7f), + ("steelblue", 0x46, 0x82, 0xb4), + ("tan", 0xd2, 0xb4, 0x8c), + ("teal", 0x00, 0x80, 0x80), + ("thistle", 0xd8, 0xbf, 0xd8), + ("tomato", 0xff, 0x63, 0x47), + ("turquoise", 0x40, 0xe0, 0xd0), + ("violet", 0xee, 0x82, 0xee), + ("wheat", 0xf5, 0xde, 0xb3), + ("white", 0xff, 0xff, 0xff), + ("whitesmoke", 0xf5, 0xf5, 0xf5), + ("yellow", 0xff, 0xff, 0x00), + ("yellowgreen", 0x9a, 0xcd, 0x32), +]; + +fn named_color(name: &str) -> Option<Rgba> { + NAMED_COLORS + .iter() + .find(|(keyword, ..)| keyword.eq_ignore_ascii_case(name)) + .map(|&(_, r, g, b)| Rgba::opaque(r, g, b)) +} + +/// hex 记法:`#rgb` `#rgba` `#rrggbb` `#rrggbbaa`(CSS Color 4 §5.2)。 +fn parse_hex(hash: &str) -> Result<Rgba, ()> { + fn hex_digit(c: u8) -> Option<u8> { + match c { + b'0'..=b'9' => Some(c - b'0'), + b'a'..=b'f' => Some(c - b'a' + 10), + b'A'..=b'F' => Some(c - b'A' + 10), + _ => None, + } + } + let bytes = hash.as_bytes(); + let parse_pair = |slice: &[u8]| -> Option<u8> { + Some(hex_digit(*slice.first()?)? * 16 + hex_digit(*slice.get(1)?)?) + }; + match bytes.len() { + 3 => { + let digits: Option<Vec<u8>> = bytes.iter().map(|&c| hex_digit(c)).collect(); + let d = digits.ok_or(())?; + Ok(Rgba::opaque(d[0] * 17, d[1] * 17, d[2] * 17)) + } + 4 => { + let digits: Option<Vec<u8>> = bytes.iter().map(|&c| hex_digit(c)).collect(); + let d = digits.ok_or(())?; + Ok(Rgba { + r: d[0] * 17, + g: d[1] * 17, + b: d[2] * 17, + a: d[3] * 17, + }) + } + 6 => Ok(Rgba::opaque( + parse_pair(&bytes[0..2]).ok_or(())?, + parse_pair(&bytes[2..4]).ok_or(())?, + parse_pair(&bytes[4..6]).ok_or(())?, + )), + 8 => Ok(Rgba { + r: parse_pair(&bytes[0..2]).ok_or(())?, + g: parse_pair(&bytes[2..4]).ok_or(())?, + b: parse_pair(&bytes[4..6]).ok_or(())?, + a: parse_pair(&bytes[6..8]).ok_or(())?, + }), + _ => Err(()), + } +} + +/// 颜色分量:数字或百分比,可选 `none` 视为本轮不支持。 +enum Component { + Number(f32), + Percentage(f32), +} + +fn parse_component(input: &mut Parser<'_>) -> Result<Component, ()> { + match input.next().map_err(|_| ())? { + Token::Number { value, .. } => Ok(Component::Number(*value)), + Token::Percentage { unit_value, .. } => Ok(Component::Percentage(*unit_value * 100.0)), + _ => Err(()), + } +} + +/// alpha 分量:数字(0–1)或百分比(0–100%)。 +fn parse_alpha(input: &mut Parser<'_>) -> Result<f32, ()> { + let component = parse_component(input)?; + Ok(match component { + Component::Number(value) => value, + Component::Percentage(value) => value / 100.0, + }) +} + +/// 分量 → 8bit 通道:数字按 0–255、百分比按 0–100% 折算后 clamp 并四舍五入 +/// (CSS Color 4:rgb() 分量超出范围时 clamp 到设备无关 0–255)。 +fn component_to_byte(component: Component) -> u8 { + let raw = match component { + Component::Number(value) => value, + Component::Percentage(value) => value * 255.0 / 100.0, + }; + raw.clamp(0.0, 255.0).round() as u8 +} + +/// rgb() / rgba() 的参数:现代空白语法(可带 `/ alpha`)与 legacy 逗号语法 +/// (CSS Color 4 §5.3)。 +fn parse_rgb_arguments(input: &mut Parser<'_>) -> Result<Rgba, ()> { + let first = parse_component(input)?; + let comma = input.try_parse(Parser::expect_comma).is_ok(); + + let (red, green, blue, alpha) = if comma { + let green = parse_component(input)?; + input.expect_comma().map_err(|_| ())?; + let blue = parse_component(input)?; + let alpha = if input.try_parse(Parser::expect_comma).is_ok() { + parse_alpha(input)? + } else { + 1.0 + }; + (first, green, blue, alpha) + } else { + let green = parse_component(input)?; + let blue = parse_component(input)?; + let alpha = if input.try_parse(|i| i.expect_delim('/')).is_ok() { + parse_alpha(input)? + } else { + 1.0 + }; + (first, green, blue, alpha) + }; + + if input.expect_exhausted().is_err() { + return Err(()); + } + Ok(Rgba { + r: component_to_byte(red), + g: component_to_byte(green), + b: component_to_byte(blue), + a: (alpha.clamp(0.0, 1.0) * 255.0).round() as u8, + }) +} + +/// hsl() / hsla() 的参数(CSS Color 4 §7)。 +fn parse_hsl_arguments(input: &mut Parser<'_>) -> Result<Rgba, ()> { + let hue = parse_hue(input)?; + let comma = input.try_parse(Parser::expect_comma).is_ok(); + let (saturation, lightness, alpha) = if comma { + let saturation = parse_percentage(input)?; + input.expect_comma().map_err(|_| ())?; + let lightness = parse_percentage(input)?; + let alpha = if input.try_parse(Parser::expect_comma).is_ok() { + parse_alpha(input)? + } else { + 1.0 + }; + (saturation, lightness, alpha) + } else { + let saturation = parse_percentage(input)?; + let lightness = parse_percentage(input)?; + let alpha = if input.try_parse(|i| i.expect_delim('/')).is_ok() { + parse_alpha(input)? + } else { + 1.0 + }; + (saturation, lightness, alpha) + }; + if input.expect_exhausted().is_err() { + return Err(()); + } + Ok(hsl_to_rgb( + hue, + saturation / 100.0, + lightness / 100.0, + alpha, + )) +} + +/// `<hue>`:裸数字(度)或角度 dimension。 +fn parse_hue(input: &mut Parser<'_>) -> Result<f32, ()> { + match input.next().map_err(|_| ())? { + Token::Number { value, .. } => Ok(*value), + Token::Dimension { value, unit, .. } => { + if unit.eq_ignore_ascii_case("deg") { + Ok(*value) + } else if unit.eq_ignore_ascii_case("grad") { + Ok(*value * 360.0 / 400.0) + } else if unit.eq_ignore_ascii_case("rad") { + Ok(value.to_degrees()) + } else if unit.eq_ignore_ascii_case("turn") { + Ok(*value * 360.0) + } else { + Err(()) + } + } + _ => Err(()), + } +} + +/// 百分比的数值(`50%` → `50.0`),与 [`Component::Percentage`] 一致。 +fn parse_percentage(input: &mut Parser<'_>) -> Result<f32, ()> { + match input.next().map_err(|_| ())? { + Token::Percentage { unit_value, .. } => Ok(*unit_value * 100.0), + _ => Err(()), + } +} + +/// HSL → sRGB(CSS Color 4 §7.1 的转换算法)。 +fn hsl_to_rgb(hue: f32, saturation: f32, lightness: f32, alpha: f32) -> Rgba { + let t2 = if lightness <= 0.5 { + lightness * (1.0 + saturation) + } else { + lightness + saturation - lightness * saturation + }; + let t1 = 2.0 * lightness - t2; + let channel = |offset: f32| -> u8 { + let h = (hue.rem_euclid(360.0) + offset).rem_euclid(360.0); + let value = if h < 60.0 { + t1 + (t2 - t1) * h / 60.0 + } else if h < 180.0 { + t2 + } else if h < 240.0 { + t1 + (t2 - t1) * (240.0 - h) / 60.0 + } else { + t1 + }; + (value.clamp(0.0, 1.0) * 255.0).round() as u8 + }; + Rgba { + r: channel(120.0), + g: channel(0.0), + b: channel(-120.0), + a: (alpha.clamp(0.0, 1.0) * 255.0).round() as u8, + } +} + +#[allow(clippy::too_many_lines)] +#[cfg(test)] +mod tests { + use super::*; + + /// 单值解析入口:解析整段文本后要求耗尽。 + fn parse_typed(property: PropertyId, text: &str) -> Result<PropertyValue, ()> { + let mut parser = Parser::new(text); + let value = parse_property_value(property, &mut parser)?; + parser.expect_exhausted().map_err(|_| ())?; + Ok(value) + } + + fn parse_one(property: PropertyId, text: &str) -> PropertyValue { + parse_typed(property, text).expect("value should parse") + } + + fn parse_err(property: PropertyId, text: &str) { + assert!( + parse_typed(property, text).is_err(), + "{text} should not parse" + ); + } + + #[test] + fn position_inset_flex_grid_properties_parse() { + use PropertyValue::{ + AlignItems, AlignSelf, FlexDirection, FlexShrink, FlexWrap, Gap, GridAutoFlow, + GridTrack as GridTrackValue, Inset, JustifyContent, Position, + }; + // position + assert_eq!( + parse_one(PropertyId::Position, "absolute"), + Position(PositionValue::Absolute) + ); + assert_eq!( + parse_one(PropertyId::Position, "FIXED"), + Position(PositionValue::Fixed) + ); + parse_err(PropertyId::Position, "sticky"); + + // inset(四边 longhand 共用 InsetValue) + assert_eq!( + parse_one(PropertyId::Top, "10px"), + Inset(InsetValue::Length(10.0)) + ); + assert_eq!( + parse_one(PropertyId::Left, "50%"), + Inset(InsetValue::Percent(0.5)) + ); + assert_eq!( + parse_one(PropertyId::Bottom, "auto"), + Inset(InsetValue::Auto) + ); + + // flex-direction / flex-wrap / flex-shrink + assert_eq!( + parse_one(PropertyId::FlexDirection, "column"), + FlexDirection(FlexDirectionValue::Column) + ); + assert_eq!( + parse_one(PropertyId::FlexWrap, "wrap-reverse"), + FlexWrap(FlexWrapValue::WrapReverse) + ); + assert_eq!(parse_one(PropertyId::FlexShrink, "2"), FlexShrink(2.0)); + parse_err(PropertyId::FlexShrink, "-1"); + + // align-items / justify-content / align-self(兼容 start/end) + assert_eq!( + parse_one(PropertyId::AlignItems, "center"), + AlignItems(AlignItemsValue::Center) + ); + assert_eq!( + parse_one(PropertyId::AlignItems, "start"), + AlignItems(AlignItemsValue::FlexStart) + ); + assert_eq!( + parse_one(PropertyId::JustifyContent, "space-between"), + JustifyContent(JustifyContentValue::SpaceBetween) + ); + assert_eq!( + parse_one(PropertyId::AlignSelf, "auto"), + AlignSelf(AlignSelfValue::Auto) + ); + + // gap(auto 非法) + assert_eq!( + parse_one(PropertyId::RowGap, "8px"), + Gap(GapValue::Length(8.0)) + ); + assert_eq!( + parse_one(PropertyId::ColumnGap, "normal"), + Gap(GapValue::Normal) + ); + parse_err(PropertyId::RowGap, "auto"); + + // grid-auto-flow(可选 dense 后缀) + assert_eq!( + parse_one(PropertyId::GridAutoFlow, "row dense"), + GridAutoFlow(GridAutoFlowValue::RowDense) + ); + assert_eq!( + parse_one(PropertyId::GridAutoFlow, "column"), + GridAutoFlow(GridAutoFlowValue::Column) + ); + + // grid 轨道列表(含 minmax 与 fr) + assert_eq!( + parse_one(PropertyId::GridTemplateColumns, "100px 1fr auto"), + GridTrackValue(GridTrackList { + tracks: vec![ + GridTrack::Length(100.0), + GridTrack::Fr(1.0), + GridTrack::Auto, + ] + }) + ); + assert_eq!( + parse_one(PropertyId::GridTemplateRows, "minmax(50px, 1fr)"), + GridTrackValue(GridTrackList { + tracks: vec![GridTrack::MinMax( + Box::new(GridTrack::Length(50.0)), + Box::new(GridTrack::Fr(1.0)), + )] + }) + ); + // 无空白分隔 / 未知轨道关键字 → 整条声明无效 + parse_err(PropertyId::GridTemplateColumns, "100px2px"); + parse_err(PropertyId::GridTemplateColumns, "auto bogus"); + // gridshorthand:gap 两值、inset 四值 + } + + #[test] + fn gap_and_inset_shorthands_expand() { + let sheet = + crate::parser::Stylesheet::parse("div { gap: 10px 20px; inset: 1px 2px 3px 4px; }"); + let declarations = &sheet.rules()[0].declarations(); + assert_eq!(declarations.len(), 6); + let get = |property: PropertyId| { + declarations + .iter() + .find(|d| d.property == property) + .map(|d| &d.value) + }; + assert_eq!( + get(PropertyId::RowGap), + Some(&DeclaredValue::Typed(PropertyValue::Gap(GapValue::Length( + 10.0 + )))) + ); + assert_eq!( + get(PropertyId::ColumnGap), + Some(&DeclaredValue::Typed(PropertyValue::Gap(GapValue::Length( + 20.0 + )))) + ); + assert_eq!( + get(PropertyId::Top), + Some(&DeclaredValue::Typed(PropertyValue::Inset( + InsetValue::Length(1.0) + ))) + ); + assert_eq!( + get(PropertyId::Left), + Some(&DeclaredValue::Typed(PropertyValue::Inset( + InsetValue::Length(4.0) + ))) + ); + } + + #[test] + fn property_id_lookup_is_ascii_case_insensitive() { + assert_eq!( + PropertyId::from_name("FONT-SIZE"), + Some(PropertyId::FontSize) + ); + assert_eq!(PropertyId::from_name("color"), Some(PropertyId::Color)); + assert_eq!(PropertyId::from_name("grid-area"), None); + assert_eq!(PropertyId::FontSize.as_str(), "font-size"); + } + + #[test] + fn box_sizing_overflow_and_min_max_parse() { + assert_eq!( + parse_one(PropertyId::BoxSizing, "border-box"), + PropertyValue::BoxSizing(BoxSizingValue::BorderBox) + ); + assert_eq!( + parse_one(PropertyId::BoxSizing, "CONTENT-BOX"), + PropertyValue::BoxSizing(BoxSizingValue::ContentBox) + ); + parse_err(PropertyId::BoxSizing, "padding-box"); + + assert_eq!( + parse_one(PropertyId::Overflow, "hidden"), + PropertyValue::Overflow(OverflowValue::Hidden) + ); + assert_eq!( + parse_one(PropertyId::Overflow, "visible"), + PropertyValue::Overflow(OverflowValue::Visible) + ); + // 偏差:auto/scroll/clip 暂不建模,按无效声明丢弃 + parse_err(PropertyId::Overflow, "auto"); + parse_err(PropertyId::Overflow, "scroll"); + parse_err(PropertyId::Overflow, "clip"); + + assert_eq!( + parse_one(PropertyId::MinWidth, "40px"), + PropertyValue::Size(SizeValue::Length(40.0)) + ); + assert_eq!( + parse_one(PropertyId::MaxWidth, "50%"), + PropertyValue::Size(SizeValue::Percent(0.5)) + ); + assert_eq!( + parse_one(PropertyId::MinHeight, "auto"), + PropertyValue::Size(SizeValue::Auto) + ); + assert_eq!( + parse_one(PropertyId::MaxHeight, "0"), + PropertyValue::Size(SizeValue::Length(0.0)) + ); + // 负尺寸非法 + parse_err(PropertyId::MaxWidth, "-10px"); + } + + #[test] + fn color_hex_forms() { + assert_eq!( + parse_one(PropertyId::Color, "#fff"), + PropertyValue::Color(Rgba::opaque(255, 255, 255)) + ); + assert_eq!( + parse_one(PropertyId::Color, "#0000"), + PropertyValue::Color(Rgba { + r: 0, + g: 0, + b: 0, + a: 0 + }) + ); + assert_eq!( + parse_one(PropertyId::Color, "#336699"), + PropertyValue::Color(Rgba::opaque(0x33, 0x66, 0x99)) + ); + assert_eq!( + parse_one(PropertyId::Color, "#33669980"), + PropertyValue::Color(Rgba { + r: 0x33, + g: 0x66, + b: 0x99, + a: 0x80 + }) + ); + parse_err(PropertyId::Color, "#ff"); + parse_err(PropertyId::Color, "#ffggzz"); + } + + #[test] + fn color_named_and_transparent() { + assert_eq!( + parse_one(PropertyId::Color, "rebeccapurple"), + PropertyValue::Color(Rgba::opaque(0x66, 0x33, 0x99)) + ); + assert_eq!( + parse_one(PropertyId::Color, "BLACK"), + PropertyValue::Color(Rgba::opaque(0, 0, 0)) + ); + assert_eq!( + parse_one(PropertyId::Color, "transparent"), + PropertyValue::Color(Rgba::transparent()) + ); + parse_err(PropertyId::Color, "notacolor"); + parse_err(PropertyId::Color, "currentcolor"); + } + + #[test] + fn color_rgb_legacy_and_modern() { + assert_eq!( + parse_one(PropertyId::Color, "rgb(255, 0, 128)"), + PropertyValue::Color(Rgba::opaque(255, 0, 128)) + ); + assert_eq!( + parse_one(PropertyId::Color, "rgba(255, 0, 128, 0.5)"), + PropertyValue::Color(Rgba { + r: 255, + g: 0, + b: 128, + a: 128 + }) + ); + assert_eq!( + parse_one(PropertyId::Color, "rgb(255 0 128)"), + PropertyValue::Color(Rgba::opaque(255, 0, 128)) + ); + assert_eq!( + parse_one(PropertyId::Color, "rgb(255 0 128 / 50%)"), + PropertyValue::Color(Rgba { + r: 255, + g: 0, + b: 128, + a: 128 + }) + ); + assert_eq!( + parse_one(PropertyId::Color, "rgb(50% 0% 100%)"), + PropertyValue::Color(Rgba::opaque(128, 0, 255)) + ); + // 超范围 clamp(CSS Color 4) + assert_eq!( + parse_one(PropertyId::Color, "rgb(-20 300 128)"), + PropertyValue::Color(Rgba::opaque(0, 255, 128)) + ); + parse_err(PropertyId::Color, "rgb(255 0)"); + parse_err(PropertyId::Color, "rgb(255, 0, 128 0.5)"); + } + + #[test] + fn color_hsl() { + assert_eq!( + parse_one(PropertyId::Color, "hsl(120, 100%, 50%)"), + PropertyValue::Color(Rgba::opaque(0, 255, 0)) + ); + assert_eq!( + parse_one(PropertyId::Color, "hsl(120 100% 50%)"), + PropertyValue::Color(Rgba::opaque(0, 255, 0)) + ); + assert_eq!( + parse_one(PropertyId::Color, "hsla(0, 0%, 0%, 0.5)"), + PropertyValue::Color(Rgba { + r: 0, + g: 0, + b: 0, + a: 128 + }) + ); + // 色相取模 + assert_eq!( + parse_one(PropertyId::Color, "hsl(480 100% 50%)"), + PropertyValue::Color(Rgba::opaque(0, 255, 0)) + ); + parse_err(PropertyId::Color, "hsl(120 50 50%)"); + } + + #[test] + fn font_size_forms() { + assert_eq!( + parse_one(PropertyId::FontSize, "16px"), + PropertyValue::FontSize(FontSizeValue::Px(16.0)) + ); + assert_eq!( + parse_one(PropertyId::FontSize, "12pt"), + PropertyValue::FontSize(FontSizeValue::Px(16.0)) + ); + assert_eq!( + parse_one(PropertyId::FontSize, "1.5em"), + PropertyValue::FontSize(FontSizeValue::Em(1.5)) + ); + assert_eq!( + parse_one(PropertyId::FontSize, "120%"), + PropertyValue::FontSize(FontSizeValue::Percent(1.2)) + ); + assert_eq!( + parse_one(PropertyId::FontSize, "0"), + PropertyValue::FontSize(FontSizeValue::Px(0.0)) + ); + assert_eq!( + parse_one(PropertyId::FontSize, "x-large"), + PropertyValue::FontSize(FontSizeValue::Absolute(AbsoluteSize::XLarge)) + ); + assert_eq!( + parse_one(PropertyId::FontSize, "larger"), + PropertyValue::FontSize(FontSizeValue::Larger) + ); + parse_err(PropertyId::FontSize, "16"); + parse_err(PropertyId::FontSize, "2rem"); + parse_err(PropertyId::FontSize, "medium small"); + } + + #[test] + fn absolute_size_table_matches_spec_factors() { + // CSS Fonts 4 §2.5.1 scaling factors + assert_eq!(AbsoluteSize::XxSmall.factor(), 0.6); + assert_eq!(AbsoluteSize::XSmall.factor(), 0.75); + assert_eq!(AbsoluteSize::Small.factor(), 8.0 / 9.0); + assert_eq!(AbsoluteSize::Medium.factor(), 1.0); + assert_eq!(AbsoluteSize::Large.factor(), 1.2); + assert_eq!(AbsoluteSize::XLarge.factor(), 1.5); + assert_eq!(AbsoluteSize::XxLarge.factor(), 2.0); + assert_eq!(AbsoluteSize::XxxLarge.factor(), 3.0); + } + + #[test] + fn font_weight_forms() { + assert_eq!( + parse_one(PropertyId::FontWeight, "400"), + PropertyValue::FontWeight(FontWeightValue::Weight(400.0)) + ); + assert_eq!( + parse_one(PropertyId::FontWeight, "normal"), + PropertyValue::FontWeight(FontWeightValue::Weight(400.0)) + ); + assert_eq!( + parse_one(PropertyId::FontWeight, "bold"), + PropertyValue::FontWeight(FontWeightValue::Weight(700.0)) + ); + assert_eq!( + parse_one(PropertyId::FontWeight, "bolder"), + PropertyValue::FontWeight(FontWeightValue::Bolder) + ); + parse_err(PropertyId::FontWeight, "0"); + parse_err(PropertyId::FontWeight, "1001"); + parse_err(PropertyId::FontWeight, "bold 700"); + } + + #[test] + fn font_family_forms() { + assert_eq!( + parse_one(PropertyId::FontFamily, "serif"), + PropertyValue::FontFamily(vec![FontFamilyValue::Generic("serif")]) + ); + assert_eq!( + parse_one(PropertyId::FontFamily, "SANS-SERIF"), + PropertyValue::FontFamily(vec![FontFamilyValue::Generic("sans-serif")]) + ); + // 带引号的 serif 是普通族名,不是 generic + assert_eq!( + parse_one(PropertyId::FontFamily, "\"serif\""), + PropertyValue::FontFamily(vec![FontFamilyValue::Family("serif".into())]) + ); + assert_eq!( + parse_one(PropertyId::FontFamily, "Times New Roman, Arial, sans-serif"), + PropertyValue::FontFamily(vec![ + FontFamilyValue::Family("Times New Roman".into()), + FontFamilyValue::Family("Arial".into()), + FontFamilyValue::Generic("sans-serif"), + ]) + ); + parse_err(PropertyId::FontFamily, ""); + parse_err(PropertyId::FontFamily, "Times \"New\" Roman"); + parse_err(PropertyId::FontFamily, "12px"); + } + + #[test] + fn keyword_properties() { + assert_eq!( + parse_one(PropertyId::Display, "none"), + PropertyValue::Display(DisplayValue::None) + ); + assert_eq!( + parse_one(PropertyId::Display, "FLEX"), + PropertyValue::Display(DisplayValue::Flex) + ); + assert_eq!( + parse_one(PropertyId::Display, "table-cell"), + PropertyValue::Display(DisplayValue::TableInternal("table-cell")) + ); + parse_err(PropertyId::Display, "ruby"); + parse_err(PropertyId::Display, "block flex"); + + assert_eq!( + parse_one(PropertyId::TextAlign, "center"), + PropertyValue::TextAlign(TextAlignValue::Center) + ); + assert_eq!( + parse_one(PropertyId::TextAlign, "match-parent"), + PropertyValue::TextAlign(TextAlignValue::MatchParent) + ); + parse_err(PropertyId::TextAlign, "middle"); + + assert_eq!( + parse_one(PropertyId::FontStyle, "italic"), + PropertyValue::FontStyle(FontStyleValue::Italic) + ); + assert_eq!( + parse_one(PropertyId::FontStyle, "oblique"), + PropertyValue::FontStyle(FontStyleValue::Oblique(None)) + ); + assert_eq!( + parse_one(PropertyId::FontStyle, "oblique 30deg"), + PropertyValue::FontStyle(FontStyleValue::Oblique(Some(30.0))) + ); + parse_err(PropertyId::FontStyle, "oblique 30px"); + } + + #[test] + fn flex_property_forms() { + // flex-grow:<number [0,∞]>(CSS Flexbox §7.1) + assert_eq!( + parse_one(PropertyId::FlexGrow, "2.5"), + PropertyValue::FlexGrow(2.5) + ); + assert_eq!( + parse_one(PropertyId::FlexGrow, "0"), + PropertyValue::FlexGrow(0.0) + ); + parse_err(PropertyId::FlexGrow, "-1"); + parse_err(PropertyId::FlexGrow, "auto"); + parse_err(PropertyId::FlexGrow, "1 2"); + + // flex-basis:auto | <length-percentage>(CSS Flexbox §7.2) + assert_eq!( + parse_one(PropertyId::FlexBasis, "auto"), + PropertyValue::FlexBasis(SizeValue::Auto) + ); + assert_eq!( + parse_one(PropertyId::FlexBasis, "0"), + PropertyValue::FlexBasis(SizeValue::Length(0.0)) + ); + assert_eq!( + parse_one(PropertyId::FlexBasis, "100px"), + PropertyValue::FlexBasis(SizeValue::Length(100.0)) + ); + assert_eq!( + parse_one(PropertyId::FlexBasis, "50%"), + PropertyValue::FlexBasis(SizeValue::Percent(0.5)) + ); + parse_err(PropertyId::FlexBasis, "-5px"); + parse_err(PropertyId::FlexBasis, "content"); + } + + #[test] + fn white_space_overflow_wrap_word_break_forms() { + // white-space:六个关键字(CSS Text 3 §3.1),大小写不敏感 + for (text, expected) in [ + ("normal", WhiteSpaceValue::Normal), + ("nowrap", WhiteSpaceValue::Nowrap), + ("pre", WhiteSpaceValue::Pre), + ("pre-wrap", WhiteSpaceValue::PreWrap), + ("PRE-LINE", WhiteSpaceValue::PreLine), + ("break-spaces", WhiteSpaceValue::BreakSpaces), + ] { + assert_eq!( + parse_one(PropertyId::WhiteSpace, text), + PropertyValue::WhiteSpace(expected) + ); + } + parse_err(PropertyId::WhiteSpace, "pre nowrap"); + parse_err(PropertyId::WhiteSpace, "pre-wrap-x"); + parse_err(PropertyId::WhiteSpace, ""); + + // overflow-wrap:normal | break-word | anywhere + assert_eq!( + parse_one(PropertyId::OverflowWrap, "normal"), + PropertyValue::OverflowWrap(OverflowWrapValue::Normal) + ); + assert_eq!( + parse_one(PropertyId::OverflowWrap, "break-word"), + PropertyValue::OverflowWrap(OverflowWrapValue::BreakWord) + ); + assert_eq!( + parse_one(PropertyId::OverflowWrap, "anywhere"), + PropertyValue::OverflowWrap(OverflowWrapValue::Anywhere) + ); + parse_err(PropertyId::OverflowWrap, "break-all"); + parse_err(PropertyId::OverflowWrap, "word-wrap"); + + // word-break:normal | break-all | keep-all + assert_eq!( + parse_one(PropertyId::WordBreak, "normal"), + PropertyValue::WordBreak(WordBreakValue::Normal) + ); + assert_eq!( + parse_one(PropertyId::WordBreak, "break-all"), + PropertyValue::WordBreak(WordBreakValue::BreakAll) + ); + assert_eq!( + parse_one(PropertyId::WordBreak, "keep-all"), + PropertyValue::WordBreak(WordBreakValue::KeepAll) + ); + parse_err(PropertyId::WordBreak, "break-word"); + parse_err(PropertyId::WordBreak, "keep"); + } + + /// CSS Text 3 的四个新属性:letter-spacing / word-spacing(§8)、 + /// text-indent(§4)、tab-size(§5)。 + #[test] + fn css_text_spacing_forms() { + // letter-spacing / word-spacing:normal | <length>(负值合法) + assert_eq!( + parse_one(PropertyId::LetterSpacing, "normal"), + PropertyValue::LetterSpacing(SpacingValue::Normal) + ); + assert_eq!( + parse_one(PropertyId::LetterSpacing, "4px"), + PropertyValue::LetterSpacing(SpacingValue::Length(4.0)) + ); + assert_eq!( + parse_one(PropertyId::LetterSpacing, "-2PX"), + PropertyValue::LetterSpacing(SpacingValue::Length(-2.0)) + ); + assert_eq!( + parse_one(PropertyId::LetterSpacing, "0.5em"), + PropertyValue::LetterSpacing(SpacingValue::Em(0.5)) + ); + assert_eq!( + parse_one(PropertyId::LetterSpacing, "0"), + PropertyValue::LetterSpacing(SpacingValue::Length(0.0)) + ); + parse_err(PropertyId::LetterSpacing, "10%"); + parse_err(PropertyId::LetterSpacing, "1vw"); + parse_err(PropertyId::LetterSpacing, "normal 4px"); + + assert_eq!( + parse_one(PropertyId::WordSpacing, "normal"), + PropertyValue::WordSpacing(SpacingValue::Normal) + ); + assert_eq!( + parse_one(PropertyId::WordSpacing, "-3px"), + PropertyValue::WordSpacing(SpacingValue::Length(-3.0)) + ); + assert_eq!( + parse_one(PropertyId::WordSpacing, "2em"), + PropertyValue::WordSpacing(SpacingValue::Em(2.0)) + ); + parse_err(PropertyId::WordSpacing, "20%"); + + // text-indent:<length-percentage>(负值合法) + assert_eq!( + parse_one(PropertyId::TextIndent, "40px"), + PropertyValue::TextIndent(TextIndentValue::Length(40.0)) + ); + assert_eq!( + parse_one(PropertyId::TextIndent, "10%"), + PropertyValue::TextIndent(TextIndentValue::Percent(0.1)) + ); + assert_eq!( + parse_one(PropertyId::TextIndent, "2em"), + PropertyValue::TextIndent(TextIndentValue::Em(2.0)) + ); + assert_eq!( + parse_one(PropertyId::TextIndent, "-10px"), + PropertyValue::TextIndent(TextIndentValue::Length(-10.0)) + ); + assert_eq!( + parse_one(PropertyId::TextIndent, "0"), + PropertyValue::TextIndent(TextIndentValue::Length(0.0)) + ); + parse_err(PropertyId::TextIndent, "auto"); + parse_err(PropertyId::TextIndent, "1vw"); + + // tab-size:<integer [0,∞]> | <length [0,∞]> + assert_eq!( + parse_one(PropertyId::TabSize, "4"), + PropertyValue::TabSize(TabSizeValue::Integer(4)) + ); + assert_eq!( + parse_one(PropertyId::TabSize, "0"), + PropertyValue::TabSize(TabSizeValue::Integer(0)) + ); + assert_eq!( + parse_one(PropertyId::TabSize, "32px"), + PropertyValue::TabSize(TabSizeValue::Length(32.0)) + ); + assert_eq!( + parse_one(PropertyId::TabSize, "2em"), + PropertyValue::TabSize(TabSizeValue::Em(2.0)) + ); + parse_err(PropertyId::TabSize, "-1"); + parse_err(PropertyId::TabSize, "8.5"); + parse_err(PropertyId::TabSize, "-4px"); + parse_err(PropertyId::TabSize, "10%"); + } + + #[test] + fn declared_value_css_wide_keywords() { + fn parse_declared(text: &str) -> Result<(DeclaredValue, bool), ()> { + let mut parser = Parser::new(text); + parse_declared_value(PropertyId::Color, &mut parser) + } + assert_eq!( + parse_declared("inherit"), + Ok((DeclaredValue::CssWide(CssWideKeyword::Inherit), false)) + ); + assert_eq!( + parse_declared("INITIAL !important"), + Ok((DeclaredValue::CssWide(CssWideKeyword::Initial), true)) + ); + assert_eq!( + parse_declared("unset"), + Ok((DeclaredValue::CssWide(CssWideKeyword::Unset), false)) + ); + assert_eq!( + parse_declared("revert"), + Ok((DeclaredValue::CssWide(CssWideKeyword::Revert), false)) + ); + // CSS-wide 关键字后不允许拼接其他值 + assert!(parse_declared("inherit red").is_err()); + assert_eq!( + parse_declared("#fff"), + Ok(( + DeclaredValue::Typed(PropertyValue::Color(Rgba::opaque(255, 255, 255))), + false + )) + ); + assert_eq!( + parse_declared("#fff !important"), + Ok(( + DeclaredValue::Typed(PropertyValue::Color(Rgba::opaque(255, 255, 255))), + true + )) + ); + assert!(parse_declared("#fff important").is_err()); + assert!(parse_declared("#fff ! bogus").is_err()); + } + + // ---- 数值卫生:巨数 token 与非有限值不进入值模型 ---- + + #[test] + fn length_boundary_at_max_is_kept_and_overflow_clamped() { + // 恰好 1e7 通过 + assert_eq!( + parse_one(PropertyId::Width, "10000000px"), + PropertyValue::Size(SizeValue::Length(MAX_CSS_LENGTH)) + ); + // 超限的有限值 clamp 到上限(UA clamp 偏差) + assert_eq!( + parse_one(PropertyId::Width, "10000001px"), + PropertyValue::Size(SizeValue::Length(MAX_CSS_LENGTH)) + ); + // 负方向同理 + assert_eq!( + parse_one(PropertyId::MarginTop, "-99999999999px"), + PropertyValue::Margin(MarginValue::Length(-MAX_CSS_LENGTH)) + ); + } + + #[test] + fn non_finite_length_tokens_are_rejected() { + // 1e40 溢出 f32 为 inf:整条声明按无效处理 + parse_err(PropertyId::Width, "1e40px"); + parse_err(PropertyId::MarginTop, "1e40px"); + parse_err(PropertyId::FontSize, "1e40px"); + parse_err(PropertyId::FlexGrow, "1e40"); + // 百分比 token 存的是除以 100 后的比值(50% → 0.5),1e42% 比值溢出 + parse_err(PropertyId::PaddingTop, "1e42%"); + } + + #[test] + fn relative_units_clamp_to_bound() { + // em / 百分比 / 无单位数值按比值 clamp 到同一上限,计算期乘积再钳(cascade) + assert_eq!( + parse_one(PropertyId::FontSize, "1e30em"), + PropertyValue::FontSize(FontSizeValue::Em(MAX_CSS_LENGTH)) + ); + // 1e40% 的比值是 1e38(有限)→ clamp;溢出比值见 non_finite 测试 + assert_eq!( + parse_one(PropertyId::PaddingTop, "1e40%"), + PropertyValue::Padding(PaddingValue::Percent(MAX_CSS_LENGTH)) + ); + assert_eq!( + parse_one(PropertyId::LineHeight, "1e30"), + PropertyValue::LineHeight(LineHeightValue::Number(MAX_CSS_LENGTH)) + ); + } +} diff --git a/crates/nexty-css/.mimosa/hook-state/sess_ca7e797f-14f7-4cd4-a65e-6a69d7418103.json b/crates/nexty-css/.mimosa/hook-state/sess_ca7e797f-14f7-4cd4-a65e-6a69d7418103.json new file mode 100644 index 0000000..cef67d4 --- /dev/null +++ b/crates/nexty-css/.mimosa/hook-state/sess_ca7e797f-14f7-4cd4-a65e-6a69d7418103.json @@ -0,0 +1 @@ +{"touched":["D:\\Nexty\\crates\\nexty-css\\src\\value.rs","D:\\Nexty\\crates\\nexty-css\\src\\parser.rs","D:\\Nexty\\crates\\nexty-css\\Cargo.toml","D:\\Nexty\\crates\\nexty-css\\src\\cascade.rs"],"bashMutation":true,"reportedFindings":[],"findingEvents":[],"baseline":{"storageId":"mv37y1v5-51660-adb7c830c0","createdAt":"2026-10-11T02:43:27.089Z","files":{"src/value.rs":{"existed":true,"snapshot":"be1c878c753064b7eaddf4a10ba4215a93dd1817d31e6788691cdb29752fd612.source"},"src/parser.rs":{"existed":true,"snapshot":"4a04259da480a6b794a2e947e4cc03eff4d1aa9330836f5b91cac68c5398193f.source"},"Cargo.toml":{"existed":true,"snapshot":"2e9d962a08321605940b5a657135052fbcef87b5e360662bb527c96d9a615542.source"},"src/cascade.rs":{"existed":true,"snapshot":"01bd7f2baaf2335e56694f02b60c806c80651a6e5acc29a13d3c84bf63ac1cdd.source"}},"complete":false,"candidateLimit":5000,"discoveredFiles":0,"capturedFiles":4,"truncated":false,"omittedAtLeast":0,"firstOmitted":"","errors":[{"stage":"baseline-capture","target":".","reason":"global task baseline was unavailable; captured only the touched file"},{"stage":"baseline-snapshot","target":"../nexty-layout/src/style_map.rs","reason":"file is outside project"},{"stage":"baseline-snapshot","target":"../nexty-layout/src/block.rs","reason":"file is outside project"},{"stage":"baseline-snapshot","target":"../nexty-layout/src/block.rs","reason":"file is outside project"}]},"stateErrors":[],"omittedReportedFindings":0,"omittedFindingEvents":0,"processing":null,"updatedAt":"2026-10-11T03:14:57.025Z"} \ No newline at end of file diff --git a/crates/nexty-css/.mimosa/hook-state/sess_ca7e797f-14f7-4cd4-a65e-6a69d7418103.mv37y1v5-51660-adb7c830c0.baseline/01bd7f2baaf2335e56694f02b60c806c80651a6e5acc29a13d3c84bf63ac1cdd.source b/crates/nexty-css/.mimosa/hook-state/sess_ca7e797f-14f7-4cd4-a65e-6a69d7418103.mv37y1v5-51660-adb7c830c0.baseline/01bd7f2baaf2335e56694f02b60c806c80651a6e5acc29a13d3c84bf63ac1cdd.source new file mode 100644 index 0000000..a4432c0 --- /dev/null +++ b/crates/nexty-css/.mimosa/hook-state/sess_ca7e797f-14f7-4cd4-a65e-6a69d7418103.mv37y1v5-51660-adb7c830c0.baseline/01bd7f2baaf2335e56694f02b60c806c80651a6e5acc29a13d3c84bf63ac1cdd.source @@ -0,0 +1,1509 @@ +//! 自研 cascade 与 computed style。 +//! +//! 行为 ground truth: +//! - 级联排序:[CSS Cascading and Inheritance Level 5 §6](https://drafts.csswg.org/css-cascade-5/#cascading) +//! - 继承 / 初始值:[CSS Cascade 5 §7](https://drafts.csswg.org/css-cascade-5/#defaulting) +//! - 字号计算:[CSS Fonts 4 §2.5](https://drafts.csswg.org/css-fonts-4/#font-size-prop) +//! - 相对字重:[CSS Fonts 4 §2.2.1](https://drafts.csswg.org/css-fonts-4/#relative-weights) +//! +//! 本轮只有 author origin(UA 样式表未引入),故排序桶为: +//! importance → 内联样式 → 特异度 → 源顺序。`revert` 回退到 UA origin, +//! 而 UA 无声明,等价于 initial。 + +use std::collections::HashMap; + +use nexty_dom::{Document, NodeId, NodeKind}; + +use crate::parser::{Declaration, MediaViewport, Stylesheet, parse_inline_style}; +use crate::selector::match_element_selectors; +use crate::value::{ + AbsoluteSize, AlignItemsValue, AlignSelfValue, BorderColorValue, BorderStyle, BorderWidthValue, + BoxSizingValue, CssWideKeyword, DeclaredValue, DisplayValue, FlexDirectionValue, FlexWrapValue, + FontFamilyValue, FontSizeValue, FontStyleValue, FontWeightValue, GapValue, GridAutoFlowValue, + GridTrackList, InsetValue, JustifyContentValue, LineHeightValue, MarginValue, OverflowValue, + PaddingValue, PositionValue, PropertyId, PropertyValue, Rgba, SizeValue, TextAlignValue, + ViewportUnit, +}; + +/// 本层 UA 的 medium 字号基准(CSS Fonts 4 §2.5:initial 值由 UA 决定, +/// 对齐浏览器默认 16px;绝对尺寸关键字按 §2.5.1 缩放系数相对它计算)。 +pub(crate) const MEDIUM_FONT_SIZE: f32 = 16.0; + +/// 一个元素的 computed style(属性集随管线逐轮扩展)。 +#[derive(Debug, Clone, PartialEq)] +pub struct ComputedStyle { + /// `display`。 + pub display: DisplayValue, + /// `color`。 + pub color: Rgba, + /// `background-color`。 + pub background_color: Rgba, + /// 计算字号(CSS px)。 + pub font_size: f32, + /// 计算字重(1–1000)。 + pub font_weight: f32, + /// `font-style`。 + pub font_style: FontStyleValue, + /// `font-family` 列表。 + pub font_family: Vec<FontFamilyValue>, + /// `text-align`。 + pub text_align: TextAlignValue, + /// `line-height`(数值/normal 保持原样;长度为绝对 px; + /// 百分比与 em 已按本元素 font-size 折算)。 + pub line_height: LineHeightValue, + /// `width`(百分比由 layout 解析)。 + pub width: SizeValue, + /// `height`(百分比由 layout 解析)。 + pub height: SizeValue, + /// `min-width`(CSS 2.1 §10.4)。 + pub min_width: SizeValue, + /// `max-width`(CSS 2.1 §10.4)。 + pub max_width: SizeValue, + /// `min-height`(CSS 2.1 §10.7)。 + pub min_height: SizeValue, + /// `max-height`(CSS 2.1 §10.7)。 + pub max_height: SizeValue, + /// `box-sizing`(CSS Sizing 4 §5.3)。 + pub box_sizing: BoxSizingValue, + /// `overflow`(CSS Overflow 3 §3;仅裁剪标记,裁剪未实现)。 + pub overflow: OverflowValue, + /// `flex-grow`(CSS Flexbox §7.1,initial 0)。 + pub flex_grow: f32, + /// `flex-basis`(CSS Flexbox §7.2,initial auto)。 + pub flex_basis: SizeValue, + /// `position`(CSS Position 3 §2,initial static)。 + pub position: PositionValue, + /// 四边 inset(top / right / bottom / left;百分比与 auto 由 layout 解析)。 + pub inset: Edges<InsetValue>, + /// `flex-direction`(CSS Flexbox §8.3.1,initial row)。 + pub flex_direction: FlexDirectionValue, + /// `flex-wrap`(CSS Flexbox §8.4.1,initial nowrap)。 + pub flex_wrap: FlexWrapValue, + /// `flex-shrink`(CSS Flexbox §7.2,initial 1)。 + pub flex_shrink: f32, + /// `align-items`(CSS Box Alignment §7,initial stretch)。 + pub align_items: AlignItemsValue, + /// `justify-content`(CSS Box Alignment §8,initial flex-start)。 + pub justify_content: JustifyContentValue, + /// `align-self`(CSS Box Alignment §7,initial auto)。 + pub align_self: AlignSelfValue, + /// `grid-template-columns`(CSS Grid §7.2,initial 空)。 + pub grid_template_columns: GridTrackList, + /// `grid-template-rows`(CSS Grid §7.3,initial 空)。 + pub grid_template_rows: GridTrackList, + /// `row-gap`(CSS Box Alignment §6,initial normal)。 + pub row_gap: GapValue, + /// `column-gap`(CSS Box Alignment §6,initial normal)。 + pub column_gap: GapValue, + /// `grid-auto-flow`(CSS Grid §7.7,initial row)。 + pub grid_auto_flow: GridAutoFlowValue, + /// 四边 margin(百分比与 auto 由 layout 解析)。 + pub margin: Edges<MarginValue>, + /// 四边 padding(百分比由 layout 解析)。 + pub padding: Edges<PaddingValue>, + /// 四边 border 宽度(computed 值:style 为 none/hidden 时为 0)。 + pub border_width: Edges<f32>, + /// 四边 border 样式。 + pub border_style: Edges<BorderStyle>, + /// 四边 border 颜色(currentcolor 已按本元素 color 解析)。 + pub border_color: Edges<Rgba>, +} + +/// 四边值(top / right / bottom / left)。 +#[derive(Debug, Clone, Copy, PartialEq)] +pub struct Edges<T> { + /// 上边。 + pub top: T, + /// 右边。 + pub right: T, + /// 下边。 + pub bottom: T, + /// 左边。 + pub left: T, +} + +impl<T: Copy> Edges<T> { + /// 用同一值填充四边。 + #[must_use] + pub const fn splat(value: T) -> Self { + Self { + top: value, + right: value, + bottom: value, + left: value, + } + } +} + +impl ComputedStyle { + /// 全部属性取 initial 值。 + /// + /// initial 值逐条对应各属性规范;UA 相关的(`color` 的 `CanvasText`、 + /// `font-family` 的 UA 默认、`font-size` 的 medium、`line-height` 的 + /// normal)取本层固定选择:黑色、serif、16px。 + #[must_use] + pub fn initial() -> Self { + Self { + display: DisplayValue::Inline, + color: Rgba::opaque(0, 0, 0), + background_color: Rgba::transparent(), + font_size: MEDIUM_FONT_SIZE, + font_weight: 400.0, + font_style: FontStyleValue::Normal, + font_family: vec![FontFamilyValue::Generic("serif")], + text_align: TextAlignValue::Start, + line_height: LineHeightValue::Normal, + width: SizeValue::Auto, + height: SizeValue::Auto, + min_width: SizeValue::Auto, + max_width: SizeValue::Auto, + min_height: SizeValue::Auto, + max_height: SizeValue::Auto, + box_sizing: BoxSizingValue::ContentBox, + overflow: OverflowValue::Visible, + flex_grow: 0.0, + flex_basis: SizeValue::Auto, + position: PositionValue::Static, + inset: Edges::splat(InsetValue::Auto), + flex_direction: FlexDirectionValue::Row, + flex_wrap: FlexWrapValue::NoWrap, + flex_shrink: 1.0, + align_items: AlignItemsValue::Stretch, + justify_content: JustifyContentValue::FlexStart, + align_self: AlignSelfValue::Auto, + grid_template_columns: GridTrackList::default(), + grid_template_rows: GridTrackList::default(), + row_gap: GapValue::Normal, + column_gap: GapValue::Normal, + grid_auto_flow: GridAutoFlowValue::Row, + margin: Edges::splat(MarginValue::Length(0.0)), + padding: Edges::splat(PaddingValue::Length(0.0)), + border_width: Edges::splat(0.0), + border_style: Edges::splat(BorderStyle::None), + border_color: Edges::splat(Rgba::opaque(0, 0, 0)), + } + } +} + +impl PropertyId { + /// 属性是否继承(各属性规范 "Inherited" 行)。 + #[must_use] + pub fn inherited(self) -> bool { + matches!( + self, + Self::Color + | Self::FontSize + | Self::FontWeight + | Self::FontStyle + | Self::FontFamily + | Self::TextAlign + | Self::LineHeight + ) + } +} + +/// 全部属性的固定枚举顺序。 +/// +/// 顺序承载计算依赖:`FontSize` 先于 `LineHeight`(百分比按自身字号折算)、 +/// `Color` 先于 border 颜色(currentcolor)、border style 先于 width +/// (none/hidden 时宽度归零)。 +const PROPERTY_ORDER: [PropertyId; 55] = [ + PropertyId::Display, + PropertyId::Color, + PropertyId::BackgroundColor, + PropertyId::FontSize, + PropertyId::FontWeight, + PropertyId::FontStyle, + PropertyId::FontFamily, + PropertyId::TextAlign, + PropertyId::LineHeight, + PropertyId::Width, + PropertyId::Height, + PropertyId::MinWidth, + PropertyId::MaxWidth, + PropertyId::MinHeight, + PropertyId::MaxHeight, + PropertyId::BoxSizing, + PropertyId::Overflow, + PropertyId::FlexGrow, + PropertyId::FlexBasis, + PropertyId::Position, + PropertyId::Top, + PropertyId::Right, + PropertyId::Bottom, + PropertyId::Left, + PropertyId::FlexDirection, + PropertyId::FlexWrap, + PropertyId::FlexShrink, + PropertyId::AlignItems, + PropertyId::JustifyContent, + PropertyId::AlignSelf, + PropertyId::GridTemplateColumns, + PropertyId::GridTemplateRows, + PropertyId::RowGap, + PropertyId::ColumnGap, + PropertyId::GridAutoFlow, + PropertyId::MarginTop, + PropertyId::MarginRight, + PropertyId::MarginBottom, + PropertyId::MarginLeft, + PropertyId::PaddingTop, + PropertyId::PaddingRight, + PropertyId::PaddingBottom, + PropertyId::PaddingLeft, + PropertyId::BorderTopStyle, + PropertyId::BorderRightStyle, + PropertyId::BorderBottomStyle, + PropertyId::BorderLeftStyle, + PropertyId::BorderTopWidth, + PropertyId::BorderRightWidth, + PropertyId::BorderBottomWidth, + PropertyId::BorderLeftWidth, + PropertyId::BorderTopColor, + PropertyId::BorderRightColor, + PropertyId::BorderBottomColor, + PropertyId::BorderLeftColor, +]; + +/// 级联 origin 桶(CSS Cascade 5 §6.4,仅 UA 与 author 两个 origin; +/// user origin 尚未引入)。 +/// +/// 值越大优先级越高:UA 普通 < author 普通 < author `!important` < +/// UA `!important`。 +#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord)] +enum OriginBucket { + UaNormal = 0, + AuthorNormal = 1, + AuthorImportant = 2, + UaImportant = 3, +} + +/// 级联排序键(CSS Cascade 5 §6.4)。 +/// +/// 字典序即优先级:先 origin/importance 桶;author 声明中内联样式排在 +/// 样式表声明之后(§6.4 style attribute);然后按特异度、规则顺序、声明顺序。 +#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord)] +struct CascadeKey { + bucket: OriginBucket, + inline: bool, + specificity: u32, + rule_order: usize, + declaration_order: usize, +} + +/// 级联 origin(CSS Cascade 5 §6.4;user origin 尚未引入)。 +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +enum Origin { + Ua, + Author, +} + +/// origin + importance → 排序桶:UA 普通 < author 普通 < author `!important` +/// < UA `!important`。 +fn bucket_of(origin: Origin, important: bool) -> OriginBucket { + match (origin, important) { + (Origin::Ua, false) => OriginBucket::UaNormal, + (Origin::Author, false) => OriginBucket::AuthorNormal, + (Origin::Author, true) => OriginBucket::AuthorImportant, + (Origin::Ua, true) => OriginBucket::UaImportant, + } +} + +/// 收集一个 origin 样式表中命中元素的全部声明。 +fn collect_origin_declarations( + document: &Document, + element: NodeId, + sheet: &Stylesheet, + origin: Origin, + matched: &mut Vec<(CascadeKey, Declaration)>, +) { + for (rule_order, rule) in sheet.rules().iter().enumerate() { + // 规则内多个选择器都能命中时,取特异度最高者 + // (CSS Cascade 5:声明的特异度取其匹配选择器中的最大值)。 + let specificity = rule + .selectors() + .iter() + .filter(|parsed| { + match_element_selectors(std::slice::from_ref(parsed), document, element) + }) + .map(|parsed| parsed.specificity) + .max(); + if let Some(specificity) = specificity { + for (declaration_order, declaration) in rule.declarations().iter().enumerate() { + matched.push(( + CascadeKey { + bucket: bucket_of(origin, declaration.important), + inline: false, + specificity, + rule_order, + declaration_order, + }, + declaration.clone(), + )); + } + } + } +} + +/// 对单个元素做级联,产出 computed style。 +/// +/// `ua_sheet` 是 UA origin 样式表(浏览器默认样式),参与级联但优先级 +/// 低于 author 声明(UA `!important` 最高,见 [`OriginBucket`])。 +/// `parent` 是树序父元素的 computed style(元素没有元素祖先时为 `None`)。 +/// 各属性:级联胜者 → CSS-wide 关键字 → 继承 → initial。 +/// 无视口信息:视口单位原样保留(见 [`cascade_in`])。 +#[must_use] +pub fn cascade( + document: &Document, + element: NodeId, + stylesheets: &[&Stylesheet], + ua_sheet: Option<&Stylesheet>, + parent: Option<&ComputedStyle>, +) -> ComputedStyle { + cascade_in(document, element, stylesheets, ua_sheet, parent, None) +} + +/// [`cascade`] 的带视口版本:视口单位(vw/vh/vmin/vmax)在 computed 阶段 +/// 按给定视口折算为绝对 px(CSS Values 4 §6.2:1v* = 视口对应边的 1%)。 +/// 未提供视口时视口单位原样保留,由消费方按降级值处理。 +#[must_use] +pub fn cascade_in( + document: &Document, + element: NodeId, + stylesheets: &[&Stylesheet], + ua_sheet: Option<&Stylesheet>, + parent: Option<&ComputedStyle>, + viewport: Option<MediaViewport>, +) -> ComputedStyle { + let mut matched: Vec<(CascadeKey, Declaration)> = Vec::new(); + + if let Some(ua) = ua_sheet { + collect_origin_declarations(document, element, ua, Origin::Ua, &mut matched); + } + // 规则顺序跨样式表连续编号:样式表按传入顺序、规则按源顺序 + for (rule_order, rule) in stylesheets + .iter() + .flat_map(|sheet| sheet.rules()) + .enumerate() + { + let specificity = rule + .selectors() + .iter() + .filter(|parsed| { + match_element_selectors(std::slice::from_ref(parsed), document, element) + }) + .map(|parsed| parsed.specificity) + .max(); + if let Some(specificity) = specificity { + for (declaration_order, declaration) in rule.declarations().iter().enumerate() { + matched.push(( + CascadeKey { + bucket: bucket_of(Origin::Author, declaration.important), + inline: false, + specificity, + rule_order, + declaration_order, + }, + declaration.clone(), + )); + } + } + } + + // 内联 style 属性:author origin,普通声明排在全部样式表声明之后 + if let Some(style_attribute) = style_attribute_of(document, element) { + for (declaration_order, declaration) in + parse_inline_style(&style_attribute).into_iter().enumerate() + { + matched.push(( + CascadeKey { + bucket: bucket_of(Origin::Author, declaration.important), + inline: true, + specificity: 0, + rule_order: usize::MAX, + declaration_order, + }, + declaration, + )); + } + } + + resolve_all(&matched, parent, viewport) +} + +/// 按树序计算整份文档的 computed style(父先于子)。 +/// +/// `<template>` 的内容子树是惰性片段,不参与级联,跳过。 +#[must_use] +pub fn compute_document_styles( + document: &Document, + stylesheets: &[&Stylesheet], + ua_sheet: Option<&Stylesheet>, +) -> HashMap<NodeId, ComputedStyle> { + compute_document_styles_in(document, stylesheets, ua_sheet, None) +} + +/// [`compute_document_styles`] 的带视口版本:视口单位(vw/vh/vmin/vmax) +/// 在 computed 阶段按给定视口折算为绝对 px(CSS Values 4 §6.2)。 +/// 未提供视口时视口单位原样保留,由消费方按降级值处理。 +#[must_use] +pub fn compute_document_styles_in( + document: &Document, + stylesheets: &[&Stylesheet], + ua_sheet: Option<&Stylesheet>, + viewport: Option<MediaViewport>, +) -> HashMap<NodeId, ComputedStyle> { + let mut styles = HashMap::new(); + walk( + document, + document.root(), + None, + stylesheets, + ua_sheet, + viewport, + &mut styles, + ); + styles +} + +fn walk( + document: &Document, + node: NodeId, + parent: Option<&ComputedStyle>, + stylesheets: &[&Stylesheet], + ua_sheet: Option<&Stylesheet>, + viewport: Option<MediaViewport>, + out: &mut HashMap<NodeId, ComputedStyle>, +) { + for child in document.children(node) { + if matches!(document.node(child), Some(NodeKind::Element(_))) { + let style = cascade_in(document, child, stylesheets, ua_sheet, parent, viewport); + walk( + document, + child, + Some(&style), + stylesheets, + ua_sheet, + viewport, + out, + ); + out.insert(child, style); + } + } +} + +/// 元素的 style 属性值。 +fn style_attribute_of(document: &Document, element: NodeId) -> Option<String> { + match document.node(element) { + Some(NodeKind::Element(data)) => data + .attributes + .iter() + .find(|attr| attr.namespace == nexty_dom::Namespace::None && attr.name == "style") + .map(|attr| attr.value.clone()), + _ => None, + } +} + +/// 某属性在级联中的胜者声明。 +fn winner(property: PropertyId, matched: &[(CascadeKey, Declaration)]) -> Option<&Declaration> { + matched + .iter() + .filter(|(_, declaration)| declaration.property == property) + .max_by_key(|(key, _)| *key) + .map(|(_, declaration)| declaration) +} + +/// 胜者决定该属性的来源。 +enum Decision<'a> { + /// 使用级联胜者的属性值。 + Use(&'a PropertyValue), + /// 取父元素的 computed value;无父元素则取 initial。 + Parent, + /// 取 initial 值。 + Initial, +} + +fn decide<'a>( + property: PropertyId, + winner: Option<&'a Declaration>, + parent: Option<&ComputedStyle>, +) -> Decision<'a> { + let has_parent = parent.is_some(); + match winner { + Some(Declaration { + value: DeclaredValue::Typed(value), + .. + }) => Decision::Use(value), + Some(Declaration { + value: DeclaredValue::CssWide(keyword), + .. + }) => match keyword { + // revert 回退到 UA origin;本层 UA 无声明,等价 initial + CssWideKeyword::Initial | CssWideKeyword::Revert => Decision::Initial, + CssWideKeyword::Inherit => Decision::Parent, + CssWideKeyword::Unset => { + if property.inherited() && has_parent { + Decision::Parent + } else { + Decision::Initial + } + } + }, + // 无声明:继承属性取父值,否则取 initial(CSS Cascade 5 §7) + None => { + if property.inherited() && has_parent { + Decision::Parent + } else { + Decision::Initial + } + } + } +} + +/// 视口单位折算为 px:1v* = 视口对应边的 1%(CSS Values 4 §6.2)。 +fn viewport_px(amount: f32, unit: ViewportUnit, viewport: MediaViewport) -> f32 { + let base = match unit { + ViewportUnit::Vw => viewport.width, + ViewportUnit::Vh => viewport.height, + ViewportUnit::Vmin => viewport.width.min(viewport.height), + ViewportUnit::Vmax => viewport.width.max(viewport.height), + }; + amount * base / 100.0 +} + +macro_rules! resolve_viewport { + ($fn_name:ident, $enum:ident) => { + fn $fn_name(value: $enum, viewport: Option<MediaViewport>) -> $enum { + match value { + $enum::Viewport(amount, unit) => match viewport { + Some(vp) => $enum::Length(viewport_px(amount, unit, vp)), + None => $enum::Viewport(amount, unit), + }, + other => other, + } + } + }; +} + +resolve_viewport!(resolve_size, SizeValue); +resolve_viewport!(resolve_inset, InsetValue); +resolve_viewport!(resolve_margin, MarginValue); +resolve_viewport!(resolve_padding, PaddingValue); +resolve_viewport!(resolve_gap, GapValue); + +/// 逐属性解析出 computed style。 +fn resolve_all( + matched: &[(CascadeKey, Declaration)], + parent: Option<&ComputedStyle>, + viewport: Option<MediaViewport>, +) -> ComputedStyle { + let initial = ComputedStyle::initial(); + let mut style = initial.clone(); + let parent_font_size = parent.map_or(MEDIUM_FONT_SIZE, |p| p.font_size); + let parent_font_weight = parent.map_or(400.0, |p| p.font_weight); + + for property in PROPERTY_ORDER { + let decision = decide(property, winner(property, matched), parent); + match (property, decision) { + (PropertyId::Display, Decision::Use(PropertyValue::Display(value))) => { + style.display = *value; + } + (PropertyId::TextAlign, Decision::Use(PropertyValue::TextAlign(value))) => { + style.text_align = *value; + } + (PropertyId::FontStyle, Decision::Use(PropertyValue::FontStyle(value))) => { + style.font_style = *value; + } + (PropertyId::Color, Decision::Use(PropertyValue::Color(value))) => { + style.color = *value; + } + (PropertyId::BackgroundColor, Decision::Use(PropertyValue::Color(value))) => { + style.background_color = *value; + } + (PropertyId::FontSize, Decision::Use(PropertyValue::FontSize(value))) => { + style.font_size = compute_font_size(value, parent_font_size); + } + (PropertyId::FontWeight, Decision::Use(PropertyValue::FontWeight(value))) => { + style.font_weight = compute_font_weight(value, parent_font_weight); + } + (PropertyId::FontFamily, Decision::Use(PropertyValue::FontFamily(value))) => { + style.font_family = value.clone(); + } + (PropertyId::LineHeight, Decision::Use(PropertyValue::LineHeight(value))) => { + // CSS 2.1 §10.8.1:百分比/em 的 computed 值为绝对长度 + //(按本元素自身 font-size,已在 PROPERTY_ORDER 中先求) + style.line_height = match *value { + LineHeightValue::Percent(fraction) => { + LineHeightValue::Length(style.font_size * fraction) + } + LineHeightValue::Em(em) => LineHeightValue::Length(style.font_size * em), + other => other, + }; + } + (PropertyId::Width, Decision::Use(PropertyValue::Size(value))) => { + style.width = resolve_size(*value, viewport); + } + (PropertyId::Height, Decision::Use(PropertyValue::Size(value))) => { + style.height = resolve_size(*value, viewport); + } + (PropertyId::MinWidth, Decision::Use(PropertyValue::Size(value))) => { + style.min_width = resolve_size(*value, viewport); + } + (PropertyId::MaxWidth, Decision::Use(PropertyValue::Size(value))) => { + style.max_width = resolve_size(*value, viewport); + } + (PropertyId::MinHeight, Decision::Use(PropertyValue::Size(value))) => { + style.min_height = resolve_size(*value, viewport); + } + (PropertyId::MaxHeight, Decision::Use(PropertyValue::Size(value))) => { + style.max_height = resolve_size(*value, viewport); + } + (PropertyId::BoxSizing, Decision::Use(PropertyValue::BoxSizing(value))) => { + style.box_sizing = *value; + } + (PropertyId::Overflow, Decision::Use(PropertyValue::Overflow(value))) => { + style.overflow = *value; + } + (PropertyId::FlexGrow, Decision::Use(PropertyValue::FlexGrow(value))) => { + style.flex_grow = *value; + } + (PropertyId::FlexBasis, Decision::Use(PropertyValue::FlexBasis(value))) => { + style.flex_basis = *value; + } + (PropertyId::Position, Decision::Use(PropertyValue::Position(value))) => { + style.position = *value; + } + (PropertyId::Top, Decision::Use(PropertyValue::Inset(value))) => { + style.inset.top = resolve_inset(*value, viewport); + } + (PropertyId::Right, Decision::Use(PropertyValue::Inset(value))) => { + style.inset.right = resolve_inset(*value, viewport); + } + (PropertyId::Bottom, Decision::Use(PropertyValue::Inset(value))) => { + style.inset.bottom = resolve_inset(*value, viewport); + } + (PropertyId::Left, Decision::Use(PropertyValue::Inset(value))) => { + style.inset.left = resolve_inset(*value, viewport); + } + (PropertyId::FlexDirection, Decision::Use(PropertyValue::FlexDirection(value))) => { + style.flex_direction = *value; + } + (PropertyId::FlexWrap, Decision::Use(PropertyValue::FlexWrap(value))) => { + style.flex_wrap = *value; + } + (PropertyId::FlexShrink, Decision::Use(PropertyValue::FlexShrink(value))) => { + style.flex_shrink = *value; + } + (PropertyId::AlignItems, Decision::Use(PropertyValue::AlignItems(value))) => { + style.align_items = *value; + } + (PropertyId::JustifyContent, Decision::Use(PropertyValue::JustifyContent(value))) => { + style.justify_content = *value; + } + (PropertyId::AlignSelf, Decision::Use(PropertyValue::AlignSelf(value))) => { + style.align_self = *value; + } + (PropertyId::GridTemplateColumns, Decision::Use(PropertyValue::GridTrack(value))) => { + style.grid_template_columns = value.clone(); + } + (PropertyId::GridTemplateRows, Decision::Use(PropertyValue::GridTrack(value))) => { + style.grid_template_rows = value.clone(); + } + (PropertyId::RowGap, Decision::Use(PropertyValue::Gap(value))) => { + style.row_gap = resolve_gap(*value, viewport); + } + (PropertyId::ColumnGap, Decision::Use(PropertyValue::Gap(value))) => { + style.column_gap = resolve_gap(*value, viewport); + } + (PropertyId::GridAutoFlow, Decision::Use(PropertyValue::GridAutoFlow(value))) => { + style.grid_auto_flow = *value; + } + (PropertyId::MarginTop, Decision::Use(PropertyValue::Margin(value))) => { + style.margin.top = resolve_margin(*value, viewport); + } + (PropertyId::MarginRight, Decision::Use(PropertyValue::Margin(value))) => { + style.margin.right = resolve_margin(*value, viewport); + } + (PropertyId::MarginBottom, Decision::Use(PropertyValue::Margin(value))) => { + style.margin.bottom = resolve_margin(*value, viewport); + } + (PropertyId::MarginLeft, Decision::Use(PropertyValue::Margin(value))) => { + style.margin.left = resolve_margin(*value, viewport); + } + (PropertyId::PaddingTop, Decision::Use(PropertyValue::Padding(value))) => { + style.padding.top = resolve_padding(*value, viewport); + } + (PropertyId::PaddingRight, Decision::Use(PropertyValue::Padding(value))) => { + style.padding.right = resolve_padding(*value, viewport); + } + (PropertyId::PaddingBottom, Decision::Use(PropertyValue::Padding(value))) => { + style.padding.bottom = resolve_padding(*value, viewport); + } + (PropertyId::PaddingLeft, Decision::Use(PropertyValue::Padding(value))) => { + style.padding.left = resolve_padding(*value, viewport); + } + (PropertyId::BorderTopStyle, Decision::Use(PropertyValue::BorderStyle(value))) => { + style.border_style.top = *value; + } + (PropertyId::BorderRightStyle, Decision::Use(PropertyValue::BorderStyle(value))) => { + style.border_style.right = *value; + } + (PropertyId::BorderBottomStyle, Decision::Use(PropertyValue::BorderStyle(value))) => { + style.border_style.bottom = *value; + } + (PropertyId::BorderLeftStyle, Decision::Use(PropertyValue::BorderStyle(value))) => { + style.border_style.left = *value; + } + (PropertyId::BorderTopWidth, Decision::Use(PropertyValue::BorderWidth(value))) => { + style.border_width.top = used_border_width(*value, style.border_style.top); + } + (PropertyId::BorderRightWidth, Decision::Use(PropertyValue::BorderWidth(value))) => { + style.border_width.right = used_border_width(*value, style.border_style.right); + } + (PropertyId::BorderBottomWidth, Decision::Use(PropertyValue::BorderWidth(value))) => { + style.border_width.bottom = used_border_width(*value, style.border_style.bottom); + } + (PropertyId::BorderLeftWidth, Decision::Use(PropertyValue::BorderWidth(value))) => { + style.border_width.left = used_border_width(*value, style.border_style.left); + } + (PropertyId::BorderTopColor, Decision::Use(PropertyValue::BorderColor(value))) => { + style.border_color.top = resolve_border_color(*value, style.color); + } + (PropertyId::BorderRightColor, Decision::Use(PropertyValue::BorderColor(value))) => { + style.border_color.right = resolve_border_color(*value, style.color); + } + (PropertyId::BorderBottomColor, Decision::Use(PropertyValue::BorderColor(value))) => { + style.border_color.bottom = resolve_border_color(*value, style.color); + } + (PropertyId::BorderLeftColor, Decision::Use(PropertyValue::BorderColor(value))) => { + style.border_color.left = resolve_border_color(*value, style.color); + } + // 关键字与继承:按属性回退 + (property, decision @ (Decision::Parent | Decision::Initial)) => { + let source = match decision { + Decision::Parent => parent.unwrap_or(&initial), + _ => &initial, + }; + match property { + PropertyId::Display => style.display = source.display, + PropertyId::Color => style.color = source.color, + PropertyId::BackgroundColor => style.background_color = source.background_color, + PropertyId::FontSize => style.font_size = source.font_size, + PropertyId::FontWeight => style.font_weight = source.font_weight, + PropertyId::FontStyle => style.font_style = source.font_style, + PropertyId::FontFamily => style.font_family = source.font_family.clone(), + PropertyId::TextAlign => style.text_align = source.text_align, + PropertyId::LineHeight => style.line_height = source.line_height, + PropertyId::Width => style.width = source.width, + PropertyId::Height => style.height = source.height, + PropertyId::MinWidth => style.min_width = source.min_width, + PropertyId::MaxWidth => style.max_width = source.max_width, + PropertyId::MinHeight => style.min_height = source.min_height, + PropertyId::MaxHeight => style.max_height = source.max_height, + PropertyId::BoxSizing => style.box_sizing = source.box_sizing, + PropertyId::Overflow => style.overflow = source.overflow, + PropertyId::FlexGrow => style.flex_grow = source.flex_grow, + PropertyId::FlexBasis => style.flex_basis = source.flex_basis, + PropertyId::Position => style.position = source.position, + PropertyId::Top => style.inset.top = source.inset.top, + PropertyId::Right => style.inset.right = source.inset.right, + PropertyId::Bottom => style.inset.bottom = source.inset.bottom, + PropertyId::Left => style.inset.left = source.inset.left, + PropertyId::FlexDirection => style.flex_direction = source.flex_direction, + PropertyId::FlexWrap => style.flex_wrap = source.flex_wrap, + PropertyId::FlexShrink => style.flex_shrink = source.flex_shrink, + PropertyId::AlignItems => style.align_items = source.align_items, + PropertyId::JustifyContent => style.justify_content = source.justify_content, + PropertyId::AlignSelf => style.align_self = source.align_self, + PropertyId::GridTemplateColumns => { + style.grid_template_columns = source.grid_template_columns.clone() + } + PropertyId::GridTemplateRows => { + style.grid_template_rows = source.grid_template_rows.clone() + } + PropertyId::RowGap => style.row_gap = source.row_gap, + PropertyId::ColumnGap => style.column_gap = source.column_gap, + PropertyId::GridAutoFlow => style.grid_auto_flow = source.grid_auto_flow, + PropertyId::MarginTop => style.margin.top = source.margin.top, + PropertyId::MarginRight => style.margin.right = source.margin.right, + PropertyId::MarginBottom => style.margin.bottom = source.margin.bottom, + PropertyId::MarginLeft => style.margin.left = source.margin.left, + PropertyId::PaddingTop => style.padding.top = source.padding.top, + PropertyId::PaddingRight => style.padding.right = source.padding.right, + PropertyId::PaddingBottom => style.padding.bottom = source.padding.bottom, + PropertyId::PaddingLeft => style.padding.left = source.padding.left, + PropertyId::BorderTopStyle => style.border_style.top = source.border_style.top, + PropertyId::BorderRightStyle => { + style.border_style.right = source.border_style.right; + } + PropertyId::BorderBottomStyle => { + style.border_style.bottom = source.border_style.bottom; + } + PropertyId::BorderLeftStyle => { + style.border_style.left = source.border_style.left; + } + PropertyId::BorderTopWidth => style.border_width.top = source.border_width.top, + PropertyId::BorderRightWidth => { + style.border_width.right = source.border_width.right; + } + PropertyId::BorderBottomWidth => { + style.border_width.bottom = source.border_width.bottom; + } + PropertyId::BorderLeftWidth => { + style.border_width.left = source.border_width.left; + } + PropertyId::BorderTopColor => style.border_color.top = source.border_color.top, + PropertyId::BorderRightColor => { + style.border_color.right = source.border_color.right; + } + PropertyId::BorderBottomColor => { + style.border_color.bottom = source.border_color.bottom; + } + PropertyId::BorderLeftColor => { + style.border_color.left = source.border_color.left; + } + } + } + // 声明值与属性不匹配只可能来自程序错误;保持 initial 值 + _ => {} + } + } + style +} + +/// border-*-width 的 computed 值:style 为 none/hidden 时为 0 +/// (CSS 2.1 §8.5.4)。 +fn used_border_width(value: BorderWidthValue, border_style: BorderStyle) -> f32 { + if border_style.visible() { + value.px() + } else { + 0.0 + } +} + +/// border-*-color 的 computed 值:currentcolor 按本元素 color 解析。 +fn resolve_border_color(value: BorderColorValue, color: Rgba) -> Rgba { + match value { + BorderColorValue::Rgba(rgba) => rgba, + BorderColorValue::CurrentColor => color, + } +} + +/// `font-size` 计算值(CSS Fonts 4 §2.5:长度/百分比相对父元素计算字号)。 +fn compute_font_size(value: &FontSizeValue, parent_font_size: f32) -> f32 { + match value { + FontSizeValue::Px(px) => *px, + FontSizeValue::Em(em) => parent_font_size * em, + FontSizeValue::Percent(fraction) => parent_font_size * fraction, + FontSizeValue::Absolute(size) => MEDIUM_FONT_SIZE * size.factor(), + FontSizeValue::Larger => adjacent_size(parent_font_size, true), + FontSizeValue::Smaller => adjacent_size(parent_font_size, false), + } +} + +/// `larger` / `smaller`:父字号恰为绝对尺寸表项时取相邻项 +/// (CSS Fonts 4 §2.5),否则按规范允许的简单比例 1.2 缩放。 +fn adjacent_size(parent_font_size: f32, larger: bool) -> f32 { + const TOLERANCE: f32 = 0.01; + let index = AbsoluteSize::ORDERED + .iter() + .position(|size| (MEDIUM_FONT_SIZE * size.factor() - parent_font_size).abs() <= TOLERANCE); + match index { + Some(index) if larger && index + 1 < AbsoluteSize::ORDERED.len() => { + MEDIUM_FONT_SIZE * AbsoluteSize::ORDERED[index + 1].factor() + } + Some(index) if !larger && index > 0 => { + MEDIUM_FONT_SIZE * AbsoluteSize::ORDERED[index - 1].factor() + } + // 表外或已到表端:简单比例 + _ => { + if larger { + parent_font_size * 1.2 + } else { + parent_font_size / 1.2 + } + } + } +} + +/// `font-weight` 计算值(CSS Fonts 4 §2.2)。 +fn compute_font_weight(value: &FontWeightValue, parent_font_weight: f32) -> f32 { + match value { + FontWeightValue::Weight(weight) => weight.clamp(1.0, 1000.0), + FontWeightValue::Bolder => relative_weight(parent_font_weight, true), + FontWeightValue::Lighter => relative_weight(parent_font_weight, false), + } +} + +/// bolder / lighter 相对映射表(CSS Fonts 4 §2.2.1)。 +fn relative_weight(parent_weight: f32, bolder: bool) -> f32 { + if parent_weight < 100.0 { + if bolder { 400.0 } else { parent_weight } + } else if parent_weight < 350.0 { + if bolder { 400.0 } else { 100.0 } + } else if parent_weight < 550.0 { + if bolder { 700.0 } else { 100.0 } + } else if parent_weight < 750.0 { + if bolder { 900.0 } else { 400.0 } + } else if parent_weight < 900.0 { + if bolder { 900.0 } else { 700.0 } + } else { + // bolder:无更粗字重,保持不变;lighter:700 + if bolder { parent_weight } else { 700.0 } + } +} + +#[cfg(test)] +mod tests { + use super::*; + use crate::html_ua_stylesheet; + use crate::test_support::{build_document, find_first_by_name}; + use crate::value::GridTrack; + + fn style_of(html: &str, sheets: &[&str], name: &str) -> ComputedStyle { + let document = build_document(html); + let parsed: Vec<Stylesheet> = sheets.iter().map(|css| Stylesheet::parse(css)).collect(); + let refs: Vec<&Stylesheet> = parsed.iter().collect(); + let element = find_first_by_name(&document, name).expect("element"); + cascade(&document, element, &refs, None, None) + } + + #[test] + fn no_declarations_fall_back_to_inheritance_and_initial() { + let document = build_document("<div style=\"color: red\"><p>x</p></div>"); + let refs: Vec<&Stylesheet> = vec![]; + let div = find_first_by_name(&document, "div").expect("div"); + let div_style = cascade(&document, div, &refs, None, None); + assert_eq!(div_style.color, Rgba::opaque(255, 0, 0), "内联样式生效"); + assert_eq!( + div_style.background_color, + Rgba::transparent(), + "非继承属性取 initial" + ); + + let p = find_first_by_name(&document, "p").expect("p"); + let p_style = cascade(&document, p, &refs, None, Some(&div_style)); + assert_eq!(p_style.color, Rgba::opaque(255, 0, 0), "继承属性取父值"); + assert_eq!(p_style.background_color, Rgba::transparent()); + assert_eq!(p_style.font_size, 16.0); + } + + #[test] + fn specificity_beats_source_order() { + let style = style_of( + "<p class=\"a\">x</p>", + &["p { color: red } .a { color: blue }"], + "p", + ); + assert_eq!(style.color, Rgba::opaque(0, 0, 255)); + } + + #[test] + fn source_order_breaks_ties() { + let style = style_of( + "<p class=\"a\">x</p>", + &[".a { color: blue } p.a { color: red }"], + "p", + ); + assert_eq!(style.color, Rgba::opaque(255, 0, 0)); + } + + #[test] + fn important_beats_specificity() { + let style = style_of( + "<p class=\"a\">x</p>", + &["p.a { color: red } p { color: blue !important }"], + "p", + ); + assert_eq!(style.color, Rgba::opaque(0, 0, 255)); + } + + #[test] + fn inline_style_ordering() { + // 内联普通声明压过样式表普通声明 + let style = style_of("<p style=\"color: red\">x</p>", &["p { color: blue }"], "p"); + assert_eq!(style.color, Rgba::opaque(255, 0, 0)); + + // 样式表 !important 压过内联普通声明 + let style = style_of( + "<p style=\"color: red\">x</p>", + &["p { color: blue !important }"], + "p", + ); + assert_eq!(style.color, Rgba::opaque(0, 0, 255)); + + // 内联 !important 压过样式表 !important + let style = style_of( + "<p style=\"color: red !important\">x</p>", + &["p { color: blue !important }"], + "p", + ); + assert_eq!(style.color, Rgba::opaque(255, 0, 0)); + } + + #[test] + fn matching_rule_selectors_use_max_specificity() { + let style = style_of( + "<p class=\"x\">x</p>", + &["p, .x { color: red } p { color: blue }"], + "p", + ); + assert_eq!(style.color, Rgba::opaque(255, 0, 0)); + } + + #[test] + fn font_size_resolves_against_parent() { + // em / 百分比相对父元素计算字号 + let mut document = build_document( + "<div style=\"font-size: 20px\"><p style=\"font-size: 1.5em\">x</p></div>", + ); + let parsed = Stylesheet::parse(""); + let div = find_first_by_name(&document, "div").expect("div"); + let div_style = cascade(&document, div, &[&parsed], None, None); + assert_eq!(div_style.font_size, 20.0); + let p = find_first_by_name(&document, "p").expect("p"); + let p_style = cascade(&document, p, &[&parsed], None, Some(&div_style)); + assert_eq!(p_style.font_size, 30.0); + + // 继承的是计算值:孙辈再乘 em 时基于 30px + let span = document.create_node(nexty_dom::NodeKind::Element(nexty_dom::ElementData { + name: "span".into(), + namespace: nexty_dom::Namespace::Html, + attributes: Vec::new(), + })); + document.insert_node(span, p, None); + let span_style = cascade(&document, span, &[&parsed], None, Some(&p_style)); + assert_eq!(span_style.font_size, 30.0, "继承计算字号而非声明值"); + } + + #[test] + fn font_size_keywords_and_relative() { + let style = style_of("<p>x</p>", &["p { font-size: x-large }"], "p"); + assert_eq!(style.font_size, 24.0); + + // larger:父字号在表内时取下一项 + let document = build_document( + "<div style=\"font-size: large\"><p style=\"font-size: larger\">x</p></div>", + ); + let parsed = Stylesheet::parse(""); + let div_style = cascade( + &document, + find_first_by_name(&document, "div").unwrap(), + &[&parsed], + None, + None, + ); + let p_style = cascade( + &document, + find_first_by_name(&document, "p").unwrap(), + &[&parsed], + None, + Some(&div_style), + ); + assert_eq!( + p_style.font_size, + MEDIUM_FONT_SIZE * 1.5, + "large(1.2) → larger(1.5)" + ); + + // 表外字号用 1.2 比例 + let document = build_document( + "<div style=\"font-size: 100px\"><p style=\"font-size: smaller\">x</p></div>", + ); + let div_style = cascade( + &document, + find_first_by_name(&document, "div").unwrap(), + &[&parsed], + None, + None, + ); + let p_style = cascade( + &document, + find_first_by_name(&document, "p").unwrap(), + &[&parsed], + None, + Some(&div_style), + ); + assert!((p_style.font_size - 100.0 / 1.2).abs() < 1e-4); + } + + #[test] + fn font_weight_relative_table() { + // CSS Fonts 4 §2.2.1 映射表 + let cases: [(f32, &str, f32); 6] = [ + (50.0, "bolder", 400.0), + (200.0, "bolder", 400.0), + (400.0, "bolder", 700.0), + (600.0, "bolder", 900.0), + (950.0, "bolder", 950.0), + (950.0, "lighter", 700.0), + ]; + for (parent_weight, keyword, expected) in cases { + let document = build_document(&format!( + "<div style=\"font-weight: {parent_weight}\"><p style=\"font-weight: {keyword}\">x</p></div>" + )); + let parsed = Stylesheet::parse(""); + let div_style = cascade( + &document, + find_first_by_name(&document, "div").unwrap(), + &[&parsed], + None, + None, + ); + assert_eq!(div_style.font_weight, parent_weight); + let p_style = cascade( + &document, + find_first_by_name(&document, "p").unwrap(), + &[&parsed], + None, + Some(&div_style), + ); + assert_eq!( + p_style.font_weight, expected, + "{keyword} from {parent_weight}" + ); + } + } + + #[test] + fn css_wide_keywords() { + // inherit:无父元素 → initial + let style = style_of("<p style=\"color: inherit\">x</p>", &[], "p"); + assert_eq!(style.color, Rgba::opaque(0, 0, 0)); + + // unset:继承属性取父值 + let document = + build_document("<div style=\"color: red\"><p style=\"color: unset\">x</p></div>"); + let parsed = Stylesheet::parse(""); + let div_style = cascade( + &document, + find_first_by_name(&document, "div").unwrap(), + &[&parsed], + None, + None, + ); + let p_style = cascade( + &document, + find_first_by_name(&document, "p").unwrap(), + &[&parsed], + None, + Some(&div_style), + ); + assert_eq!(p_style.color, Rgba::opaque(255, 0, 0)); + + // unset:非继承属性取 initial + let style = style_of( + "<p style=\"background-color: unset\" class=\"x\">x</p>", + &["p.x { background-color: red }"], + "p", + ); + assert_eq!(style.background_color, Rgba::transparent()); + + // initial:显式回到 initial + let style = style_of( + "<p style=\"color: initial\">x</p>", + &["p { color: red }"], + "p", + ); + assert_eq!(style.color, Rgba::opaque(0, 0, 0)); + + // revert:回退到 UA origin(本层无 UA 声明 → initial) + let style = style_of( + "<p style=\"color: revert\">x</p>", + &["p { color: red }"], + "p", + ); + assert_eq!(style.color, Rgba::opaque(0, 0, 0)); + } + + #[test] + fn document_styles_walk_parents_first() { + let document = + build_document("<body><div style=\"color: red\"><p><em>x</em></p></div></body>"); + let sheet = Stylesheet::parse("em { font-style: italic }"); + let styles = compute_document_styles(&document, &[&sheet], None); + + let div = find_first_by_name(&document, "div").expect("div"); + let p = find_first_by_name(&document, "p").expect("p"); + let em = find_first_by_name(&document, "em").expect("em"); + + assert_eq!(styles[&div].color, Rgba::opaque(255, 0, 0)); + assert_eq!(styles[&p].color, Rgba::opaque(255, 0, 0), "p 继承 div"); + assert_eq!(styles[&em].color, Rgba::opaque(255, 0, 0), "em 继承 p"); + assert_eq!( + styles[&em].font_style, + FontStyleValue::Italic, + "样式表命中 em" + ); + // body 自身也在结果里 + let body = find_first_by_name(&document, "body").expect("body"); + assert_eq!(styles[&body].font_style, FontStyleValue::Normal); + } + + #[test] + fn multiple_stylesheets_cascade_in_order() { + let document = build_document("<p>x</p>"); + let first = Stylesheet::parse("p { color: red }"); + let second = Stylesheet::parse("p { color: blue }"); + let style = cascade( + &document, + find_first_by_name(&document, "p").unwrap(), + &[&first, &second], + None, + None, + ); + assert_eq!(style.color, Rgba::opaque(0, 0, 255), "后传入的样式表胜出"); + } + + #[test] + fn where_has_zero_specificity_is_takes_argument_max() { + // Selectors 4::where() 特异度为 0;:is() 取参数中的最大特异度 + let document = build_document("<p id=\"a\" class=\"x\">x</p>"); + let sheet = Stylesheet::parse( + "p { color: red } :where(p.x) { color: blue } :is(#a) { color: green }", + ); + let style = cascade( + &document, + find_first_by_name(&document, "p").unwrap(), + &[&sheet], + None, + None, + ); + // :is(#a) 特异度 (1,0,0) 压过其余两条 + assert_eq!(style.color, Rgba::opaque(0, 128, 0)); + + let sheet = Stylesheet::parse("p { color: red } :where(p.x) { color: blue }"); + let style = cascade( + &document, + find_first_by_name(&document, "p").unwrap(), + &[&sheet], + None, + None, + ); + // :where(p.x) 特异度为 0,p (0,0,1) 按源顺序在后仍胜出 + assert_eq!(style.color, Rgba::opaque(255, 0, 0)); + } + + #[test] + fn ua_origin_ordering_matches_cascade_5() { + let ua_block = Stylesheet::parse("div { display: block }"); + let ua_important_none = Stylesheet::parse("div { display: none !important }"); + let div = || build_document("<div>x</div>"); + + // UA normal < author normal + let document = div(); + let author = Stylesheet::parse("div { display: inline }"); + let style = cascade( + &document, + find_first_by_name(&document, "div").unwrap(), + &[], + Some(&ua_block), + None, + ); + assert_eq!( + style.display, + DisplayValue::Block, + "无 author 声明时 UA 生效" + ); + let style = cascade( + &document, + find_first_by_name(&document, "div").unwrap(), + &[&author], + Some(&ua_block), + None, + ); + assert_eq!( + style.display, + DisplayValue::Inline, + "author normal 压过 UA normal" + ); + + // author normal < author important < UA important + let document = div(); + let author_normal = Stylesheet::parse("div { display: block }"); + let style = cascade( + &document, + find_first_by_name(&document, "div").unwrap(), + &[&author_normal], + Some(&ua_important_none), + None, + ); + assert_eq!( + style.display, + DisplayValue::None, + "UA !important 压过 author normal" + ); + + let document = div(); + let author_important = Stylesheet::parse("div { display: block !important }"); + let style = cascade( + &document, + find_first_by_name(&document, "div").unwrap(), + &[&author_important], + Some(&ua_important_none), + None, + ); + assert_eq!( + style.display, + DisplayValue::None, + "UA !important 压过 author !important" + ); + } + + #[test] + fn html_ua_stylesheet_provides_rendering_defaults() { + let document = + build_document("<div><p>x</p></div><head></head><ul><li>item</li></ul><b>bold</b>"); + let styles = compute_document_styles(&document, &[], Some(html_ua_stylesheet())); + let display_of = |name: &str| { + let node = find_first_by_name(&document, name).expect(name); + styles[&node].display + }; + assert_eq!(display_of("div"), DisplayValue::Block); + assert_eq!(display_of("p"), DisplayValue::Block); + assert_eq!(display_of("head"), DisplayValue::None); + assert_eq!(display_of("li"), DisplayValue::ListItem); + assert_eq!( + display_of("b"), + DisplayValue::Inline, + "未列入 UA 表的元素保持 initial" + ); + + // author normal 声明覆盖 UA 默认 margin + let sheet = Stylesheet::parse("body { margin: 0 }"); + let styles = compute_document_styles(&document, &[&sheet], Some(html_ua_stylesheet())); + let body = find_first_by_name(&document, "body").expect("body"); + assert_eq!( + styles[&body].margin, + crate::Edges::splat(MarginValue::Length(0.0)) + ); + } + + #[test] + fn border_width_folds_style_and_currentcolor_resolves() { + // style 缺省为 none → computed 宽度 0(CSS 2.1 §8.5.4) + let style = style_of("<p>x</p>", &["p { border: 4px }"], "p"); + assert_eq!(style.border_width, Edges::splat(0.0)); + assert_eq!(style.border_style, Edges::splat(BorderStyle::None)); + + // style 可见 → 宽度生效;currentcolor 按本元素 color 解析 + let style = style_of( + "<p>x</p>", + &[ + "p { border: 2px solid; color: red; border-top-color: currentcolor; border-left-color: green }", + ], + "p", + ); + assert_eq!(style.border_width, Edges::splat(2.0)); + assert_eq!(style.border_style.top, BorderStyle::Solid); + assert_eq!( + style.border_color.top, + Rgba::opaque(255, 0, 0), + "currentcolor" + ); + assert_eq!(style.border_color.left, Rgba::opaque(0, 128, 0)); + assert_eq!( + style.border_color.bottom, + Rgba::opaque(255, 0, 0), + "border 简写缺省 color = currentcolor" + ); + } + + #[test] + fn line_height_computes_percent_and_em_to_absolute() { + let style = style_of( + "<p>x</p>", + &["p { font-size: 20px; line-height: 150% }"], + "p", + ); + assert_eq!(style.line_height, LineHeightValue::Length(30.0)); + + let style = style_of( + "<p>x</p>", + &["p { font-size: 20px; line-height: 1.2em }"], + "p", + ); + assert_eq!(style.line_height, LineHeightValue::Length(24.0)); + + // 数值保持数值:无单位数值按数值继承 + let document = build_document( + "<div style=\"font-size: 10px; line-height: 2\"><p style=\"font-size: 20px\">x</p></div>", + ); + let parsed = Stylesheet::parse(""); + let div = find_first_by_name(&document, "div").expect("div"); + let div_style = cascade(&document, div, &[&parsed], None, None); + let p = find_first_by_name(&document, "p").expect("p"); + let p_style = cascade(&document, p, &[&parsed], None, Some(&div_style)); + assert_eq!(div_style.line_height, LineHeightValue::Number(2.0)); + assert_eq!( + p_style.line_height, + LineHeightValue::Number(2.0), + "数值 line-height 以数值继承,不随父字号折算" + ); + } + + #[test] + fn box_model_properties_reach_computed_style() { + let style = style_of( + "<p style=\"margin: 10px 20%; padding: 5px; width: 300px; height: 50%\">x</p>", + &[], + "p", + ); + assert_eq!( + style.margin, + Edges { + top: MarginValue::Length(10.0), + right: MarginValue::Percent(0.2), + bottom: MarginValue::Length(10.0), + left: MarginValue::Percent(0.2), + } + ); + assert_eq!(style.padding, Edges::splat(PaddingValue::Length(5.0))); + assert_eq!(style.width, SizeValue::Length(300.0)); + assert_eq!(style.height, SizeValue::Percent(0.5)); + } + + #[test] + fn layout_properties_reach_computed_style() { + let style = style_of( + "<div style=\"position: absolute; top: 10px; right: 20%; bottom: auto; left: 5px;\ + flex-direction: column; flex-wrap: wrap; flex-shrink: 2;\ + align-items: center; justify-content: space-between; align-self: flex-end;\ + row-gap: 8px; column-gap: 4px; grid-auto-flow: row dense;\ + grid-template-columns: 100px 1fr; grid-template-rows: auto\">x</div>", + &[], + "div", + ); + assert_eq!(style.position, PositionValue::Absolute); + assert_eq!( + style.inset, + Edges { + top: InsetValue::Length(10.0), + right: InsetValue::Percent(0.2), + bottom: InsetValue::Auto, + left: InsetValue::Length(5.0), + } + ); + assert_eq!(style.flex_direction, FlexDirectionValue::Column); + assert_eq!(style.flex_wrap, FlexWrapValue::Wrap); + assert_eq!(style.flex_shrink, 2.0); + assert_eq!(style.align_items, AlignItemsValue::Center); + assert_eq!(style.justify_content, JustifyContentValue::SpaceBetween); + assert_eq!(style.align_self, AlignSelfValue::FlexEnd); + assert_eq!(style.row_gap, GapValue::Length(8.0)); + assert_eq!(style.column_gap, GapValue::Length(4.0)); + assert_eq!(style.grid_auto_flow, GridAutoFlowValue::RowDense); + assert_eq!( + style.grid_template_columns, + GridTrackList { + tracks: vec![GridTrack::Length(100.0), GridTrack::Fr(1.0)] + } + ); + assert_eq!( + style.grid_template_rows, + GridTrackList { + tracks: vec![GridTrack::Auto] + } + ); + } +} diff --git a/crates/nexty-css/.mimosa/hook-state/sess_ca7e797f-14f7-4cd4-a65e-6a69d7418103.mv37y1v5-51660-adb7c830c0.baseline/2e9d962a08321605940b5a657135052fbcef87b5e360662bb527c96d9a615542.source b/crates/nexty-css/.mimosa/hook-state/sess_ca7e797f-14f7-4cd4-a65e-6a69d7418103.mv37y1v5-51660-adb7c830c0.baseline/2e9d962a08321605940b5a657135052fbcef87b5e360662bb527c96d9a615542.source new file mode 100644 index 0000000..a73d4be --- /dev/null +++ b/crates/nexty-css/.mimosa/hook-state/sess_ca7e797f-14f7-4cd4-a65e-6a69d7418103.mv37y1v5-51660-adb7c830c0.baseline/2e9d962a08321605940b5a657135052fbcef87b5e360662bb527c96d9a615542.source @@ -0,0 +1,31 @@ +[package] +name = "nexty-css" +description = "Nexty CSS 层:解析与选择器匹配复用 cssparser/selectors,cascade 自研" +version = "0.1.8" +edition.workspace = true +license.workspace = true +repository.workspace = true +rust-version.workspace = true + +[features] +# 默认开启全部已实现能力;下游(nexty-layout / nexty-chrome)依赖默认即可。 +default = ["values", "selectors", "stylesheets", "cascade", "ua-stylesheet"] +# 属性值模型与逐属性解析(value 模块),依赖 cssparser。 +values = ["dep:cssparser"] +# 选择器解析与 arena DOM 匹配(selector 模块),依赖 selectors 与 nexty-dom。 +selectors = ["dep:cssparser", "dep:selectors", "dep:nexty-dom", "dep:precomputed-hash"] +# 样式表与声明块解析(parser 模块),依赖选择器与属性值模型。 +stylesheets = ["values", "selectors"] +# 自研 cascade 与 computed style(cascade 模块)。 +cascade = ["values", "selectors", "stylesheets", "dep:nexty-dom"] +# UA 默认样式表(ua 模块),依赖样式表解析。 +ua-stylesheet = ["stylesheets"] + +[dependencies] +cssparser = { version = "0.38.0", optional = true } +precomputed-hash = { version = "0.1.1", optional = true } +nexty-dom = { path = "../nexty-dom", version = "0.1.0", optional = true } +selectors = { version = "0.41.0", optional = true } + +[dev-dependencies] +nexty-html = { path = "../nexty-html", version = "0.1.0" } diff --git a/crates/nexty-css/.mimosa/hook-state/sess_ca7e797f-14f7-4cd4-a65e-6a69d7418103.mv37y1v5-51660-adb7c830c0.baseline/4a04259da480a6b794a2e947e4cc03eff4d1aa9330836f5b91cac68c5398193f.source b/crates/nexty-css/.mimosa/hook-state/sess_ca7e797f-14f7-4cd4-a65e-6a69d7418103.mv37y1v5-51660-adb7c830c0.baseline/4a04259da480a6b794a2e947e4cc03eff4d1aa9330836f5b91cac68c5398193f.source new file mode 100644 index 0000000..605eeab --- /dev/null +++ b/crates/nexty-css/.mimosa/hook-state/sess_ca7e797f-14f7-4cd4-a65e-6a69d7418103.mv37y1v5-51660-adb7c830c0.baseline/4a04259da480a6b794a2e947e4cc03eff4d1aa9330836f5b91cac68c5398193f.source @@ -0,0 +1,1435 @@ +//! 样式表解析:`cssparser` 的语法引擎 + 逐属性值解析。 +//! +//! 行为 ground truth:[CSS Syntax Module Level 3 §5](https://drafts.csswg.org/css-syntax-3/#parsing)。 +//! +//! - 顶层按 rule list 消费:样式规则(qualified rule)产出 [`StyleRule`], +//! at-rule 由 cssparser 按规范错误恢复整块跳过(§5.4);文档开头 +//! 的 `@charset` 自动忽略。 +//! - 样式规则 prelude 是选择器列表:任一选择器无效 → 整条规则丢弃(§5.3.2)。 +//! - 声明块逐条解析:单条声明无效只丢弃该条,其余保留(§5.5)。 +//! - 未知属性按无效声明处理;未知 at-rule(`@import` / `@supports` / …)整块跳过。 +//! - `@media` 按视口条件求值([`Stylesheet::parse_with_viewport`]):命中的 +//! 规则按源顺序就地展开参与级联,未命中或未提供视口的整块丢弃。 +//! +//! 已知偏差:`@supports` 等其余 at-rule 不求值(整体跳过);媒体特性只认 +//! `min/max-width/height`(px);嵌套 `@media` 不支持。 +//! +//! **Feature**:本模块受 `stylesheets` feature 控制(由 lib.rs 装配)。`StyleRule` +//! 的 `selectors` / `specificity` 字段由 `cascade` 模块读取,故关闭 cascade 时 +//! 它们暂无读取方——此时按模块整体抑制 dead_code。 + +#![cfg_attr(not(feature = "cascade"), allow(dead_code))] + +use crate::selector::{NextySelector, parse_selector_list}; +use crate::value::{ + BorderColorValue, BorderStyle, BorderWidthValue, DeclaredValue, PropertyId, PropertyValue, + parse_border_color_value, parse_border_style_value, parse_border_width_value, + parse_css_wide_keyword, parse_declared_value, parse_font_shorthand, parse_gap_value, + parse_inset_value, parse_margin_value, parse_padding_value, +}; +use cssparser::{ + AtRuleParser, DeclarationParser, ParseError, Parser, QualifiedRuleParser, RuleBodyItemParser, + RuleBodyParser, StyleSheetParser, Token, +}; + +/// 一份已解析的样式表,规则保持源顺序。 +#[derive(Debug, Clone, Default)] +pub struct Stylesheet { + rules: Vec<StyleRule>, +} + +/// `@media` 求值的视口条件(CSS px)。 +#[derive(Debug, Clone, Copy, PartialEq)] +pub struct MediaViewport { + /// 视口宽。 + pub width: f32, + /// 视口高。 + pub height: f32, +} + +impl Stylesheet { + /// 解析样式表文本。 + /// + /// 输入按 UTF-8 处理(调用方负责按 HTTP/文档编码解码)。解析错误按 + /// CSS Syntax §5 的恢复规则就地吞掉:无效的规则与声明不会出现在结果里, + /// 也不上报。`@media` 整块跳过(未提供求值条件)。 + #[must_use] + pub fn parse(css: &str) -> Stylesheet { + Self::parse_inner(css, None) + } + + /// 解析样式表文本并按视口条件求值 `@media`。 + /// + /// 命中的 `@media` 内层规则按源顺序就地展开参与级联;未命中的整块丢弃 + /// (CSS Conditional 3:不匹配的 condition 不贡献任何规则)。 + #[must_use] + pub fn parse_with_viewport(css: &str, viewport: MediaViewport) -> Stylesheet { + Self::parse_inner(css, Some(viewport)) + } + + fn parse_inner(css: &str, viewport: Option<MediaViewport>) -> Stylesheet { + let mut rule_parser = StylesheetRuleParser { viewport }; + let mut input = Parser::new(css); + let mut rules = Vec::new(); + // at-rule 产出的是规则组(@media 展开),普通规则是单元素组 + for group in StyleSheetParser::new(&mut input, &mut rule_parser).flatten() { + rules.extend(group); + } + Stylesheet { rules } + } + + /// 按源顺序返回全部样式规则。 + #[must_use] + pub fn rules(&self) -> &[StyleRule] { + &self.rules + } +} + +/// 一条样式规则:选择器列表 + 声明块。 +#[derive(Debug, Clone)] +pub struct StyleRule { + selectors: Vec<NextySelector>, + selector_text: String, + declarations: Vec<Declaration>, +} + +impl StyleRule { + /// 规则的选择器文本(序列化形式,与源文本等价但可能经过规范化)。 + #[must_use] + pub fn selector_text(&self) -> &str { + &self.selector_text + } + + /// 声明列表(保持源顺序)。 + #[must_use] + pub fn declarations(&self) -> &[Declaration] { + &self.declarations + } + + /// 供 cascade 使用的已解析选择器(含逐条特异度)。 + pub(crate) fn selectors(&self) -> &[NextySelector] { + &self.selectors + } +} + +/// 一条属性声明。 +#[derive(Debug, Clone, PartialEq)] +pub struct Declaration { + /// 属性。 + pub property: PropertyId, + /// 解析后的声明值。 + pub value: DeclaredValue, + /// 是否带 `!important`。 + pub important: bool, +} + +/// 顶层样式表规则解析:接受样式规则与 `@media`(带视口条件时求值)。 +struct StylesheetRuleParser { + /// `@media` 求值条件;`None` 时 `@media` 不命中(整块丢弃)。 + viewport: Option<MediaViewport>, +} + +impl<'i> QualifiedRuleParser<'i> for StylesheetRuleParser { + type Prelude = Vec<NextySelector>; + type QualifiedRule = Vec<StyleRule>; + type Error = (); + + fn parse_prelude( + &mut self, + input: &mut Parser<'i>, + ) -> Result<Self::Prelude, ParseError<Self::Error>> { + parse_selector_list(input).map_err(|_| ParseError::<()>::unexpected_token()) + } + + fn parse_block<'t>( + &mut self, + prelude: Self::Prelude, + _start: &cssparser::ParserState, + input: &mut Parser<'i>, + ) -> Result<Self::QualifiedRule, ParseError<Self::Error>> { + let selector_text = prelude + .iter() + .map(NextySelector::to_css_string) + .collect::<Vec<_>>() + .join(", "); + Ok(vec![StyleRule { + selectors: prelude, + selector_text, + declarations: parse_declaration_block(input), + }]) + } +} + +// 未知 at-rule(@import / @supports / …)走默认拒绝, +// StyleSheetParser 按规范把整块消费掉。 +impl<'i> AtRuleParser<'i> for StylesheetRuleParser { + type Prelude = MediaQuery; + type AtRule = Vec<StyleRule>; + type Error = (); + + fn parse_prelude( + &mut self, + name: cssparser::CowRcStr<'i>, + input: &mut Parser<'i>, + ) -> Result<Self::Prelude, ParseError<Self::Error>> { + if name.eq_ignore_ascii_case("media") { + parse_media_query(input).ok_or_else(ParseError::<()>::unexpected_token) + } else { + Err(ParseError::unexpected_token()) + } + } + + fn parse_block<'t>( + &mut self, + prelude: Self::Prelude, + _start: &cssparser::ParserState, + input: &mut Parser<'i>, + ) -> Result<Self::AtRule, ParseError<Self::Error>> { + // 内层按 rule list 解析(块必须整体消费后再决定去留); + // 嵌套 at-rule 在内层解析器里按未知拒绝 + let mut inner = MediaQueryRuleParser; + let mut rules = Vec::new(); + for group in RuleBodyParser::new(input, &mut inner).flatten() { + rules.extend(group); + } + let matched = match self.viewport { + Some(viewport) => prelude.matches(viewport), + None => false, + }; + Ok(if matched { rules } else { Vec::new() }) + } +} + +/// `@media` 块内层规则解析:只接受样式规则,声明与嵌套 at-rule 拒绝。 +struct MediaQueryRuleParser; + +impl<'i> DeclarationParser<'i> for MediaQueryRuleParser { + type Declaration = Vec<StyleRule>; + type Error = (); +} + +impl<'i> QualifiedRuleParser<'i> for MediaQueryRuleParser { + type Prelude = Vec<NextySelector>; + type QualifiedRule = Vec<StyleRule>; + type Error = (); + + fn parse_prelude( + &mut self, + input: &mut Parser<'i>, + ) -> Result<Self::Prelude, ParseError<Self::Error>> { + parse_selector_list(input).map_err(|_| ParseError::<()>::unexpected_token()) + } + + fn parse_block<'t>( + &mut self, + prelude: Self::Prelude, + _start: &cssparser::ParserState, + input: &mut Parser<'i>, + ) -> Result<Self::QualifiedRule, ParseError<Self::Error>> { + let selector_text = prelude + .iter() + .map(NextySelector::to_css_string) + .collect::<Vec<_>>() + .join(", "); + Ok(vec![StyleRule { + selectors: prelude, + selector_text, + declarations: parse_declaration_block(input), + }]) + } +} + +// 嵌套 at-rule(@media 内再套 @media / @supports 等)不支持,默认拒绝。 +impl<'i> AtRuleParser<'i> for MediaQueryRuleParser { + type Prelude = (); + type AtRule = Vec<StyleRule>; + type Error = (); +} + +impl<'i> RuleBodyItemParser<'i, Vec<StyleRule>, ()> for MediaQueryRuleParser { + // @media 块内不解析声明(顶层声明本身非法),只解析样式规则 + fn parse_declarations(&self) -> bool { + false + } + + fn parse_qualified(&self) -> bool { + true + } +} + +/// 一条媒体查询的解析结果(CSS Conditional 3 §3 / CSS3 Media Queries 语法子集)。 +#[derive(Debug)] +struct MediaQuery { + /// 查询是否合法;非法查询按 "not all" 处理(恒不命中)。 + valid: bool, + /// `not` 前缀:命中条件取反。 + negate: bool, + /// 媒体类型是否可接受(空 / all / screen)。 + type_ok: bool, + /// `and` 连接的特性条件。 + features: Vec<MediaFeature>, +} + +impl MediaQuery { + /// 该查询在给定视口下是否命中。 + fn matches(&self, viewport: MediaViewport) -> bool { + let matched = self.valid + && self.type_ok + && self + .features + .iter() + .all(|feature| feature.matches(viewport)); + if self.negate { !matched } else { matched } + } +} + +/// 单个媒体特性:min/max-width/height(px)。 +#[derive(Debug, Clone, Copy, PartialEq)] +enum MediaFeature { + MinWidth(f32), + MaxWidth(f32), + MinHeight(f32), + MaxHeight(f32), +} + +impl MediaFeature { + fn matches(&self, viewport: MediaViewport) -> bool { + match *self { + MediaFeature::MinWidth(value) => viewport.width >= value, + MediaFeature::MaxWidth(value) => viewport.width <= value, + MediaFeature::MinHeight(value) => viewport.height >= value, + MediaFeature::MaxHeight(value) => viewport.height <= value, + } + } +} + +/// 解析 `@media` 的 prelude:`[only | not]? <type>? [and <expression>]*`。 +/// +/// 不认识的前缀 / 类型 / 特性 → `None`(整条规则丢弃,CSS Conditional 3: +/// 未知查询等价 `not all`)。 +fn parse_media_query(input: &mut Parser<'_>) -> Option<MediaQuery> { + let mut query = MediaQuery { + valid: true, + negate: false, + type_ok: true, + features: Vec::new(), + }; + let mut expect_expression = false; + + loop { + let token = match input.next() { + Ok(token) => token, + // EOF:查询正常结束 + Err(_) => return Some(query), + }; + match token { + Token::Ident(name) if name.eq_ignore_ascii_case("only") => {} + Token::Ident(name) if name.eq_ignore_ascii_case("not") => query.negate = true, + Token::Ident(name) if name.eq_ignore_ascii_case("and") => { + if !expect_expression { + return None; // and 出现在不该出现的位置 + } + expect_expression = false; + } + Token::Ident(name) => { + // 媒体类型:空缺视为 all;print/speech 等不命中。 + // 类型之后允许 `and <expression>` + query.type_ok = + name.eq_ignore_ascii_case("all") || name.eq_ignore_ascii_case("screen"); + expect_expression = true; + } + Token::Function(_) => return None, + Token::ParenthesisBlock => { + let feature = input + .parse_nested_block(|input| { + parse_media_feature(input).map_err(|_| ParseError::<()>::unexpected_token()) + }) + .ok()?; + query.features.push(feature); + expect_expression = true; + } + _ => return None, + } + } +} + +/// 解析一个媒体特性表达式:`(min-width: 400px)` 等。 +fn parse_media_feature(input: &mut Parser<'_>) -> Result<MediaFeature, ()> { + let name = match input.next().map_err(|_| ())? { + Token::Ident(name) => name.to_string(), + _ => return Err(()), + }; + input.expect_colon().map_err(|_| ())?; + let value = match input.next().map_err(|_| ())? { + // px 数值;无单位数字按 px(CSS 层面其实不允许,宽松处理) + Token::Dimension { value, unit, .. } if unit.eq_ignore_ascii_case("px") => *value, + Token::Number { value, .. } => *value, + _ => return Err(()), + }; + input.expect_exhausted().map_err(|_| ())?; + if name.eq_ignore_ascii_case("min-width") { + Ok(MediaFeature::MinWidth(value)) + } else if name.eq_ignore_ascii_case("max-width") { + Ok(MediaFeature::MaxWidth(value)) + } else if name.eq_ignore_ascii_case("min-height") { + Ok(MediaFeature::MinHeight(value)) + } else if name.eq_ignore_ascii_case("max-height") { + Ok(MediaFeature::MaxHeight(value)) + } else { + Err(()) + } +} + +/// 解析一个声明块(`{ ... }` 内容或内联 style 属性值)。 +/// +/// 无效声明(含未知属性)就地跳过,其余保留(CSS Syntax §5.5)。 +pub(crate) fn parse_declaration_block(input: &mut Parser<'_>) -> Vec<Declaration> { + let mut declaration_parser = DeclarationListParser; + let mut declarations = Vec::new(); + for group in RuleBodyParser::new(input, &mut declaration_parser).flatten() { + declarations.extend(group); + } + declarations +} + +/// 解析一段内联 style 属性为声明列表。 +#[must_use] +pub fn parse_inline_style(style_attribute: &str) -> Vec<Declaration> { + let mut input = Parser::new(style_attribute); + parse_declaration_block(&mut input) +} + +/// 声明块内容解析器:只接受声明,拒绝嵌套规则与 at-rule。 +/// +/// 一条声明可展开为多条(简写属性按 CSS Cascade 5 §8 展开为 longhand, +/// 保持书写顺序)。 +struct DeclarationListParser; + +/// [`DeclarationParser::Declaration`] 的承载类型:一条简写可产出多条声明。 +type DeclarationGroup = Vec<Declaration>; + +impl<'i> DeclarationParser<'i> for DeclarationListParser { + type Declaration = DeclarationGroup; + type Error = (); + + fn parse_value<'t>( + &mut self, + name: cssparser::CowRcStr<'i>, + input: &mut Parser<'i>, + _declaration_start: &cssparser::ParserState, + ) -> Result<DeclarationGroup, ParseError<Self::Error>> { + // 简写属性:展开为 longhand(CSS Cascade 5 §8 shorthand expansion) + if let Some(expanded) = expand_shorthand(&name, input) { + let (values, important) = expanded.map_err(|_| ParseError::<()>::unexpected_token())?; + return Ok(values + .into_iter() + .map(|(property, value)| Declaration { + property, + value, + important, + }) + .collect()); + } + let Some(property) = PropertyId::from_name(&name) else { + // 未知属性(含 custom property)按无效声明处理 + return Err(ParseError::<()>::unexpected_token()); + }; + let (value, important) = parse_declared_value(property, input) + .map_err(|_| ParseError::<()>::unexpected_token())?; + Ok(vec![Declaration { + property, + value, + important, + }]) + } +} + +impl<'i> QualifiedRuleParser<'i> for DeclarationListParser { + type Prelude = (); + type QualifiedRule = DeclarationGroup; + type Error = (); +} + +impl<'i> AtRuleParser<'i> for DeclarationListParser { + type Prelude = (); + type AtRule = DeclarationGroup; + type Error = (); +} + +impl<'i> RuleBodyItemParser<'i, DeclarationGroup, ()> for DeclarationListParser { + fn parse_declarations(&self) -> bool { + true + } + + fn parse_qualified(&self) -> bool { + false + } +} + +/// 简写展开结果:展开出的 (longhand, 值) 列表与 `!important` 标记。 +type ShorthandExpansion = (Vec<(PropertyId, DeclaredValue)>, bool); + +/// 简写属性展开(CSS Cascade 5 §8)。 +/// +/// 返回 `None` 表示 `name` 不是本层支持的简写;`Some(Err)` 表示简写值无效 +/// (整条声明丢弃)。CSS-wide 关键字作用于全部 longhand。 +fn expand_shorthand(name: &str, input: &mut Parser<'_>) -> Option<Result<ShorthandExpansion, ()>> { + // font 简写:缺省成分重置为 initial(CSS Fonts 4 §3.3),longhand 组见 + // font_longhands;small-caps / font-width 成分在值层接受后丢弃。 + if name.eq_ignore_ascii_case("font") { + if let Ok(keyword) = input.try_parse(parse_css_wide_keyword) { + let important = input.try_parse(cssparser::parse_important).is_ok(); + if input.expect_exhausted().is_err() { + return Some(Err(())); + } + return Some(Ok(( + font_longhands() + .into_iter() + .map(|property| (property, DeclaredValue::CssWide(keyword))) + .collect(), + important, + ))); + } + let expanded = parse_font_shorthand(input) + .map(|values| { + values + .into_iter() + .map(|(property, value)| (property, DeclaredValue::Typed(value))) + .collect::<Vec<_>>() + }) + .map_err(|_| ()); + let important = input.try_parse(cssparser::parse_important).is_ok(); + if input.expect_exhausted().is_err() { + return Some(Err(())); + } + return expanded.map(|declarations| (declarations, important)); + } + + // gap 简写:row-gap || column-gap(两值:行优先,缺省列取行)。 + if name.eq_ignore_ascii_case("gap") { + if let Ok(keyword) = input.try_parse(parse_css_wide_keyword) { + let important = input.try_parse(cssparser::parse_important).is_ok(); + if input.expect_exhausted().is_err() { + return Some(Err(())); + } + let longhands = [PropertyId::RowGap, PropertyId::ColumnGap]; + return Some(Ok(( + longhands + .into_iter() + .map(|property| (property, DeclaredValue::CssWide(keyword))) + .collect(), + important, + ))); + } + return Some(parse_gap_shorthand(input)); + } + + // 先确认是简写名,再试 CSS-wide 关键字(否则关键字会被误吞且不复位) + let is_border = name.eq_ignore_ascii_case("border"); + let edges = box_shorthand_edges(name); + if !is_border && edges.is_none() { + return None; + } + + if let Ok(keyword) = input.try_parse(parse_css_wide_keyword) { + let important = input.try_parse(cssparser::parse_important).is_ok(); + if input.expect_exhausted().is_err() { + return Some(Err(())); + } + let longhands = if is_border { + border_longhands() + } else { + match edges { + Some(BoxEdges::Margin) => margin_longhands(), + Some(BoxEdges::Padding) => padding_longhands(), + Some(BoxEdges::BorderWidth) => border_width_longhands(), + Some(BoxEdges::BorderStyle) => border_style_longhands(), + Some(BoxEdges::BorderColor) => border_color_longhands(), + Some(BoxEdges::Inset) => inset_longhands(), + None => border_longhands(), + } + }; + return Some(Ok(( + longhands + .into_iter() + .map(|property| (property, DeclaredValue::CssWide(keyword))) + .collect(), + important, + ))); + } + + if is_border { + return Some(parse_border_shorthand(input)); + } + let expanded = match edges? { + BoxEdges::Margin => expand_box_values(input, parse_margin_value) + .map(|values| zip_edges(values, margin_longhands(), PropertyValue::Margin)), + BoxEdges::Padding => expand_box_values(input, parse_padding_value) + .map(|values| zip_edges(values, padding_longhands(), PropertyValue::Padding)), + BoxEdges::BorderWidth => expand_box_values(input, parse_border_width_value) + .map(|values| zip_edges(values, border_width_longhands(), PropertyValue::BorderWidth)), + BoxEdges::BorderStyle => expand_box_values(input, parse_border_style_value) + .map(|values| zip_edges(values, border_style_longhands(), PropertyValue::BorderStyle)), + BoxEdges::BorderColor => expand_box_values(input, parse_border_color_value) + .map(|values| zip_edges(values, border_color_longhands(), PropertyValue::BorderColor)), + BoxEdges::Inset => expand_box_values(input, parse_inset_value) + .map(|values| zip_edges(values, inset_longhands(), PropertyValue::Inset)), + } + .ok()?; + let important = input.try_parse(cssparser::parse_important).is_ok(); + if input.expect_exhausted().is_err() { + return Some(Err(())); + } + Some(Ok((expanded, important))) +} + +/// 四边值与对应 longhand 组装为声明(统一包成 [`DeclaredValue::Typed`])。 +fn zip_edges<T>( + values: (T, T, T, T), + longhands: Vec<PropertyId>, + wrap: impl Fn(T) -> PropertyValue, +) -> Vec<(PropertyId, DeclaredValue)> { + let (top, right, bottom, left) = values; + [top, right, bottom, left] + .into_iter() + .zip(longhands) + .map(|(value, property)| (property, DeclaredValue::Typed(wrap(value)))) + .collect() +} + +/// 盒模型四边简写的属性组。 +#[derive(Debug, Clone, Copy)] +enum BoxEdges { + Margin, + Padding, + BorderWidth, + BorderStyle, + BorderColor, + Inset, +} + +fn box_shorthand_edges(name: &str) -> Option<BoxEdges> { + if name.eq_ignore_ascii_case("margin") { + Some(BoxEdges::Margin) + } else if name.eq_ignore_ascii_case("padding") { + Some(BoxEdges::Padding) + } else if name.eq_ignore_ascii_case("border-width") { + Some(BoxEdges::BorderWidth) + } else if name.eq_ignore_ascii_case("border-style") { + Some(BoxEdges::BorderStyle) + } else if name.eq_ignore_ascii_case("border-color") { + Some(BoxEdges::BorderColor) + } else if name.eq_ignore_ascii_case("inset") { + Some(BoxEdges::Inset) + } else { + None + } +} + +/// 1–4 值的盒模型展开(CSS 2.1 §8.3:顺时针 top → right → bottom → left)。 +fn expand_box_values<T: Clone>( + input: &mut Parser<'_>, + parse_one: impl Fn(&mut Parser<'_>) -> Result<T, ()>, +) -> Result<(T, T, T, T), ()> { + let top = parse_one(input)?; + let second = input.try_parse(|i| parse_one(i)).ok(); + let third = input.try_parse(|i| parse_one(i)).ok(); + let fourth = input.try_parse(|i| parse_one(i)).ok(); + match (second, third, fourth) { + (None, None, None) => Ok((top.clone(), top.clone(), top.clone(), top)), + (Some(horizontal), None, None) => Ok((top.clone(), horizontal.clone(), top, horizontal)), + (Some(horizontal), Some(bottom), None) => Ok((top, horizontal.clone(), bottom, horizontal)), + (Some(right), Some(bottom), Some(left)) => Ok((top, right, bottom, left)), + _ => Err(()), + } +} + +/// `border` 简写:`<line-width> || <line-style> || <color>`(任意顺序、 +/// 至少一项;缺省项取 initial:medium / none / currentcolor)。 +fn parse_border_shorthand( + input: &mut Parser<'_>, +) -> Result<(Vec<(PropertyId, DeclaredValue)>, bool), ()> { + let mut width = None; + let mut style = None; + let mut color = None; + loop { + if width.is_none() + && let Ok(value) = input.try_parse(parse_border_width_value) + { + width = Some(value); + continue; + } + if style.is_none() + && let Ok(value) = input.try_parse(parse_border_style_value) + { + style = Some(value); + continue; + } + if color.is_none() + && let Ok(value) = input.try_parse(parse_border_color_value) + { + color = Some(value); + continue; + } + break; + } + if width.is_none() && style.is_none() && color.is_none() { + return Err(()); + } + let important = input.try_parse(cssparser::parse_important).is_ok(); + if input.expect_exhausted().is_err() { + return Err(()); + } + + let width = width.unwrap_or(BorderWidthValue::Medium); + let style = style.unwrap_or(BorderStyle::None); + let color = color.unwrap_or(BorderColorValue::CurrentColor); + + let widths = border_width_longhands(); + let styles = border_style_longhands(); + let colors = border_color_longhands(); + let mut declarations = Vec::with_capacity(12); + for property in widths { + declarations.push(( + property, + DeclaredValue::Typed(PropertyValue::BorderWidth(width)), + )); + } + for property in styles { + declarations.push(( + property, + DeclaredValue::Typed(PropertyValue::BorderStyle(style)), + )); + } + for property in colors { + declarations.push(( + property, + DeclaredValue::Typed(PropertyValue::BorderColor(color)), + )); + } + Ok((declarations, important)) +} + +fn margin_longhands() -> Vec<PropertyId> { + vec![ + PropertyId::MarginTop, + PropertyId::MarginRight, + PropertyId::MarginBottom, + PropertyId::MarginLeft, + ] +} + +fn padding_longhands() -> Vec<PropertyId> { + vec![ + PropertyId::PaddingTop, + PropertyId::PaddingRight, + PropertyId::PaddingBottom, + PropertyId::PaddingLeft, + ] +} + +fn border_width_longhands() -> Vec<PropertyId> { + vec![ + PropertyId::BorderTopWidth, + PropertyId::BorderRightWidth, + PropertyId::BorderBottomWidth, + PropertyId::BorderLeftWidth, + ] +} + +fn border_style_longhands() -> Vec<PropertyId> { + vec![ + PropertyId::BorderTopStyle, + PropertyId::BorderRightStyle, + PropertyId::BorderBottomStyle, + PropertyId::BorderLeftStyle, + ] +} + +fn border_color_longhands() -> Vec<PropertyId> { + vec![ + PropertyId::BorderTopColor, + PropertyId::BorderRightColor, + PropertyId::BorderBottomColor, + PropertyId::BorderLeftColor, + ] +} + +/// `inset` 简写的四边 longhand(top / right / bottom / left)。 +fn inset_longhands() -> Vec<PropertyId> { + vec![ + PropertyId::Top, + PropertyId::Right, + PropertyId::Bottom, + PropertyId::Left, + ] +} + +/// `gap` 简写:`<row-gap> <column-gap>?`(CSS Box Alignment §6)。 +/// +/// 单值同时作用于行与列;双值行领先、列取第二项。`normal` 不是合法 gap 值, +/// 由 `parse_gap` 按无效声明丢弃。 +fn parse_gap_shorthand( + input: &mut Parser<'_>, +) -> Result<(Vec<(PropertyId, DeclaredValue)>, bool), ()> { + let row = parse_gap_value(input)?; + let column = input.try_parse(parse_gap_value).unwrap_or(row); + let important = input.try_parse(cssparser::parse_important).is_ok(); + if input.expect_exhausted().is_err() { + return Err(()); + } + Ok(( + vec![ + ( + PropertyId::RowGap, + DeclaredValue::Typed(PropertyValue::Gap(row)), + ), + ( + PropertyId::ColumnGap, + DeclaredValue::Typed(PropertyValue::Gap(column)), + ), + ], + important, + )) +} + +fn border_longhands() -> Vec<PropertyId> { + [ + border_width_longhands(), + border_style_longhands(), + border_color_longhands(), + ] + .concat() +} + +/// `font` 简写的 longhand 组(CSS Fonts 4 §3.3:简写重置全部子属性, +/// 故缺省成分也产声明、值取 initial)。 +fn font_longhands() -> Vec<PropertyId> { + vec![ + PropertyId::FontStyle, + PropertyId::FontWeight, + PropertyId::FontSize, + PropertyId::LineHeight, + PropertyId::FontFamily, + ] +} + +#[cfg(test)] +mod tests { + use super::*; + use crate::value::{ + BorderColorValue, BorderStyle, BorderWidthValue, CssWideKeyword, FontSizeValue, + LineHeightValue, MarginValue, PaddingValue, PropertyValue, Rgba, SizeValue, + }; + + fn rule_texts(sheet: &Stylesheet) -> Vec<&str> { + sheet.rules().iter().map(StyleRule::selector_text).collect() + } + + fn declaration_of(sheet: &Stylesheet, rule_index: usize, property: PropertyId) -> &Declaration { + sheet.rules()[rule_index] + .declarations() + .iter() + .find(|declaration| declaration.property == property) + .unwrap_or_else(|| panic!("missing declaration {property:?}")) + } + + #[test] + fn parses_rules_in_source_order() { + let sheet = + Stylesheet::parse("p { color: red; } .a { font-size: 16px } #b { display: none; }"); + assert_eq!(rule_texts(&sheet), vec!["p", ".a", "#b"]); + assert_eq!( + declaration_of(&sheet, 0, PropertyId::Color).value, + DeclaredValue::Typed(PropertyValue::Color(Rgba::opaque(255, 0, 0))) + ); + assert_eq!( + declaration_of(&sheet, 1, PropertyId::FontSize).value, + DeclaredValue::Typed(PropertyValue::FontSize(FontSizeValue::Px(16.0))) + ); + } + + #[test] + fn selector_list_keeps_rule_once_with_serialized_text() { + let sheet = Stylesheet::parse("h1, h2, .title { color: blue; }"); + assert_eq!(rule_texts(&sheet), vec!["h1, h2, .title"]); + } + + #[test] + fn invalid_selector_drops_whole_rule() { + // CSS Syntax §5.3.2:qualified rule prelude 无效 → 整条规则丢弃, + // 但后续规则不受影响 + let sheet = + Stylesheet::parse("p > { color: red } p { color: blue } , {} p b { display: none }"); + assert_eq!(rule_texts(&sheet), vec!["p", "p b"]); + } + + #[test] + fn at_rules_are_skipped_including_blocks() { + // @charset 由 StyleSheetParser 直接忽略;未知 at-rule 整块跳过。 + // 注意:顶层游离分号按现行 CSS Syntax §5.5.3 并入下一条 qualified rule + // 的 prelude("semicolons don't end them"),故这里用空白分隔规则。 + let sheet = Stylesheet::parse( + "@charset \"utf-8\";\ + @media screen { p { color: red } div { color: green } }\ + @import url(\"x.css\");\ + @unknown foo { p { color: pink } }\ + p { color: blue }", + ); + assert_eq!(rule_texts(&sheet), vec!["p"]); + assert_eq!( + declaration_of(&sheet, 0, PropertyId::Color).value, + DeclaredValue::Typed(PropertyValue::Color(Rgba::opaque(0, 0, 255))) + ); + } + + // ---- T7:@media 按视口求值(CSS Conditional 3) ---- + + /// 窄视口命中 max-width 分支;宽视口命中 min-width 分支。 + #[test] + fn media_query_matches_by_viewport_width() { + let css = "@media (max-width: 500px) { p { color: red } }\ + @media (min-width: 600px) { p { color: blue } }"; + + let narrow = Stylesheet::parse_with_viewport( + css, + MediaViewport { + width: 300.0, + height: 600.0, + }, + ); + assert_eq!(rule_texts(&narrow), vec!["p"], "窄视口只命中 max-width 块"); + assert_eq!( + declaration_of(&narrow, 0, PropertyId::Color).value, + DeclaredValue::Typed(PropertyValue::Color(Rgba::opaque(255, 0, 0))) + ); + + let wide = Stylesheet::parse_with_viewport( + css, + MediaViewport { + width: 900.0, + height: 600.0, + }, + ); + assert_eq!(rule_texts(&wide), vec!["p"], "宽视口只命中 min-width 块"); + assert_eq!( + declaration_of(&wide, 0, PropertyId::Color).value, + DeclaredValue::Typed(PropertyValue::Color(Rgba::opaque(0, 0, 255))) + ); + } + + /// 不匹配的规则不参与级联;边界值按闭区间语义(<= / >=)。 + #[test] + fn non_matching_media_rules_are_dropped() { + let css = "@media (min-width: 600px) { p { color: red } }\ + p { display: none }"; + + let narrow = Stylesheet::parse_with_viewport( + css, + MediaViewport { + width: 599.0, + height: 0.0, + }, + ); + assert_eq!(rule_texts(&narrow), vec!["p"], "599px 不命中 600px 下限"); + + // 边界:600px 恰好命中 min-width: 600px + let boundary = Stylesheet::parse_with_viewport( + css, + MediaViewport { + width: 600.0, + height: 0.0, + }, + ); + assert_eq!( + rule_texts(&boundary), + vec!["p", "p"], + "600px 命中 min-width" + ); + } + + /// and 组合、not、媒体类型与非法查询的求值语义。 + #[test] + fn media_query_combinators_and_invalid_queries() { + let viewport = MediaViewport { + width: 800.0, + height: 400.0, + }; + // and 组合全命中 + let sheet = Stylesheet::parse_with_viewport( + "@media screen and (min-width: 400px) and (max-height: 500px) { p { color: red } }", + viewport, + ); + assert_eq!(rule_texts(&sheet), vec!["p"]); + // not 取反 + let sheet = Stylesheet::parse_with_viewport( + "@media not screen and (min-width: 400px) { p { color: red } }", + viewport, + ); + assert!(sheet.rules().is_empty(), "not screen 命中的查询被取反"); + // print 类型不命中 + let sheet = Stylesheet::parse_with_viewport("@media print { p { color: red } }", viewport); + assert!(sheet.rules().is_empty()); + // 非法特性 → 恒不命中(not all) + let sheet = Stylesheet::parse_with_viewport( + "@media (resolution: 300dpi) { p { color: red } }", + viewport, + ); + assert!(sheet.rules().is_empty()); + // 命中的块与不命中的块交错时保持源顺序 + let sheet = Stylesheet::parse_with_viewport( + "@media (max-width: 100px) { a { color: red } }\ + b { color: blue }\ + @media (min-width: 100px) { c { color: green } }", + viewport, + ); + assert_eq!(rule_texts(&sheet), vec!["b", "c"]); + } + + /// 命中的 @media 规则真实参与级联。 + #[test] + fn media_rules_participate_in_cascade() { + use crate::{compute_document_styles, html_ua_stylesheet, test_support}; + + let document = test_support::build_document("<p>x</p>"); + let sheet = Stylesheet::parse_with_viewport( + "@media (min-width: 600px) { p { color: blue } }", + MediaViewport { + width: 800.0, + height: 600.0, + }, + ); + let styles = compute_document_styles(&document, &[&sheet], Some(html_ua_stylesheet())); + let p = test_support::find_first_by_name(&document, "p").expect("p"); + assert_eq!(styles[&p].color, Rgba::opaque(0, 0, 255), "命中块参与级联"); + } + + #[test] + fn invalid_declarations_are_recovered_individually() { + // CSS Syntax §5.5:单条声明无效 → 跳过该条,保留其余 + let sheet = Stylesheet::parse( + "p { color: red;; colr: blue; font-size: ; display: none; color: ; grid-area: x }", + ); + let declarations = &sheet.rules()[0].declarations; + let properties: Vec<PropertyId> = declarations.iter().map(|d| d.property).collect(); + assert_eq!(properties, vec![PropertyId::Color, PropertyId::Display]); + } + + #[test] + fn unknown_property_is_dropped_but_custom_property_syntax_recovered() { + let sheet = Stylesheet::parse("p { --custom: 1px solid; color: green }"); + assert_eq!(sheet.rules()[0].declarations().len(), 1); + assert_eq!( + sheet.rules()[0].declarations()[0].property, + PropertyId::Color + ); + } + + #[test] + fn important_flag_is_parsed() { + let sheet = Stylesheet::parse("p { color: red !important; font-size: 10px }"); + assert!(declaration_of(&sheet, 0, PropertyId::Color).important); + assert!(!declaration_of(&sheet, 0, PropertyId::FontSize).important); + } + + #[test] + fn css_wide_keywords_survive_parsing() { + let sheet = Stylesheet::parse("p { color: inherit; font-size: initial !important }"); + assert_eq!( + declaration_of(&sheet, 0, PropertyId::Color).value, + DeclaredValue::CssWide(CssWideKeyword::Inherit) + ); + let font_size = declaration_of(&sheet, 0, PropertyId::FontSize); + assert_eq!( + font_size.value, + DeclaredValue::CssWide(CssWideKeyword::Initial) + ); + assert!(font_size.important); + } + + #[test] + fn comments_and_cdo_cdc_are_ignored() { + let sheet = Stylesheet::parse( + "/* header */ <!-- p { color: red } --> /* tail */ p em { color: blue }", + ); + assert_eq!(rule_texts(&sheet), vec!["p", "p em"]); + } + + #[test] + fn inline_style_parses_declarations() { + let declarations = parse_inline_style("color: red; font-size: 2em !important; bogus: 1"); + assert_eq!(declarations.len(), 2); + assert_eq!(declarations[0].property, PropertyId::Color); + assert!(!declarations[0].important); + assert_eq!(declarations[1].property, PropertyId::FontSize); + assert!(declarations[1].important); + } + + #[test] + fn empty_and_garbage_input_yield_no_rules() { + assert!(Stylesheet::parse("").rules().is_empty()); + assert!(Stylesheet::parse("}{{{{").rules().is_empty()); + assert!(Stylesheet::parse("@").rules().is_empty()); + } + + fn property_values(sheet: &Stylesheet, rule: usize) -> Vec<(PropertyId, &DeclaredValue)> { + sheet.rules()[rule] + .declarations() + .iter() + .map(|declaration| (declaration.property, &declaration.value)) + .collect() + } + + fn length(value: f32) -> DeclaredValue { + DeclaredValue::Typed(PropertyValue::Margin(MarginValue::Length(value))) + } + + #[test] + fn margin_shorthand_expands_clockwise() { + let one = Stylesheet::parse("p { margin: 10px }"); + let values = property_values(&one, 0); + assert_eq!(values.len(), 4); + for (property, value) in values { + assert!(matches!( + property, + PropertyId::MarginTop + | PropertyId::MarginRight + | PropertyId::MarginBottom + | PropertyId::MarginLeft + )); + assert_eq!(value, &length(10.0), "{property:?}"); + } + + let two = Stylesheet::parse("p { margin: 1px 2px }"); + let values = property_values(&two, 0); + assert_eq!( + values, + vec![ + (PropertyId::MarginTop, &length(1.0)), + (PropertyId::MarginRight, &length(2.0)), + (PropertyId::MarginBottom, &length(1.0)), + (PropertyId::MarginLeft, &length(2.0)), + ] + ); + + let three = Stylesheet::parse("p { margin: 1px 2px 3px }"); + let values = property_values(&three, 0); + assert_eq!(values[1].1, &length(2.0), "三值时左右取第二个"); + assert_eq!(values[2].1, &length(3.0)); + + let four = Stylesheet::parse("p { margin: 1px 2px 3px 4px }"); + let values = property_values(&four, 0); + assert_eq!( + values, + vec![ + (PropertyId::MarginTop, &length(1.0)), + (PropertyId::MarginRight, &length(2.0)), + (PropertyId::MarginBottom, &length(3.0)), + (PropertyId::MarginLeft, &length(4.0)), + ] + ); + } + + #[test] + fn margin_accepts_negative_auto_percent() { + let sheet = Stylesheet::parse("p { margin: -5px auto 50% }"); + let values = property_values(&sheet, 0); + assert_eq!(values[0].1, &length(-5.0), "margin 可为负"); + assert_eq!( + values[1].1, + &DeclaredValue::Typed(PropertyValue::Margin(MarginValue::Auto)) + ); + assert_eq!( + values[2].1, + &DeclaredValue::Typed(PropertyValue::Margin(MarginValue::Percent(0.5))) + ); + } + + #[test] + fn padding_rejects_auto_and_negative() { + let sheet = Stylesheet::parse("p { padding: 10px 5%; bogus: x }"); + let values = property_values(&sheet, 0); + assert_eq!(values.len(), 4); + assert_eq!( + values[0].1, + &DeclaredValue::Typed(PropertyValue::Padding(PaddingValue::Length(10.0))) + ); + assert_eq!( + values[3].1, + &DeclaredValue::Typed(PropertyValue::Padding(PaddingValue::Percent(0.05))) + ); + + // auto / 负值 → 整条声明丢弃(规则保留,声明为空) + assert!( + Stylesheet::parse("p { padding: auto }").rules()[0] + .declarations() + .is_empty() + ); + assert!( + Stylesheet::parse("p { padding: -5px }").rules()[0] + .declarations() + .is_empty() + ); + } + + #[test] + fn border_shorthand_expands_to_twelve_longhands() { + let sheet = Stylesheet::parse("p { border: 1px solid red }"); + let declarations = &sheet.rules()[0].declarations(); + assert_eq!(declarations.len(), 12); + assert!( + declarations + .iter() + .filter(|declaration| matches!( + declaration.property, + PropertyId::BorderTopWidth + | PropertyId::BorderRightWidth + | PropertyId::BorderBottomWidth + | PropertyId::BorderLeftWidth + )) + .all(|declaration| declaration.value + == DeclaredValue::Typed(PropertyValue::BorderWidth(BorderWidthValue::Length( + 1.0 + )))) + ); + assert!(declarations.iter().all(|declaration| !matches!( + declaration.property, + PropertyId::BorderTopColor + ) || declaration.value + == DeclaredValue::Typed(PropertyValue::BorderColor(BorderColorValue::Rgba( + Rgba::opaque(255, 0, 0) + ))))); + + // 缺省成分取 initial:medium / none / currentcolor + let sheet = Stylesheet::parse("p { border: solid }"); + let declarations = &sheet.rules()[0].declarations(); + assert_eq!(declarations.len(), 12); + assert!(declarations.iter().any(|declaration| declaration.value + == DeclaredValue::Typed(PropertyValue::BorderWidth(BorderWidthValue::Medium)))); + assert!(declarations.iter().any(|declaration| declaration.value + == DeclaredValue::Typed(PropertyValue::BorderColor(BorderColorValue::CurrentColor)))); + } + + #[test] + fn side_shorthands_expand_independently() { + let sheet = Stylesheet::parse( + "p { border-width: 1px 2px; border-style: dashed dotted; border-color: currentcolor }", + ); + let declarations = &sheet.rules()[0].declarations(); + assert_eq!(declarations.len(), 12); + assert!(declarations.iter().any(|declaration| declaration.value + == DeclaredValue::Typed(PropertyValue::BorderWidth(BorderWidthValue::Length(2.0))))); + assert!(declarations.iter().any(|declaration| declaration.value + == DeclaredValue::Typed(PropertyValue::BorderStyle(BorderStyle::Dotted)))); + assert!(declarations.iter().any(|declaration| declaration.value + == DeclaredValue::Typed(PropertyValue::BorderColor(BorderColorValue::CurrentColor)))); + } + + #[test] + fn css_wide_keyword_on_shorthand_applies_to_all_longhands() { + let sheet = Stylesheet::parse("p { margin: inherit !important }"); + let declarations = &sheet.rules()[0].declarations(); + assert_eq!(declarations.len(), 4); + for declaration in declarations.iter() { + assert_eq!( + declaration.value, + DeclaredValue::CssWide(CssWideKeyword::Inherit) + ); + assert!(declaration.important); + } + } + + #[test] + fn width_height_line_height_parse() { + let sheet = Stylesheet::parse("p { width: 50%; height: auto; line-height: 1.5 }"); + let values = property_values(&sheet, 0); + assert_eq!(values.len(), 3); + assert_eq!( + values[0].1, + &DeclaredValue::Typed(PropertyValue::Size(SizeValue::Percent(0.5))) + ); + assert_eq!( + values[1].1, + &DeclaredValue::Typed(PropertyValue::Size(SizeValue::Auto)) + ); + assert_eq!( + values[2].1, + &DeclaredValue::Typed(PropertyValue::LineHeight(LineHeightValue::Number(1.5))) + ); + + // 负宽度、负行高、未知值 → 声明无效(丢弃,规则保留) + for css in [ + "p { width: -5px }", + "p { line-height: -1 }", + "p { line-height: 20zz }", + ] { + assert!( + Stylesheet::parse(css).rules()[0].declarations().is_empty(), + "{css} should drop the declaration" + ); + } + } + + // ---- font 简写(CSS Fonts 4 §3.3) ---- + + use crate::value::{FontFamilyValue, FontStyleValue, FontWeightValue}; + + #[test] + fn font_shorthand_expands_with_line_height() { + let sheet = + Stylesheet::parse(r#"p { font: italic bold 12px/1.5 "Helvetica Neue", serif }"#); + assert_eq!( + declaration_of(&sheet, 0, PropertyId::FontStyle).value, + DeclaredValue::Typed(PropertyValue::FontStyle(FontStyleValue::Italic)) + ); + assert_eq!( + declaration_of(&sheet, 0, PropertyId::FontWeight).value, + DeclaredValue::Typed(PropertyValue::FontWeight(FontWeightValue::Weight(700.0))) + ); + assert_eq!( + declaration_of(&sheet, 0, PropertyId::FontSize).value, + DeclaredValue::Typed(PropertyValue::FontSize(FontSizeValue::Px(12.0))) + ); + assert_eq!( + declaration_of(&sheet, 0, PropertyId::LineHeight).value, + DeclaredValue::Typed(PropertyValue::LineHeight(LineHeightValue::Number(1.5))) + ); + assert_eq!( + declaration_of(&sheet, 0, PropertyId::FontFamily).value, + DeclaredValue::Typed(PropertyValue::FontFamily(vec![ + FontFamilyValue::Family("Helvetica Neue".to_string()), + FontFamilyValue::Generic("serif"), + ])) + ); + } + + /// 缺省成分按简写语义重置为 initial(style=normal、weight=400、 + /// line-height=normal)。 + #[test] + fn font_shorthand_resets_missing_longhands_to_initial() { + let sheet = Stylesheet::parse("p { font: 12px serif }"); + assert_eq!( + declaration_of(&sheet, 0, PropertyId::FontStyle).value, + DeclaredValue::Typed(PropertyValue::FontStyle(FontStyleValue::Normal)) + ); + assert_eq!( + declaration_of(&sheet, 0, PropertyId::FontWeight).value, + DeclaredValue::Typed(PropertyValue::FontWeight(FontWeightValue::Weight(400.0))) + ); + assert_eq!( + declaration_of(&sheet, 0, PropertyId::FontSize).value, + DeclaredValue::Typed(PropertyValue::FontSize(FontSizeValue::Px(12.0))) + ); + assert_eq!( + declaration_of(&sheet, 0, PropertyId::LineHeight).value, + DeclaredValue::Typed(PropertyValue::LineHeight(LineHeightValue::Normal)) + ); + assert_eq!( + declaration_of(&sheet, 0, PropertyId::FontFamily).value, + DeclaredValue::Typed(PropertyValue::FontFamily(vec![FontFamilyValue::Generic( + "serif" + )])) + ); + } + + /// `normal` 占位(style/variant/weight/width 槽位)与数值字重。 + #[test] + fn font_shorthand_accepts_normal_placeholders_and_numeric_weight() { + let sheet = Stylesheet::parse("p { font: normal normal 400 1em sans-serif }"); + assert_eq!( + declaration_of(&sheet, 0, PropertyId::FontStyle).value, + DeclaredValue::Typed(PropertyValue::FontStyle(FontStyleValue::Normal)) + ); + assert_eq!( + declaration_of(&sheet, 0, PropertyId::FontWeight).value, + DeclaredValue::Typed(PropertyValue::FontWeight(FontWeightValue::Weight(400.0))) + ); + assert_eq!( + declaration_of(&sheet, 0, PropertyId::FontSize).value, + DeclaredValue::Typed(PropertyValue::FontSize(FontSizeValue::Em(1.0))) + ); + assert_eq!( + declaration_of(&sheet, 0, PropertyId::FontFamily).value, + DeclaredValue::Typed(PropertyValue::FontFamily(vec![FontFamilyValue::Generic( + "sans-serif" + )])) + ); + } + + /// `||` 成分任意顺序;small-caps / font-width 无 longhand,接受后丢弃。 + #[test] + fn font_shorthand_components_in_any_order_with_discarded_width() { + let sheet = Stylesheet::parse("p { font: small-caps condensed bold oblique 14px monospace }"); + assert_eq!( + declaration_of(&sheet, 0, PropertyId::FontStyle).value, + DeclaredValue::Typed(PropertyValue::FontStyle(FontStyleValue::Oblique(None))) + ); + assert_eq!( + declaration_of(&sheet, 0, PropertyId::FontWeight).value, + DeclaredValue::Typed(PropertyValue::FontWeight(FontWeightValue::Weight(700.0))) + ); + assert_eq!( + declaration_of(&sheet, 0, PropertyId::FontSize).value, + DeclaredValue::Typed(PropertyValue::FontSize(FontSizeValue::Px(14.0))) + ); + assert_eq!( + declaration_of(&sheet, 0, PropertyId::FontFamily).value, + DeclaredValue::Typed(PropertyValue::FontFamily(vec![FontFamilyValue::Generic( + "monospace" + )])) + ); + } + + /// `!important` 作用于全部 longhand(族名解析在 `!` 前停止)。 + #[test] + fn font_shorthand_important_applies_to_all_longhands() { + let sheet = Stylesheet::parse("p { font: 12px serif !important }"); + let declarations = &sheet.rules()[0].declarations(); + assert_eq!(declarations.len(), 5); + assert!(declarations.iter().all(|declaration| declaration.important)); + } + + /// CSS-wide 关键字作用于全部 longhand。 + #[test] + fn font_shorthand_css_wide_keyword() { + let sheet = Stylesheet::parse("p { font: inherit }"); + let declarations = &sheet.rules()[0].declarations(); + assert_eq!(declarations.len(), 5); + assert!( + declarations + .iter() + .all(|declaration| declaration.value == DeclaredValue::CssWide(CssWideKeyword::Inherit)) + ); + } + + /// 非法值整条丢弃:缺 size、缺 family、系统字体关键字、值后残留垃圾。 + #[test] + fn font_shorthand_invalid_values_are_dropped() { + for css in [ + "p { font: 12px }", // 缺 family + "p { font: bold serif }", // 缺 size + "p { font: caption }", // 系统字体关键字 + "p { font: 12px serif garbage }", // family 后残留 + "p { font: 12px/ }", // 行高缺失 + ] { + assert!( + Stylesheet::parse(css).rules()[0].declarations().is_empty(), + "{css} should drop the declaration" + ); + } + } + + /// font-family longhand 本身带 `!important`(族名解析在 `!` 前停止)。 + #[test] + fn font_family_longhand_with_important() { + let sheet = Stylesheet::parse(r#"p { font-family: "Helvetica Neue", serif !important }"#); + assert!(declaration_of(&sheet, 0, PropertyId::FontFamily).important); + assert_eq!( + declaration_of(&sheet, 0, PropertyId::FontFamily).value, + DeclaredValue::Typed(PropertyValue::FontFamily(vec![ + FontFamilyValue::Family("Helvetica Neue".to_string()), + FontFamilyValue::Generic("serif"), + ])) + ); + } +} diff --git a/crates/nexty-css/.mimosa/hook-state/sess_ca7e797f-14f7-4cd4-a65e-6a69d7418103.mv37y1v5-51660-adb7c830c0.baseline/be1c878c753064b7eaddf4a10ba4215a93dd1817d31e6788691cdb29752fd612.source b/crates/nexty-css/.mimosa/hook-state/sess_ca7e797f-14f7-4cd4-a65e-6a69d7418103.mv37y1v5-51660-adb7c830c0.baseline/be1c878c753064b7eaddf4a10ba4215a93dd1817d31e6788691cdb29752fd612.source new file mode 100644 index 0000000..e6c0f58 --- /dev/null +++ b/crates/nexty-css/.mimosa/hook-state/sess_ca7e797f-14f7-4cd4-a65e-6a69d7418103.mv37y1v5-51660-adb7c830c0.baseline/be1c878c753064b7eaddf4a10ba4215a93dd1817d31e6788691cdb29752fd612.source @@ -0,0 +1,2840 @@ +//! 属性值模型与逐属性解析。 +//! +//! 行为 ground truth: +//! - CSS-wide 关键字:[CSS Cascading and Inheritance Level 5 §6](https://drafts.csswg.org/css-cascade-5/#defaulting-keywords) +//! - 颜色:[CSS Color Module Level 4](https://drafts.csswg.org/css-color-4/)(hex / rgb() / hsl() / 命名色) +//! - 字号:[CSS Fonts Module Level 4 §2.5](https://drafts.csswg.org/css-fonts-4/#font-size-prop) +//! - 字重:[CSS Fonts Module Level 4 §2.2](https://drafts.csswg.org/css-fonts-4/#font-weight-numeric) +//! - 字体族:[CSS Fonts Module Level 4 §2.3](https://drafts.csswg.org/css-fonts-4/#font-family-prop) +//! - font 简写:[CSS Fonts Module Level 4 §3.3](https://drafts.csswg.org/css-fonts-4/#font-prop) +//! - display:[CSS Display Module Level 3](https://drafts.csswg.org/css-display-3/#the-display-properties) +//! - text-align:[CSS Text Module Level 4](https://drafts.csswg.org/css-text-4/#text-align-property) +//! +//! 已知偏差(按需再补,见本轮 goal.md 非目标):`rem` / `ex` / `ch` 等 +//! 相对单位、`currentcolor`、`color-mix()` 等函数色、`display` 的多关键字 +//! 语法与 ruby 内部盒、`var()` 均视为无效声明(浏览器会接受其中的合法值)。 +//! `font` 简写里无对应 longhand 的成分——`<font-variant-css2>`(`small-caps`) +//! 与 `<font-width-css3>`(宽度关键字/百分比)——按语法接受后丢弃(无渲染 +//! 效果但声明不整体失效);系统字体关键字(`caption` / `menu` 等)整条无效。 +//! +//! **Feature**:本模块受 `values` feature 控制(由 lib.rs 装配)。其中的 +//! `parse_*` 逐属性解析函数供 `parser` / `cascade` 模块消费,故当上层 feature +//! 关闭时这些内部函数没有调用方——此时按模块整体抑制 dead_code。 + +#![cfg_attr(not(feature = "stylesheets"), allow(dead_code))] + +use cssparser::{ParseError, Parser, Token, parse_important}; + +/// 非预乘 sRGB 颜色。 +/// +/// 对应 CSS Color 4 的 [`<color>`](https://drafts.csswg.org/css-color-4/#color-syntax) +/// 解析结果;alpha 与各通道均量化到 8bit。 +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +pub struct Rgba { + /// 红通道。 + pub r: u8, + /// 绿通道。 + pub g: u8, + /// 蓝通道。 + pub b: u8, + /// alpha 通道。 + pub a: u8, +} + +impl Rgba { + /// 不透明颜色。 + #[must_use] + pub const fn opaque(r: u8, g: u8, b: u8) -> Self { + Self { r, g, b, a: 0xff } + } + + /// 全透明黑,即 CSS 关键字 `transparent` + /// ([CSS Color 4 §5.5](https://drafts.csswg.org/css-color-4/#transparent-color))。 + #[must_use] + pub const fn transparent() -> Self { + Self { + r: 0, + g: 0, + b: 0, + a: 0, + } + } +} + +/// 级联引擎认识的最小属性集合。 +/// +/// 只覆盖当前管线需要的属性;新属性随消费方(layout / text / paint)落地时加入, +/// 不预先铺满。属性元数据(inherited / initial)见 `cascade` 模块。 +#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)] +pub enum PropertyId { + /// `display`。 + Display, + /// `color`。 + Color, + /// `background-color`。 + BackgroundColor, + /// `font-size`。 + FontSize, + /// `font-weight`。 + FontWeight, + /// `font-style`。 + FontStyle, + /// `font-family`。 + FontFamily, + /// `text-align`。 + TextAlign, + /// `line-height`。 + LineHeight, + /// `width`。 + Width, + /// `height`。 + Height, + /// `min-width`。 + MinWidth, + /// `max-width`。 + MaxWidth, + /// `min-height`。 + MinHeight, + /// `max-height`。 + MaxHeight, + /// `box-sizing`。 + BoxSizing, + /// `overflow`。 + Overflow, + /// `flex-grow`。 + FlexGrow, + /// `flex-basis`。 + FlexBasis, + /// `position`。 + Position, + /// `top`。 + Top, + /// `right`。 + Right, + /// `bottom`。 + Bottom, + /// `left`。 + Left, + /// `flex-direction`。 + FlexDirection, + /// `flex-wrap`。 + FlexWrap, + /// `flex-shrink`。 + FlexShrink, + /// `align-items`。 + AlignItems, + /// `justify-content`。 + JustifyContent, + /// `align-self`。 + AlignSelf, + /// `grid-template-columns`。 + GridTemplateColumns, + /// `grid-template-rows`。 + GridTemplateRows, + /// `row-gap`。 + RowGap, + /// `column-gap`。 + ColumnGap, + /// `grid-auto-flow`。 + GridAutoFlow, + /// `margin-top`。 + MarginTop, + /// `margin-right`。 + MarginRight, + /// `margin-bottom`。 + MarginBottom, + /// `margin-left`。 + MarginLeft, + /// `padding-top`。 + PaddingTop, + /// `padding-right`。 + PaddingRight, + /// `padding-bottom`。 + PaddingBottom, + /// `padding-left`。 + PaddingLeft, + /// `border-top-style`。 + BorderTopStyle, + /// `border-right-style`。 + BorderRightStyle, + /// `border-bottom-style`。 + BorderBottomStyle, + /// `border-left-style`。 + BorderLeftStyle, + /// `border-top-width`。 + BorderTopWidth, + /// `border-right-width`。 + BorderRightWidth, + /// `border-bottom-width`。 + BorderBottomWidth, + /// `border-left-width`。 + BorderLeftWidth, + /// `border-top-color`。 + BorderTopColor, + /// `border-right-color`。 + BorderRightColor, + /// `border-bottom-color`。 + BorderBottomColor, + /// `border-left-color`。 + BorderLeftColor, +} + +impl PropertyId { + /// 属性的规范名(小写)。 + #[must_use] + pub fn as_str(self) -> &'static str { + match self { + PropertyId::Display => "display", + PropertyId::Color => "color", + PropertyId::BackgroundColor => "background-color", + PropertyId::FontSize => "font-size", + PropertyId::FontWeight => "font-weight", + PropertyId::FontStyle => "font-style", + PropertyId::FontFamily => "font-family", + PropertyId::TextAlign => "text-align", + PropertyId::LineHeight => "line-height", + PropertyId::Width => "width", + PropertyId::Height => "height", + PropertyId::MinWidth => "min-width", + PropertyId::MaxWidth => "max-width", + PropertyId::MinHeight => "min-height", + PropertyId::MaxHeight => "max-height", + PropertyId::BoxSizing => "box-sizing", + PropertyId::Overflow => "overflow", + PropertyId::FlexGrow => "flex-grow", + PropertyId::FlexBasis => "flex-basis", + PropertyId::Position => "position", + PropertyId::Top => "top", + PropertyId::Right => "right", + PropertyId::Bottom => "bottom", + PropertyId::Left => "left", + PropertyId::FlexDirection => "flex-direction", + PropertyId::FlexWrap => "flex-wrap", + PropertyId::FlexShrink => "flex-shrink", + PropertyId::AlignItems => "align-items", + PropertyId::JustifyContent => "justify-content", + PropertyId::AlignSelf => "align-self", + PropertyId::GridTemplateColumns => "grid-template-columns", + PropertyId::GridTemplateRows => "grid-template-rows", + PropertyId::RowGap => "row-gap", + PropertyId::ColumnGap => "column-gap", + PropertyId::GridAutoFlow => "grid-auto-flow", + PropertyId::MarginTop => "margin-top", + PropertyId::MarginRight => "margin-right", + PropertyId::MarginBottom => "margin-bottom", + PropertyId::MarginLeft => "margin-left", + PropertyId::PaddingTop => "padding-top", + PropertyId::PaddingRight => "padding-right", + PropertyId::PaddingBottom => "padding-bottom", + PropertyId::PaddingLeft => "padding-left", + PropertyId::BorderTopStyle => "border-top-style", + PropertyId::BorderRightStyle => "border-right-style", + PropertyId::BorderBottomStyle => "border-bottom-style", + PropertyId::BorderLeftStyle => "border-left-style", + PropertyId::BorderTopWidth => "border-top-width", + PropertyId::BorderRightWidth => "border-right-width", + PropertyId::BorderBottomWidth => "border-bottom-width", + PropertyId::BorderLeftWidth => "border-left-width", + PropertyId::BorderTopColor => "border-top-color", + PropertyId::BorderRightColor => "border-right-color", + PropertyId::BorderBottomColor => "border-bottom-color", + PropertyId::BorderLeftColor => "border-left-color", + } + } + + /// 按属性名查 [`PropertyId`],ASCII case-insensitive + /// (CSS Syntax:声明名匹配大小写不敏感)。 + #[must_use] + pub fn from_name(name: &str) -> Option<Self> { + const ALL: [PropertyId; 55] = [ + PropertyId::Display, + PropertyId::Color, + PropertyId::BackgroundColor, + PropertyId::FontSize, + PropertyId::FontWeight, + PropertyId::FontStyle, + PropertyId::FontFamily, + PropertyId::TextAlign, + PropertyId::LineHeight, + PropertyId::Width, + PropertyId::Height, + PropertyId::MinWidth, + PropertyId::MaxWidth, + PropertyId::MinHeight, + PropertyId::MaxHeight, + PropertyId::BoxSizing, + PropertyId::Overflow, + PropertyId::FlexGrow, + PropertyId::FlexBasis, + PropertyId::Position, + PropertyId::Top, + PropertyId::Right, + PropertyId::Bottom, + PropertyId::Left, + PropertyId::FlexDirection, + PropertyId::FlexWrap, + PropertyId::FlexShrink, + PropertyId::AlignItems, + PropertyId::JustifyContent, + PropertyId::AlignSelf, + PropertyId::GridTemplateColumns, + PropertyId::GridTemplateRows, + PropertyId::RowGap, + PropertyId::ColumnGap, + PropertyId::GridAutoFlow, + PropertyId::MarginTop, + PropertyId::MarginRight, + PropertyId::MarginBottom, + PropertyId::MarginLeft, + PropertyId::PaddingTop, + PropertyId::PaddingRight, + PropertyId::PaddingBottom, + PropertyId::PaddingLeft, + PropertyId::BorderTopStyle, + PropertyId::BorderRightStyle, + PropertyId::BorderBottomStyle, + PropertyId::BorderLeftStyle, + PropertyId::BorderTopWidth, + PropertyId::BorderRightWidth, + PropertyId::BorderBottomWidth, + PropertyId::BorderLeftWidth, + PropertyId::BorderTopColor, + PropertyId::BorderRightColor, + PropertyId::BorderBottomColor, + PropertyId::BorderLeftColor, + ]; + ALL.into_iter() + .find(|id| id.as_str().eq_ignore_ascii_case(name)) + } +} + +/// CSS-wide 关键字 +/// ([CSS Cascade 5 §6.1](https://drafts.csswg.org/css-cascade-5/#defaulting-keywords))。 +/// +/// 对任何属性都合法,求值语义由 cascade 模块实现。 +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +pub enum CssWideKeyword { + /// `initial`。 + Initial, + /// `inherit`。 + Inherit, + /// `unset`。 + Unset, + /// `revert`。 + Revert, +} + +/// 一条声明按属性解析后的值。 +#[derive(Debug, Clone, PartialEq)] +pub enum DeclaredValue { + /// CSS-wide 关键字(对任意属性合法)。 + CssWide(CssWideKeyword), + /// 按属性语法解析出的值。 + Typed(PropertyValue), +} + +/// 各属性解析后的值。 +/// +/// 每个变体对应 [`PropertyId`] 中一个属性的可接受语法;不在集合内的值按 +/// 无效声明处理(整体丢弃,声明级恢复,见 CSS Syntax §5.5)。 +#[derive(Debug, Clone, PartialEq)] +pub enum PropertyValue { + /// `display` 关键字。 + Display(DisplayValue), + /// `text-align` 关键字。 + TextAlign(TextAlignValue), + /// `font-style` 关键字。 + FontStyle(FontStyleValue), + /// 颜色值。 + Color(Rgba), + /// `font-size` 值。 + FontSize(FontSizeValue), + /// `font-weight` 值。 + FontWeight(FontWeightValue), + /// `font-family` 字体族列表。 + FontFamily(Vec<FontFamilyValue>), + /// `line-height` 值。 + LineHeight(LineHeightValue), + /// `width` / `height` 值(min-width / max-width / min-height / max-height + /// 复用同一语法)。 + Size(SizeValue), + /// `box-sizing` 关键字。 + BoxSizing(BoxSizingValue), + /// `overflow` 关键字。 + Overflow(OverflowValue), + /// `flex-grow` 数值。 + FlexGrow(f32), + /// `flex-basis` 值(auto | <length-percentage>)。 + FlexBasis(SizeValue), + /// `position` 关键字。 + Position(PositionValue), + /// `top` / `right` / `bottom` / `left` 值。 + Inset(InsetValue), + /// `flex-direction` 关键字。 + FlexDirection(FlexDirectionValue), + /// `flex-wrap` 关键字。 + FlexWrap(FlexWrapValue), + /// `flex-shrink` 数值。 + FlexShrink(f32), + /// `align-items` 关键字。 + AlignItems(AlignItemsValue), + /// `justify-content` 关键字。 + JustifyContent(JustifyContentValue), + /// `align-self` 关键字。 + AlignSelf(AlignSelfValue), + /// `grid-template-columns` / `grid-template-rows` 轨道列表。 + GridTrack(GridTrackList), + /// `row-gap` / `column-gap` 值。 + Gap(GapValue), + /// `grid-auto-flow` 关键字。 + GridAutoFlow(GridAutoFlowValue), + /// margin 值(四边共用)。 + Margin(MarginValue), + /// padding 值(四边共用)。 + Padding(PaddingValue), + /// border-*-width 值。 + BorderWidth(BorderWidthValue), + /// border-*-style 关键字。 + BorderStyle(BorderStyle), + /// border-*-color 值。 + BorderColor(BorderColorValue), +} + +/// `display` 的单关键字值 +/// ([CSS Display 3 §2](https://drafts.csswg.org/css-display-3/#the-display-properties))。 +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +pub enum DisplayValue { + /// `inline`(initial)。 + Inline, + /// `block`。 + Block, + /// `list-item`。 + ListItem, + /// `inline-block`。 + InlineBlock, + /// `flow-root`。 + FlowRoot, + /// `flex`。 + Flex, + /// `inline-flex`。 + InlineFlex, + /// `grid`。 + Grid, + /// `inline-grid`。 + InlineGrid, + /// `table`。 + Table, + /// `inline-table`。 + InlineTable, + /// 表格内部盒(`table-row-group` / `table-header-group` / + /// `table-footer-group` / `table-row` / `table-cell` / + /// `table-column-group` / `table-column` / `table-caption`)。 + TableInternal(&'static str), + /// `contents`。 + Contents, + /// `none`。 + None, +} + +/// `text-align` 值 +/// ([CSS Text 4](https://drafts.csswg.org/css-text-4/#text-align-property))。 +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +pub enum TextAlignValue { + /// `start`(initial)。 + Start, + /// `end`。 + End, + /// `left`。 + Left, + /// `right`。 + Right, + /// `center`。 + Center, + /// `justify`。 + Justify, + /// `match-parent`。 + MatchParent, + /// `justify-all`。 + JustifyAll, +} + +/// `font-style` 值 +/// ([CSS Fonts 4 §2.1](https://drafts.csswg.org/css-fonts-4/#font-style-prop))。 +#[derive(Debug, Clone, Copy, PartialEq)] +pub enum FontStyleValue { + /// `normal`(initial)。 + Normal, + /// `italic`。 + Italic, + /// `oblique`,可选倾斜角(角度制;`oblique none` 为 `None`)。 + Oblique(Option<f32>), +} + +/// `font-size` 的绝对尺寸关键字及其缩放系数 +/// ([CSS Fonts 4 §2.5.1](https://drafts.csswg.org/css-fonts-4/#absolute-size-mapping): +/// medium 为基准 1,其余为规范给出的 scaling factor)。 +#[derive(Debug, Clone, Copy, PartialEq)] +pub enum AbsoluteSize { + /// `xx-small`(3/5)。 + XxSmall, + /// `x-small`(3/4)。 + XSmall, + /// `small`(8/9)。 + Small, + /// `medium`(1)。 + Medium, + /// `large`(6/5)。 + Large, + /// `x-large`(3/2)。 + XLarge, + /// `xx-large`(2/1)。 + XxLarge, + /// `xxx-large`(3/1)。 + XxxLarge, +} + +impl AbsoluteSize { + /// 相对 medium 的缩放系数。 + #[must_use] + pub fn factor(self) -> f32 { + match self { + AbsoluteSize::XxSmall => 3.0 / 5.0, + AbsoluteSize::XSmall => 3.0 / 4.0, + AbsoluteSize::Small => 8.0 / 9.0, + AbsoluteSize::Medium => 1.0, + AbsoluteSize::Large => 6.0 / 5.0, + AbsoluteSize::XLarge => 1.5, + AbsoluteSize::XxLarge => 2.0, + AbsoluteSize::XxxLarge => 3.0, + } + } + + /// 绝对尺寸关键字的有序表,供 `larger` / `smaller` 取相邻项。 + pub const ORDERED: [AbsoluteSize; 8] = [ + AbsoluteSize::XxSmall, + AbsoluteSize::XSmall, + AbsoluteSize::Small, + AbsoluteSize::Medium, + AbsoluteSize::Large, + AbsoluteSize::XLarge, + AbsoluteSize::XxLarge, + AbsoluteSize::XxxLarge, + ]; +} + +/// `font-size` 值 +/// ([CSS Fonts 4 §2.5](https://drafts.csswg.org/css-fonts-4/#font-size-prop))。 +#[derive(Debug, Clone, Copy, PartialEq)] +pub enum FontSizeValue { + /// 绝对长度(已折算为 CSS px)。 + Px(f32), + /// 相对父元素计算字号的 em。 + Em(f32), + /// 相对父元素计算字号的百分比,以小数存储(`120%` → `1.2`)。 + Percent(f32), + /// 绝对尺寸关键字。 + Absolute(AbsoluteSize), + /// `larger`。 + Larger, + /// `smaller`。 + Smaller, +} + +/// `font-weight` 值 +/// ([CSS Fonts 4 §2.2](https://drafts.csswg.org/css-fonts-4/#font-weight-numeric))。 +#[derive(Debug, Clone, Copy, PartialEq)] +pub enum FontWeightValue { + /// 数值字重,1–1000(`normal` = 400、`bold` = 700 已在解析期折算)。 + Weight(f32), + /// `bolder`:相对继承值。 + Bolder, + /// `lighter`:相对继承值。 + Lighter, +} + +/// 字体族列表中的一项 +/// ([CSS Fonts 4 §2.3](https://drafts.csswg.org/css-fonts-4/#font-family-prop))。 +/// +/// 带引号的 `"serif"` 是名为 serif 的普通字体族,只有不带引号的 +/// generic 关键字才映射到 [`FontFamilyValue`] 的 generic 变体。 +#[derive(Debug, Clone, PartialEq, Eq)] +pub enum FontFamilyValue { + /// generic 族(`serif` / `sans-serif` / `cursive` / `fantasy` / + /// `monospace` / `system-ui` / `ui-serif` / `ui-sans-serif` / + /// `ui-monospace` / `ui-rounded` / `math` / `emoji` / `fangsong`)。 + Generic(&'static str), + /// 具名字体族。 + Family(String), +} + +/// `line-height` 值 +/// ([CSS 2.1 §10.8.1](https://www.w3.org/TR/CSS21/visudet.html#line-height))。 +/// +/// 数值保持数值(以自身数值继承,子元素按自身 font-size 求值); +/// 百分比与 em 在 computed 阶段按元素自身 font-size 折算(cascade 模块)。 +#[derive(Debug, Clone, Copy, PartialEq)] +pub enum LineHeightValue { + /// `normal`(initial,约 1.2,具体由 UA 决定)。 + Normal, + /// 无单位数值(可为 0,不可为负)。 + Number(f32), + /// 绝对长度(已折算为 CSS px)。 + Length(f32), + /// 相对自身 font-size 的 em。 + Em(f32), + /// 百分比(以小数存储,`150%` → `1.5`;computed 阶段乘 font-size)。 + Percent(f32), +} + +/// `width` / `height` 值 +/// ([CSS 2.1 §10.2](https://www.w3.org/TR/CSS21/visudet.html#the-width-property)、 +/// [§10.5](https://www.w3.org/TR/CSS21/visudet.html#the-height-property))。 +/// +/// 百分比由 layout 相对包含块宽度解析;负值非法(声明无效)。 +#[derive(Debug, Clone, Copy, PartialEq)] +pub enum SizeValue { + /// `auto`(initial)。 + Auto, + /// 绝对长度(CSS px)。 + Length(f32), + /// 百分比(以小数存储)。 + Percent(f32), +} + +/// `box-sizing` 值 +/// ([CSS Sizing 4 §5.3](https://drafts.csswg.org/css-sizing-4/#box-sizing))。 +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +pub enum BoxSizingValue { + /// `content-box`(initial):width/height 指内容盒。 + ContentBox, + /// `border-box`:width/height 指边框盒。 + BorderBox, +} + +/// `overflow` 值 +/// ([CSS Overflow 3 §3](https://drafts.csswg.org/css-overflow-3/#overflow-control))。 +/// +/// 本层只建模 visible / hidden 的裁剪标记;`auto` / `scroll` / `clip` +/// 暂按无效声明丢弃(回退 initial `visible`,见模块偏差)。 +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +pub enum OverflowValue { + /// `visible`(initial):内容溢出可见。 + Visible, + /// `hidden`:内容裁剪标记(裁剪实现待 paint/layout 接入)。 + Hidden, +} + +/// `position` 值 +/// ([CSS Position 3 §2](https://drafts.csswg.org/css-position-3/#position-properties))。 +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +pub enum PositionValue { + /// `static`(initial):常规流,不建立包含块。 + Static, + /// `relative`:相对自身偏移,仍占常规流空间。 + Relative, + /// `absolute`:相对最近定位祖先(无则视口)定位,脱离常规流。 + Absolute, + /// `fixed`:相对视口定位(本布局层按 absolute 处理)。 + Fixed, +} + +/// `top` / `right` / `bottom` / `left` 值(inset) +/// ([CSS Position 3 §3](https://drafts.csswg.org/css-position-3/#insets))。 +#[derive(Debug, Clone, Copy, PartialEq)] +pub enum InsetValue { + /// 绝对长度(CSS px)。 + Length(f32), + /// 百分比(相对包含块对应轴尺寸;本层仅垂直相对高度,水平相对宽度, + /// 由 layout 解析)。 + Percent(f32), + /// `auto`(initial)。 + Auto, +} + +/// `flex-direction` 值 +/// ([CSS Flexbox §8.3.1](https://drafts.csswg.org/css-flexbox/#flex-direction-property))。 +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +pub enum FlexDirectionValue { + /// `row`(initial)。 + Row, + /// `row-reverse`。 + RowReverse, + /// `column`。 + Column, + /// `column-reverse`。 + ColumnReverse, +} + +/// `flex-wrap` 值 +/// ([CSS Flexbox §8.4.1](https://drafts.csswg.org/css-flexbox/#flex-wrap-property))。 +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +pub enum FlexWrapValue { + /// `nowrap`(initial):单行。 + NoWrap, + /// `wrap`:多行。 + Wrap, + /// `wrap-reverse`:多行反向。 + WrapReverse, +} + +/// `align-items` / `align-self` 的 cross-axis 对齐值 +/// ([CSS Box Alignment §7](https://drafts.csswg.org/css-align-3/#align-items-property))。 +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +pub enum AlignItemsValue { + /// `stretch`(initial)。 + Stretch, + /// `flex-start` / `start`。 + FlexStart, + /// `flex-end` / `end`。 + FlexEnd, + /// `center`。 + Center, + /// `baseline`。 + Baseline, +} + +/// `justify-content` 的主轴对齐值 +/// ([CSS Box Alignment §8](https://drafts.csswg.org/css-align-3/#justify-content-property))。 +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +pub enum JustifyContentValue { + /// `flex-start` / `start`(initial)。 + FlexStart, + /// `flex-end` / `end`。 + FlexEnd, + /// `center`。 + Center, + /// `space-between`。 + SpaceBetween, + /// `space-around`。 + SpaceAround, + /// `space-evenly`。 + SpaceEvenly, +} + +/// `align-self` 值(在 `align-items` 基础上多一个 `auto` 回退父值)。 +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +pub enum AlignSelfValue { + /// `auto`(initial):回退到父 `align-items`。 + Auto, + /// 同 [`AlignItemsValue::Stretch`]。 + Stretch, + /// 同 [`AlignItemsValue::FlexStart`]。 + FlexStart, + /// 同 [`AlignItemsValue::FlexEnd`]。 + FlexEnd, + /// 同 [`AlignItemsValue::Center`]。 + Center, + /// 同 [`AlignItemsValue::Baseline`]。 + Baseline, +} + +/// `gap` 值 +/// ([CSS Box Alignment §6](https://drafts.csswg.org/css-align-3/#gap-shorthand))。 +#[derive(Debug, Clone, Copy, PartialEq)] +pub enum GapValue { + /// 绝对长度(CSS px)。 + Length(f32), + /// 百分比(相对包含块对应轴尺寸)。 + Percent(f32), + /// `normal`(initial):退化为 0。 + Normal, +} + +/// `grid-auto-flow` 值 +/// ([CSS Grid §7.7](https://drafts.csswg.org/css-grid/#grid-auto-flow-property))。 +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +pub enum GridAutoFlowValue { + /// `row`(initial)。 + Row, + /// `column`。 + Column, + /// `row dense`。 + RowDense, + /// `column dense`。 + ColumnDense, +} + +/// 一条 grid 轨道的轨道尺寸函数(简化版)。 +/// +/// 仅覆盖布局几何需要的子集:固定长度、百分比、弹性系数 `fr`、自适应 +/// `auto`、以及两段式 `minmax(a, b)`(a/b 各为长度/百分比/fr/auto)。 +#[derive(Debug, Clone, PartialEq)] +pub enum GridTrack { + /// 固定长度(CSS px)。 + Length(f32), + /// 百分比(相对网格容器尺寸)。 + Percent(f32), + /// 弹性系数 `fr`(参与剩余空间分配)。 + Fr(f32), + /// `auto`:内容驱动尺寸。 + Auto, + /// `minmax(a, b)`。 + MinMax(Box<GridTrack>, Box<GridTrack>), +} + +/// `grid-template-columns` / `grid-template-rows` 的轨道列表。 +#[derive(Debug, Clone, PartialEq, Default)] +pub struct GridTrackList { + /// 轨道序列;空表示未显式指定(用隐式轨道)。 + pub tracks: Vec<GridTrack>, +} + +/// `margin-*` 值 +/// ([CSS 2.1 §8.3](https://www.w3.org/TR/CSS21/box.html#margin-properties))。 +/// +/// 可为负;百分比由 layout 相对包含块宽度解析。 +#[derive(Debug, Clone, Copy, PartialEq)] +pub enum MarginValue { + /// 绝对长度(CSS px,可负)。 + Length(f32), + /// 百分比(以小数存储)。 + Percent(f32), + /// `auto`(initial;块级布局中解析为 0 或剩余空间)。 + Auto, +} + +/// `padding-*` 值 +/// ([CSS 2.1 §8.4](https://www.w3.org/TR/CSS21/box.html#padding-properties))。 +/// +/// 不接受 auto,负值非法;百分比由 layout 相对包含块宽度解析。 +#[derive(Debug, Clone, Copy, PartialEq)] +pub enum PaddingValue { + /// 绝对长度(CSS px,非负)。 + Length(f32), + /// 百分比(以小数存储)。 + Percent(f32), +} + +/// `border-*-width` 值 +/// ([CSS 2.1 §8.5.4](https://www.w3.org/TR/CSS21/box.html#border-width-properties))。 +/// +/// 关键字在解析期折算(thin 1px / medium 3px / thick 5px,与浏览器默认一致); +/// computed 阶段 style 为 none/hidden 时归零(cascade 模块)。 +#[derive(Debug, Clone, Copy, PartialEq)] +pub enum BorderWidthValue { + /// 绝对长度(CSS px,非负)。 + Length(f32), + /// `thin`(1px)。 + Thin, + /// `medium`(initial,3px)。 + Medium, + /// `thick`(5px)。 + Thick, +} + +impl BorderWidthValue { + /// 关键字/长度 → CSS px。 + #[must_use] + pub fn px(self) -> f32 { + match self { + BorderWidthValue::Length(px) => px, + BorderWidthValue::Thin => 1.0, + BorderWidthValue::Medium => 3.0, + BorderWidthValue::Thick => 5.0, + } + } +} + +/// `border-*-style` 关键字 +/// ([CSS 2.1 §8.5.3](https://www.w3.org/TR/CSS21/box.html#border-style-properties))。 +/// +/// 全部 10 个关键字都按规范接受;绘制端当前只区分 none/hidden 与可见边框 +/// (`solid` 语义),其余样式的绘制待 paint 层扩展。 +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +pub enum BorderStyle { + /// `none`(initial)。 + None, + /// `hidden`。 + Hidden, + /// `solid`。 + Solid, + /// `dashed`。 + Dashed, + /// `dotted`。 + Dotted, + /// `double`。 + Double, + /// `groove`。 + Groove, + /// `ridge`。 + Ridge, + /// `inset`。 + Inset, + /// `outset`。 + Outset, +} + +impl BorderStyle { + /// 是否画出可见边框(none/hidden 之外)。 + #[must_use] + pub fn visible(self) -> bool { + !matches!(self, BorderStyle::None | BorderStyle::Hidden) + } +} + +/// `border-*-color` 值 +/// ([CSS 2.1 §8.5.2](https://www.w3.org/TR/CSS21/box.html#border-color-properties))。 +/// +/// `currentcolor` 在 computed 阶段按本元素 `color` 解析(cascade 模块)。 +#[derive(Debug, Clone, Copy, PartialEq)] +pub enum BorderColorValue { + /// 具体颜色。 + Rgba(Rgba), + /// `currentcolor`。 + CurrentColor, +} + +/// 把声明值解析为 [`DeclaredValue`]:先识别 CSS-wide 关键字,再按属性语法解析。 +/// +/// `input` 已由调用方限定在本条声明的值范围内(分号 / 块尾之前)。 +/// 返回值连同该声明是否带 `!important`(CSS Cascade 5 §5.1);返回 `Err` +/// 表示整条声明无效。 +pub(crate) fn parse_declared_value( + property: PropertyId, + input: &mut Parser<'_>, +) -> Result<(DeclaredValue, bool), ()> { + if let Ok(keyword) = input.try_parse(parse_css_wide_keyword) { + let important = input.try_parse(parse_important).is_ok(); + // CSS-wide 关键字不允许再拼接其他值 + // (CSS Cascade 5:关键字是完整的 <declaration-value>)。 + if input.expect_exhausted().is_err() { + return Err(()); + } + return Ok((DeclaredValue::CssWide(keyword), important)); + } + let value = parse_property_value(property, input)?; + let important = input.try_parse(parse_important).is_ok(); + if input.expect_exhausted().is_err() { + return Err(()); + } + Ok((DeclaredValue::Typed(value), important)) +} + +/// 解析 CSS-wide 关键字(ASCII case-insensitive)。 +pub(crate) fn parse_css_wide_keyword(input: &mut Parser<'_>) -> Result<CssWideKeyword, ()> { + let Token::Ident(name) = input.next().map_err(|_| ())? else { + return Err(()); + }; + if name.eq_ignore_ascii_case("initial") { + Ok(CssWideKeyword::Initial) + } else if name.eq_ignore_ascii_case("inherit") { + Ok(CssWideKeyword::Inherit) + } else if name.eq_ignore_ascii_case("unset") { + Ok(CssWideKeyword::Unset) + } else if name.eq_ignore_ascii_case("revert") { + Ok(CssWideKeyword::Revert) + } else { + Err(()) + } +} + +/// 按属性语法解析值。 +fn parse_property_value(property: PropertyId, input: &mut Parser<'_>) -> Result<PropertyValue, ()> { + match property { + PropertyId::Display => parse_display(input).map(PropertyValue::Display), + PropertyId::TextAlign => parse_text_align(input).map(PropertyValue::TextAlign), + PropertyId::FontStyle => parse_font_style(input).map(PropertyValue::FontStyle), + PropertyId::Color => parse_color(input).map(PropertyValue::Color), + PropertyId::FontSize => parse_font_size(input).map(PropertyValue::FontSize), + PropertyId::FontWeight => parse_font_weight(input).map(PropertyValue::FontWeight), + PropertyId::FontFamily => parse_font_family(input).map(PropertyValue::FontFamily), + PropertyId::BackgroundColor => parse_color(input).map(PropertyValue::Color), + PropertyId::LineHeight => parse_line_height(input).map(PropertyValue::LineHeight), + PropertyId::Width + | PropertyId::Height + | PropertyId::MinWidth + | PropertyId::MaxWidth + | PropertyId::MinHeight + | PropertyId::MaxHeight => parse_size(input).map(PropertyValue::Size), + PropertyId::BoxSizing => parse_box_sizing(input).map(PropertyValue::BoxSizing), + PropertyId::Overflow => parse_overflow(input).map(PropertyValue::Overflow), + PropertyId::FlexGrow => parse_flex_grow(input).map(PropertyValue::FlexGrow), + PropertyId::FlexBasis => parse_size(input).map(PropertyValue::FlexBasis), + PropertyId::Position => parse_position(input).map(PropertyValue::Position), + PropertyId::Top | PropertyId::Right | PropertyId::Bottom | PropertyId::Left => { + parse_inset(input).map(PropertyValue::Inset) + } + PropertyId::FlexDirection => parse_flex_direction(input).map(PropertyValue::FlexDirection), + PropertyId::FlexWrap => parse_flex_wrap(input).map(PropertyValue::FlexWrap), + PropertyId::FlexShrink => parse_flex_shrink(input).map(PropertyValue::FlexShrink), + PropertyId::AlignItems => parse_align_items(input).map(PropertyValue::AlignItems), + PropertyId::JustifyContent => { + parse_justify_content(input).map(PropertyValue::JustifyContent) + } + PropertyId::AlignSelf => parse_align_self(input).map(PropertyValue::AlignSelf), + PropertyId::GridTemplateColumns | PropertyId::GridTemplateRows => { + parse_grid_track_list(input).map(PropertyValue::GridTrack) + } + PropertyId::RowGap | PropertyId::ColumnGap => parse_gap(input).map(PropertyValue::Gap), + PropertyId::GridAutoFlow => parse_grid_auto_flow(input).map(PropertyValue::GridAutoFlow), + PropertyId::MarginTop + | PropertyId::MarginRight + | PropertyId::MarginBottom + | PropertyId::MarginLeft => parse_margin(input).map(PropertyValue::Margin), + PropertyId::PaddingTop + | PropertyId::PaddingRight + | PropertyId::PaddingBottom + | PropertyId::PaddingLeft => parse_padding(input).map(PropertyValue::Padding), + PropertyId::BorderTopWidth + | PropertyId::BorderRightWidth + | PropertyId::BorderBottomWidth + | PropertyId::BorderLeftWidth => parse_border_width(input).map(PropertyValue::BorderWidth), + PropertyId::BorderTopStyle + | PropertyId::BorderRightStyle + | PropertyId::BorderBottomStyle + | PropertyId::BorderLeftStyle => parse_border_style(input).map(PropertyValue::BorderStyle), + PropertyId::BorderTopColor + | PropertyId::BorderRightColor + | PropertyId::BorderBottomColor + | PropertyId::BorderLeftColor => parse_border_color(input).map(PropertyValue::BorderColor), + } +} + +/// `line-height`:normal | <number [0,∞]> | <length> | <percentage> +/// (CSS 2.1 §10.8.1)。 +fn parse_line_height(input: &mut Parser<'_>) -> Result<LineHeightValue, ()> { + match input.next().map_err(|_| ())? { + Token::Ident(name) if name.eq_ignore_ascii_case("normal") => Ok(LineHeightValue::Normal), + Token::Number { value, .. } => { + if *value >= 0.0 { + Ok(LineHeightValue::Number(*value)) + } else { + Err(()) + } + } + Token::Percentage { unit_value, .. } => Ok(LineHeightValue::Percent(*unit_value)), + Token::Dimension { value, unit, .. } => { + if unit.eq_ignore_ascii_case("em") { + Ok(LineHeightValue::Em(*value)) + } else { + length_to_px(*value, unit) + .map(LineHeightValue::Length) + .ok_or(()) + } + } + _ => Err(()), + } +} + +/// `width` / `height`:<length> | <percentage> | auto,负值非法。 +fn parse_size(input: &mut Parser<'_>) -> Result<SizeValue, ()> { + match input.next().map_err(|_| ())? { + Token::Ident(name) if name.eq_ignore_ascii_case("auto") => Ok(SizeValue::Auto), + Token::Number { value: 0.0, .. } => Ok(SizeValue::Length(0.0)), + Token::Percentage { unit_value, .. } => Ok(SizeValue::Percent(*unit_value)), + Token::Dimension { value, unit, .. } => { + if *value < 0.0 { + return Err(()); + } + length_to_px(*value, unit).map(SizeValue::Length).ok_or(()) + } + _ => Err(()), + } +} + +/// `box-sizing`:content-box | border-box(ASCII case-insensitive)。 +fn parse_box_sizing(input: &mut Parser<'_>) -> Result<BoxSizingValue, ()> { + match input.next().map_err(|_| ())? { + Token::Ident(name) if name.eq_ignore_ascii_case("content-box") => { + Ok(BoxSizingValue::ContentBox) + } + Token::Ident(name) if name.eq_ignore_ascii_case("border-box") => { + Ok(BoxSizingValue::BorderBox) + } + _ => Err(()), + } +} + +/// `overflow`:visible | hidden(偏差:auto/scroll/clip 暂按无效丢弃)。 +fn parse_overflow(input: &mut Parser<'_>) -> Result<OverflowValue, ()> { + match input.next().map_err(|_| ())? { + Token::Ident(name) if name.eq_ignore_ascii_case("visible") => Ok(OverflowValue::Visible), + Token::Ident(name) if name.eq_ignore_ascii_case("hidden") => Ok(OverflowValue::Hidden), + _ => Err(()), + } +} + +/// `flex-grow`:<number [0,∞]>(CSS Flexbox §7.1;负数非法)。 +fn parse_flex_grow(input: &mut Parser<'_>) -> Result<f32, ()> { + match input.next().map_err(|_| ())? { + Token::Number { value, .. } if *value >= 0.0 => Ok(*value), + _ => Err(()), + } +} + +/// `position`:static | relative | absolute | fixed(ASCII case-insensitive)。 +/// +/// `fixed` 在本布局层按 `absolute` 处理(相对视口定位的包含块由 layout 提供)。 +fn parse_position(input: &mut Parser<'_>) -> Result<PositionValue, ()> { + let Token::Ident(name) = input.next().map_err(|_| ())? else { + return Err(()); + }; + if name.eq_ignore_ascii_case("static") { + Ok(PositionValue::Static) + } else if name.eq_ignore_ascii_case("relative") { + Ok(PositionValue::Relative) + } else if name.eq_ignore_ascii_case("absolute") { + Ok(PositionValue::Absolute) + } else if name.eq_ignore_ascii_case("fixed") { + Ok(PositionValue::Fixed) + } else { + Err(()) + } +} + +/// `top` / `right` / `bottom` / `left`:<length> | <percentage> | auto。 +fn parse_inset(input: &mut Parser<'_>) -> Result<InsetValue, ()> { + match input.next().map_err(|_| ())? { + Token::Ident(name) if name.eq_ignore_ascii_case("auto") => Ok(InsetValue::Auto), + Token::Number { value: 0.0, .. } => Ok(InsetValue::Length(0.0)), + Token::Percentage { unit_value, .. } => Ok(InsetValue::Percent(*unit_value)), + Token::Dimension { value, unit, .. } => { + length_to_px(*value, unit).map(InsetValue::Length).ok_or(()) + } + _ => Err(()), + } +} + +/// `flex-direction`:row | row-reverse | column | column-reverse。 +fn parse_flex_direction(input: &mut Parser<'_>) -> Result<FlexDirectionValue, ()> { + let Token::Ident(name) = input.next().map_err(|_| ())? else { + return Err(()); + }; + if name.eq_ignore_ascii_case("row") { + Ok(FlexDirectionValue::Row) + } else if name.eq_ignore_ascii_case("row-reverse") { + Ok(FlexDirectionValue::RowReverse) + } else if name.eq_ignore_ascii_case("column") { + Ok(FlexDirectionValue::Column) + } else if name.eq_ignore_ascii_case("column-reverse") { + Ok(FlexDirectionValue::ColumnReverse) + } else { + Err(()) + } +} + +/// `flex-wrap`:nowrap | wrap | wrap-reverse。 +fn parse_flex_wrap(input: &mut Parser<'_>) -> Result<FlexWrapValue, ()> { + let Token::Ident(name) = input.next().map_err(|_| ())? else { + return Err(()); + }; + if name.eq_ignore_ascii_case("nowrap") { + Ok(FlexWrapValue::NoWrap) + } else if name.eq_ignore_ascii_case("wrap") { + Ok(FlexWrapValue::Wrap) + } else if name.eq_ignore_ascii_case("wrap-reverse") { + Ok(FlexWrapValue::WrapReverse) + } else { + Err(()) + } +} + +/// `flex-shrink`:<number [0,∞]>(CSS Flexbox §7.2;负数非法)。 +fn parse_flex_shrink(input: &mut Parser<'_>) -> Result<f32, ()> { + match input.next().map_err(|_| ())? { + Token::Number { value, .. } if *value >= 0.0 => Ok(*value), + _ => Err(()), + } +} + +/// `align-items`:stretch | flex-start | flex-end | center | baseline +/// (兼容 `start` / `end` 取 flex-* 语义;CSS Box Alignment §7)。 +fn parse_align_items(input: &mut Parser<'_>) -> Result<AlignItemsValue, ()> { + let Token::Ident(name) = input.next().map_err(|_| ())? else { + return Err(()); + }; + if name.eq_ignore_ascii_case("stretch") { + Ok(AlignItemsValue::Stretch) + } else if name.eq_ignore_ascii_case("flex-start") || name.eq_ignore_ascii_case("start") { + Ok(AlignItemsValue::FlexStart) + } else if name.eq_ignore_ascii_case("flex-end") || name.eq_ignore_ascii_case("end") { + Ok(AlignItemsValue::FlexEnd) + } else if name.eq_ignore_ascii_case("center") { + Ok(AlignItemsValue::Center) + } else if name.eq_ignore_ascii_case("baseline") { + Ok(AlignItemsValue::Baseline) + } else { + Err(()) + } +} + +/// `justify-content`:flex-start | flex-end | center | space-between | +/// space-around | space-evenly(兼容 `start` / `end`)。 +fn parse_justify_content(input: &mut Parser<'_>) -> Result<JustifyContentValue, ()> { + let Token::Ident(name) = input.next().map_err(|_| ())? else { + return Err(()); + }; + if name.eq_ignore_ascii_case("flex-start") || name.eq_ignore_ascii_case("start") { + Ok(JustifyContentValue::FlexStart) + } else if name.eq_ignore_ascii_case("flex-end") || name.eq_ignore_ascii_case("end") { + Ok(JustifyContentValue::FlexEnd) + } else if name.eq_ignore_ascii_case("center") { + Ok(JustifyContentValue::Center) + } else if name.eq_ignore_ascii_case("space-between") { + Ok(JustifyContentValue::SpaceBetween) + } else if name.eq_ignore_ascii_case("space-around") { + Ok(JustifyContentValue::SpaceAround) + } else if name.eq_ignore_ascii_case("space-evenly") { + Ok(JustifyContentValue::SpaceEvenly) + } else { + Err(()) + } +} + +/// `align-self`:auto | stretch | flex-start | flex-end | center | baseline。 +fn parse_align_self(input: &mut Parser<'_>) -> Result<AlignSelfValue, ()> { + let Token::Ident(name) = input.next().map_err(|_| ())? else { + return Err(()); + }; + if name.eq_ignore_ascii_case("auto") { + Ok(AlignSelfValue::Auto) + } else if name.eq_ignore_ascii_case("stretch") { + Ok(AlignSelfValue::Stretch) + } else if name.eq_ignore_ascii_case("flex-start") || name.eq_ignore_ascii_case("start") { + Ok(AlignSelfValue::FlexStart) + } else if name.eq_ignore_ascii_case("flex-end") || name.eq_ignore_ascii_case("end") { + Ok(AlignSelfValue::FlexEnd) + } else if name.eq_ignore_ascii_case("center") { + Ok(AlignSelfValue::Center) + } else if name.eq_ignore_ascii_case("baseline") { + Ok(AlignSelfValue::Baseline) + } else { + Err(()) + } +} + +/// `row-gap` / `column-gap`:<length> | <percentage> | normal +/// (CSS Box Alignment §6;`auto` 不是合法 gap 值,按无效声明丢弃)。 +fn parse_gap(input: &mut Parser<'_>) -> Result<GapValue, ()> { + match input.next().map_err(|_| ())? { + Token::Ident(name) if name.eq_ignore_ascii_case("normal") => Ok(GapValue::Normal), + Token::Number { value: 0.0, .. } => Ok(GapValue::Length(0.0)), + Token::Percentage { unit_value, .. } => Ok(GapValue::Percent(*unit_value)), + Token::Dimension { value, unit, .. } => { + length_to_px(*value, unit).map(GapValue::Length).ok_or(()) + } + _ => Err(()), + } +} + +/// `grid-auto-flow`:row | column | row dense | column dense。 +fn parse_grid_auto_flow(input: &mut Parser<'_>) -> Result<GridAutoFlowValue, ()> { + let first = match input.next().map_err(|_| ())? { + Token::Ident(name) if name.eq_ignore_ascii_case("row") => GridAutoFlowValue::Row, + Token::Ident(name) if name.eq_ignore_ascii_case("column") => GridAutoFlowValue::Column, + _ => return Err(()), + }; + // 可选 `dense` 后缀 + if input + .try_parse(|i| i.expect_ident_matching("dense").map(|_| ())) + .is_ok() + { + if input.expect_exhausted().is_err() { + return Err(()); + } + return Ok(match first { + GridAutoFlowValue::Row => GridAutoFlowValue::RowDense, + GridAutoFlowValue::Column => GridAutoFlowValue::ColumnDense, + _ => unreachable!(), + }); + } + if input.expect_exhausted().is_err() { + return Err(()); + } + Ok(first) +} + +/// `grid-template-columns` / `grid-template-rows` 的轨道列表解析 +/// (CSS Grid §7.2/§7.3;空白分隔轨道,支持 `minmax()`)。 +fn parse_grid_track_list(input: &mut Parser<'_>) -> Result<GridTrackList, ()> { + let mut tracks = Vec::new(); + let mut first = true; + while !input.is_exhausted() { + if !first && input.try_parse(|i| i.expect_whitespace()).is_err() { + return Err(()); + } + first = false; + tracks.push(parse_grid_track(input)?); + } + Ok(GridTrackList { tracks }) +} + +/// 单条 grid 轨道尺寸函数。 +fn parse_grid_track(input: &mut Parser<'_>) -> Result<GridTrack, ()> { + if input + .try_parse(|i| i.expect_function_matching("minmax").map(|_| ())) + .is_ok() + { + return input + .parse_nested_block(|i| { + let a = + parse_grid_track_size(i).map_err(|_| ParseError::<()>::unexpected_token())?; + i.expect_comma() + .map_err(|_| ParseError::<()>::unexpected_token())?; + let b = + parse_grid_track_size(i).map_err(|_| ParseError::<()>::unexpected_token())?; + i.expect_exhausted() + .map_err(|_| ParseError::<()>::unexpected_token())?; + Ok(GridTrack::MinMax(Box::new(a), Box::new(b))) + }) + .map_err(|_| ()); + } + parse_grid_track_size(input) +} + +/// 单段轨道尺寸(`minmax` 内的一段):<length> | <percentage> | <flex> | auto。 +fn parse_grid_track_size(input: &mut Parser<'_>) -> Result<GridTrack, ()> { + match input.next().map_err(|_| ())? { + Token::Ident(name) if name.eq_ignore_ascii_case("auto") => Ok(GridTrack::Auto), + Token::Number { value: 0.0, .. } => Ok(GridTrack::Length(0.0)), + Token::Percentage { unit_value, .. } => Ok(GridTrack::Percent(*unit_value)), + Token::Dimension { value, unit, .. } => { + if unit.eq_ignore_ascii_case("fr") { + Ok(GridTrack::Fr(*value)) + } else { + length_to_px(*value, unit).map(GridTrack::Length).ok_or(()) + } + } + _ => Err(()), + } +} + +/// `margin-*`:<length> | <percentage> | auto,长度可负。 +fn parse_margin(input: &mut Parser<'_>) -> Result<MarginValue, ()> { + match input.next().map_err(|_| ())? { + Token::Ident(name) if name.eq_ignore_ascii_case("auto") => Ok(MarginValue::Auto), + Token::Number { value: 0.0, .. } => Ok(MarginValue::Length(0.0)), + Token::Percentage { unit_value, .. } => Ok(MarginValue::Percent(*unit_value)), + Token::Dimension { value, unit, .. } => length_to_px(*value, unit) + .map(MarginValue::Length) + .ok_or(()), + _ => Err(()), + } +} + +/// `padding-*`:<length> | <percentage>,不接受 auto、负值非法。 +fn parse_padding(input: &mut Parser<'_>) -> Result<PaddingValue, ()> { + match input.next().map_err(|_| ())? { + Token::Number { value: 0.0, .. } => Ok(PaddingValue::Length(0.0)), + Token::Percentage { unit_value, .. } => Ok(PaddingValue::Percent(*unit_value)), + Token::Dimension { value, unit, .. } => { + if *value < 0.0 { + return Err(()); + } + length_to_px(*value, unit) + .map(PaddingValue::Length) + .ok_or(()) + } + _ => Err(()), + } +} + +/// `border-*-width`:<line-width>(<length [0,∞]> | thin | medium | thick)。 +fn parse_border_width(input: &mut Parser<'_>) -> Result<BorderWidthValue, ()> { + match input.next().map_err(|_| ())? { + Token::Ident(name) if name.eq_ignore_ascii_case("thin") => Ok(BorderWidthValue::Thin), + Token::Ident(name) if name.eq_ignore_ascii_case("medium") => Ok(BorderWidthValue::Medium), + Token::Ident(name) if name.eq_ignore_ascii_case("thick") => Ok(BorderWidthValue::Thick), + Token::Number { value: 0.0, .. } => Ok(BorderWidthValue::Length(0.0)), + Token::Dimension { value, unit, .. } => { + if *value < 0.0 { + return Err(()); + } + length_to_px(*value, unit) + .map(BorderWidthValue::Length) + .ok_or(()) + } + _ => Err(()), + } +} + +/// `border-*-style`:<line-style>(10 个关键字)。 +fn parse_border_style(input: &mut Parser<'_>) -> Result<BorderStyle, ()> { + let Token::Ident(name) = input.next().map_err(|_| ())? else { + return Err(()); + }; + const STYLES: [(&str, BorderStyle); 10] = [ + ("none", BorderStyle::None), + ("hidden", BorderStyle::Hidden), + ("solid", BorderStyle::Solid), + ("dashed", BorderStyle::Dashed), + ("dotted", BorderStyle::Dotted), + ("double", BorderStyle::Double), + ("groove", BorderStyle::Groove), + ("ridge", BorderStyle::Ridge), + ("inset", BorderStyle::Inset), + ("outset", BorderStyle::Outset), + ]; + STYLES + .into_iter() + .find(|(keyword, _)| keyword.eq_ignore_ascii_case(name)) + .map(|(_, style)| style) + .ok_or(()) +} + +/// `border-*-color`:<color> | currentcolor。 +fn parse_border_color(input: &mut Parser<'_>) -> Result<BorderColorValue, ()> { + if let Ok(rgba) = input.try_parse(parse_color) { + return Ok(BorderColorValue::Rgba(rgba)); + } + match input.next().map_err(|_| ())? { + Token::Ident(name) if name.eq_ignore_ascii_case("currentcolor") => { + Ok(BorderColorValue::CurrentColor) + } + _ => Err(()), + } +} + +/// 以下为简写展开(parser 模块)复用的单值解析入口。 +pub(crate) fn parse_margin_value(input: &mut Parser<'_>) -> Result<MarginValue, ()> { + parse_margin(input) +} + +pub(crate) fn parse_padding_value(input: &mut Parser<'_>) -> Result<PaddingValue, ()> { + parse_padding(input) +} + +pub(crate) fn parse_border_width_value(input: &mut Parser<'_>) -> Result<BorderWidthValue, ()> { + parse_border_width(input) +} + +pub(crate) fn parse_border_style_value(input: &mut Parser<'_>) -> Result<BorderStyle, ()> { + parse_border_style(input) +} + +pub(crate) fn parse_border_color_value(input: &mut Parser<'_>) -> Result<BorderColorValue, ()> { + parse_border_color(input) +} + +/// `inset` 简写复用单值解析入口。 +pub(crate) fn parse_inset_value(input: &mut Parser<'_>) -> Result<InsetValue, ()> { + parse_inset(input) +} + +/// `gap` 简写复用单值解析入口。 +pub(crate) fn parse_gap_value(input: &mut Parser<'_>) -> Result<GapValue, ()> { + parse_gap(input) +} + +fn parse_display(input: &mut Parser<'_>) -> Result<DisplayValue, ()> { + let Token::Ident(name) = input.next().map_err(|_| ())? else { + return Err(()); + }; + if name.eq_ignore_ascii_case("inline") { + return Ok(DisplayValue::Inline); + } + if name.eq_ignore_ascii_case("block") { + return Ok(DisplayValue::Block); + } + if name.eq_ignore_ascii_case("list-item") { + return Ok(DisplayValue::ListItem); + } + if name.eq_ignore_ascii_case("inline-block") { + return Ok(DisplayValue::InlineBlock); + } + if name.eq_ignore_ascii_case("flow-root") { + return Ok(DisplayValue::FlowRoot); + } + if name.eq_ignore_ascii_case("flex") { + return Ok(DisplayValue::Flex); + } + if name.eq_ignore_ascii_case("inline-flex") { + return Ok(DisplayValue::InlineFlex); + } + if name.eq_ignore_ascii_case("grid") { + return Ok(DisplayValue::Grid); + } + if name.eq_ignore_ascii_case("inline-grid") { + return Ok(DisplayValue::InlineGrid); + } + if name.eq_ignore_ascii_case("table") { + return Ok(DisplayValue::Table); + } + if name.eq_ignore_ascii_case("inline-table") { + return Ok(DisplayValue::InlineTable); + } + if name.eq_ignore_ascii_case("contents") { + return Ok(DisplayValue::Contents); + } + if name.eq_ignore_ascii_case("none") { + return Ok(DisplayValue::None); + } + const INTERNAL: [(&str, &str); 8] = [ + ("table-row-group", "table-row-group"), + ("table-header-group", "table-header-group"), + ("table-footer-group", "table-footer-group"), + ("table-row", "table-row"), + ("table-cell", "table-cell"), + ("table-column-group", "table-column-group"), + ("table-column", "table-column"), + ("table-caption", "table-caption"), + ]; + for (keyword, label) in INTERNAL { + if name.eq_ignore_ascii_case(keyword) { + return Ok(DisplayValue::TableInternal(label)); + } + } + Err(()) +} + +fn parse_text_align(input: &mut Parser<'_>) -> Result<TextAlignValue, ()> { + let Token::Ident(name) = input.next().map_err(|_| ())? else { + return Err(()); + }; + if name.eq_ignore_ascii_case("start") { + return Ok(TextAlignValue::Start); + } + if name.eq_ignore_ascii_case("end") { + return Ok(TextAlignValue::End); + } + if name.eq_ignore_ascii_case("left") { + return Ok(TextAlignValue::Left); + } + if name.eq_ignore_ascii_case("right") { + return Ok(TextAlignValue::Right); + } + if name.eq_ignore_ascii_case("center") { + return Ok(TextAlignValue::Center); + } + if name.eq_ignore_ascii_case("justify") { + return Ok(TextAlignValue::Justify); + } + if name.eq_ignore_ascii_case("match-parent") { + return Ok(TextAlignValue::MatchParent); + } + if name.eq_ignore_ascii_case("justify-all") { + return Ok(TextAlignValue::JustifyAll); + } + Err(()) +} + +fn parse_font_style(input: &mut Parser<'_>) -> Result<FontStyleValue, ()> { + let Token::Ident(name) = input.next().map_err(|_| ())? else { + return Err(()); + }; + if name.eq_ignore_ascii_case("normal") { + return Ok(FontStyleValue::Normal); + } + if name.eq_ignore_ascii_case("italic") { + return Ok(FontStyleValue::Italic); + } + if name.eq_ignore_ascii_case("oblique") { + // oblique [ <angle> | none ]? + let angle = input.try_parse(parse_angle).ok(); + if angle.is_none() + && (input.try_parse(|i| i.expect_ident_matching("none").map_err(|_| ()))).is_err() + && input.expect_exhausted().is_err() + { + return Err(()); + } + return Ok(FontStyleValue::Oblique(angle)); + } + Err(()) +} + +/// 解析角度并折算为角度制。 +fn parse_angle(input: &mut Parser<'_>) -> Result<f32, ()> { + match input.next().map_err(|_| ())? { + Token::Dimension { value, unit, .. } => { + if unit.eq_ignore_ascii_case("deg") { + Ok(*value) + } else if unit.eq_ignore_ascii_case("grad") { + Ok(*value * 360.0 / 400.0) + } else if unit.eq_ignore_ascii_case("rad") { + Ok(value.to_degrees()) + } else if unit.eq_ignore_ascii_case("turn") { + Ok(*value * 360.0) + } else { + Err(()) + } + } + _ => Err(()), + } +} + +/// `<length-percentage>` 折算为 px;返回 `None` 表示该单位不受支持。 +fn length_to_px(value: f32, unit: &str) -> Option<f32> { + if unit.eq_ignore_ascii_case("px") { + Some(value) + } else if unit.eq_ignore_ascii_case("pt") { + // 1pt = 1/72in,1in = 96px(CSS Values 4 绝对长度定义) + Some(value * 96.0 / 72.0) + } else if unit.eq_ignore_ascii_case("pc") { + Some(value * 16.0) + } else if unit.eq_ignore_ascii_case("in") { + Some(value * 96.0) + } else if unit.eq_ignore_ascii_case("cm") { + Some(value * 96.0 / 2.54) + } else if unit.eq_ignore_ascii_case("mm") { + Some(value * 96.0 / 25.4) + } else if unit.eq_ignore_ascii_case("q") { + Some(value * 96.0 / 101.6) + } else { + None + } +} + +fn parse_font_size(input: &mut Parser<'_>) -> Result<FontSizeValue, ()> { + match input.next().map_err(|_| ())? { + // <length> 为 0 时单位可省略(CSS Values 4) + Token::Number { value: 0.0, .. } => Ok(FontSizeValue::Px(0.0)), + Token::Number { .. } => Err(()), + Token::Percentage { unit_value, .. } => Ok(FontSizeValue::Percent(*unit_value)), + Token::Dimension { value, unit, .. } => { + if unit.eq_ignore_ascii_case("em") { + Ok(FontSizeValue::Em(*value)) + } else { + length_to_px(*value, unit).map(FontSizeValue::Px).ok_or(()) + } + } + Token::Ident(name) => { + if name.eq_ignore_ascii_case("xx-small") { + Ok(FontSizeValue::Absolute(AbsoluteSize::XxSmall)) + } else if name.eq_ignore_ascii_case("x-small") { + Ok(FontSizeValue::Absolute(AbsoluteSize::XSmall)) + } else if name.eq_ignore_ascii_case("small") { + Ok(FontSizeValue::Absolute(AbsoluteSize::Small)) + } else if name.eq_ignore_ascii_case("medium") { + Ok(FontSizeValue::Absolute(AbsoluteSize::Medium)) + } else if name.eq_ignore_ascii_case("large") { + Ok(FontSizeValue::Absolute(AbsoluteSize::Large)) + } else if name.eq_ignore_ascii_case("x-large") { + Ok(FontSizeValue::Absolute(AbsoluteSize::XLarge)) + } else if name.eq_ignore_ascii_case("xx-large") { + Ok(FontSizeValue::Absolute(AbsoluteSize::XxLarge)) + } else if name.eq_ignore_ascii_case("xxx-large") { + Ok(FontSizeValue::Absolute(AbsoluteSize::XxxLarge)) + } else if name.eq_ignore_ascii_case("larger") { + Ok(FontSizeValue::Larger) + } else if name.eq_ignore_ascii_case("smaller") { + Ok(FontSizeValue::Smaller) + } else { + Err(()) + } + } + _ => Err(()), + } +} + +fn parse_font_weight(input: &mut Parser<'_>) -> Result<FontWeightValue, ()> { + match input.next().map_err(|_| ())? { + Token::Number { value, .. } => { + // CSS Fonts 4:<number [1,1000]>,越界无效 + if (1.0..=1000.0).contains(value) { + Ok(FontWeightValue::Weight(*value)) + } else { + Err(()) + } + } + Token::Ident(name) => { + if name.eq_ignore_ascii_case("normal") { + Ok(FontWeightValue::Weight(400.0)) + } else if name.eq_ignore_ascii_case("bold") { + Ok(FontWeightValue::Weight(700.0)) + } else if name.eq_ignore_ascii_case("bolder") { + Ok(FontWeightValue::Bolder) + } else if name.eq_ignore_ascii_case("lighter") { + Ok(FontWeightValue::Lighter) + } else { + Err(()) + } + } + _ => Err(()), + } +} + +fn parse_font_family(input: &mut Parser<'_>) -> Result<Vec<FontFamilyValue>, ()> { + input + .parse_comma_separated(|input| { + parse_family_item(input).map_err(|_| ParseError::<()>::unexpected_token()) + }) + .map_err(|_| ()) +} + +/// 解析一个字体族名:`<string>` 或一串 `<custom-ident>`(以空白分隔)。 +/// +/// 在 `!`(`!important` 前缀,不属于族名语法)处停止——`try_parse` 返回 +/// `Err` 会还原位置,`!` 留给调用方的 `parse_important`;EOF 同样停止。 +fn parse_family_item(input: &mut Parser<'_>) -> Result<FontFamilyValue, ()> { + let mut tokens = Vec::new(); + loop { + let token = input.try_parse(|i| match i.next_including_whitespace() { + Ok(Token::Delimiter('!')) => Err(()), + Ok(token) => Ok(token.clone()), + Err(_) => Err(()), + }); + match token { + Ok(token) => tokens.push(token), + Err(_) => break, + } + } + family_from_tokens(&tokens) +} + +/// 把族名的 token 序列归一化为 [`FontFamilyValue`]:去首尾空白、中部空白 +/// 折叠为单个空格;无引号的单词族名映射 generic。 +fn family_from_tokens(tokens: &[Token<'_>]) -> Result<FontFamilyValue, ()> { + let mut parts: Vec<String> = Vec::new(); + let mut current: Option<String> = None; + let mut quoted = false; + for token in tokens { + match token { + Token::WhiteSpace(_) => { + if let Some(word) = current.take() { + parts.push(word); + } + } + Token::Ident(name) => { + current.get_or_insert_with(String::new).push_str(name); + } + Token::QuotedString(text) => { + if current.is_some() || !parts.is_empty() { + // 字符串只能单独成族名(CSS Fonts 4 §2.3 语法) + return Err(()); + } + quoted = true; + parts.push(text.to_string()); + } + _ => return Err(()), + } + } + if let Some(word) = current.take() { + parts.push(word); + } + + if parts.is_empty() { + return Err(()); + } + // 带引号的 "serif" 是名为 serif 的普通族名,不映射 generic + if parts.len() == 1 + && !quoted + && let Some(generic) = generic_family(&parts[0]) + { + return Ok(FontFamilyValue::Generic(generic)); + } + Ok(FontFamilyValue::Family(parts.join(" "))) +} + +/// `font` 简写值解析并展开为 longhand(CSS Fonts 4 §3.3)。 +/// +/// 语法:`[ <'font-style'> || <font-variant-css2> || <'font-weight'> || +/// <font-width-css3> ]? <'font-size'> [ / <'line-height'> ]? <'font-family'>#`—— +/// `||` 成分任意顺序、每项至多一次;缺省成分按简写语义重置为 initial。 +/// 偏差:`font-variant-css2`(`small-caps`)与 `<font-width-css3>`(宽度 +/// 关键字/百分比)无对应 longhand,按语法接受后丢弃;系统字体关键字 +/// (`caption` 等)整条无效。 +pub(crate) fn parse_font_shorthand( + input: &mut Parser<'_>, +) -> Result<Vec<(PropertyId, PropertyValue)>, ()> { + if is_system_family_name(input) { + return Err(()); + } + let mut style: Option<FontStyleValue> = None; + let mut weight: Option<FontWeightValue> = None; + let mut small_caps_seen = false; + let mut width_seen = false; + // `normal` 可出现在 style / variant / weight / width 四个槽位; + // style 与 weight 的解析器各自吞掉一份 normal,这里再放行两份。 + let mut extra_normals = 0usize; + loop { + if style.is_none() + && let Ok(value) = input.try_parse(parse_font_style) + { + style = Some(value); + continue; + } + if weight.is_none() + && let Ok(value) = input.try_parse(parse_font_weight) + { + weight = Some(value); + continue; + } + if extra_normals < 2 && try_parse_ident(input, "normal") { + extra_normals += 1; + continue; + } + if !small_caps_seen && try_parse_ident(input, "small-caps") { + small_caps_seen = true; + continue; + } + if !width_seen && try_parse_font_width(input) { + width_seen = true; + continue; + } + break; + } + + let size = parse_font_size(input)?; + let line_height = if input.try_parse(|i| i.expect_delim('/')).is_ok() { + Some(parse_line_height(input)?) + } else { + None + }; + let families = parse_font_family(input)?; + + Ok(vec![ + ( + PropertyId::FontStyle, + PropertyValue::FontStyle(style.unwrap_or(FontStyleValue::Normal)), + ), + ( + PropertyId::FontWeight, + PropertyValue::FontWeight(weight.unwrap_or(FontWeightValue::Weight(400.0))), + ), + (PropertyId::FontSize, PropertyValue::FontSize(size)), + ( + PropertyId::LineHeight, + PropertyValue::LineHeight(line_height.unwrap_or(LineHeightValue::Normal)), + ), + (PropertyId::FontFamily, PropertyValue::FontFamily(families)), + ]) +} + +/// `font` 简写的系统字体关键字(CSS Fonts 4 §3.3 `<system-family-name>`): +/// 依赖 UA 系统设置且要求重置全部子属性,本层不支持。 +fn is_system_family_name(input: &mut Parser<'_>) -> bool { + const SYSTEM: [&str; 6] = [ + "caption", + "icon", + "menu", + "message-box", + "small-caption", + "status-bar", + ]; + input + .try_parse(|i| match i.next() { + Ok(Token::Ident(name)) if SYSTEM.iter().any(|k| name.eq_ignore_ascii_case(k)) => Ok(()), + _ => Err(()), + }) + .is_ok() +} + +/// 尝试消费一个指定关键字(ASCII case-insensitive),命中则消费并返回真。 +fn try_parse_ident(input: &mut Parser<'_>, expected: &str) -> bool { + input + .try_parse(|i| match i.next() { + Ok(Token::Ident(name)) if name.eq_ignore_ascii_case(expected) => Ok(()), + _ => Err(()), + }) + .is_ok() +} + +/// `<font-width-css3>`:宽度关键字或非负百分比。本层无 font-stretch +/// longhand,按语法接受后丢弃(返回是否命中)。 +fn try_parse_font_width(input: &mut Parser<'_>) -> bool { + const KEYWORDS: [&str; 8] = [ + "ultra-condensed", + "extra-condensed", + "condensed", + "semi-condensed", + "semi-expanded", + "expanded", + "extra-expanded", + "ultra-expanded", + ]; + input + .try_parse(|i| match i.next() { + Ok(Token::Ident(name)) if KEYWORDS.iter().any(|k| name.eq_ignore_ascii_case(k)) => { + Ok(()) + } + Ok(Token::Percentage { unit_value, .. }) if *unit_value >= 0.0 => Ok(()), + _ => Err(()), + }) + .is_ok() +} + +/// 无引号的 generic 族关键字 +/// (CSS Fonts 4 §2.3:serif、sans-serif、cursive、fantasy、monospace、 +/// system-ui、math、emoji、fangsong、ui-serif、ui-sans-serif、ui-monospace、 +/// ui-rounded)。 +fn generic_family(name: &str) -> Option<&'static str> { + const GENERICS: [&str; 13] = [ + "serif", + "sans-serif", + "cursive", + "fantasy", + "monospace", + "system-ui", + "math", + "emoji", + "fangsong", + "ui-serif", + "ui-sans-serif", + "ui-monospace", + "ui-rounded", + ]; + GENERICS + .into_iter() + .find(|generic| generic.eq_ignore_ascii_case(name)) +} + +/// 解析 `<color>`([CSS Color 4 §5](https://drafts.csswg.org/css-color-4/#color-syntax)): +/// hex、`rgb()` / `rgba()`、`hsl()` / `hsla()`(现代与 legacy 逗号语法)、 +/// 命名色与 `transparent`。 +pub(crate) fn parse_color(input: &mut Parser<'_>) -> Result<Rgba, ()> { + let token = input.next().map_err(|_| ())?; + match token { + // `#fff` 这类合法标识符形式的 hash 会词法为 IDHash,与 Hash 同义 + Token::Hash(hash) | Token::IDHash(hash) => parse_hex(hash), + Token::Ident(name) => { + if name.eq_ignore_ascii_case("transparent") { + Ok(Rgba::transparent()) + } else if name.eq_ignore_ascii_case("currentcolor") { + // 依赖元素上下文,本轮不支持(见模块文档偏差) + Err(()) + } else { + named_color(name).ok_or(()) + } + } + Token::Function(name) => { + if name.eq_ignore_ascii_case("rgb") || name.eq_ignore_ascii_case("rgba") { + input + .parse_nested_block(|input| { + parse_rgb_arguments(input).map_err(|_| ParseError::<()>::unexpected_token()) + }) + .map_err(|_| ()) + } else if name.eq_ignore_ascii_case("hsl") || name.eq_ignore_ascii_case("hsla") { + input + .parse_nested_block(|input| { + parse_hsl_arguments(input).map_err(|_| ParseError::<()>::unexpected_token()) + }) + .map_err(|_| ()) + } else { + Err(()) + } + } + _ => Err(()), + } +} + +/// CSS Color 4 §6.1 命名色表(148 项,由规范表格生成)。 +const NAMED_COLORS: [(&str, u8, u8, u8); 148] = [ + ("aliceblue", 0xf0, 0xf8, 0xff), + ("antiquewhite", 0xfa, 0xeb, 0xd7), + ("aqua", 0x00, 0xff, 0xff), + ("aquamarine", 0x7f, 0xff, 0xd4), + ("azure", 0xf0, 0xff, 0xff), + ("beige", 0xf5, 0xf5, 0xdc), + ("bisque", 0xff, 0xe4, 0xc4), + ("black", 0x00, 0x00, 0x00), + ("blanchedalmond", 0xff, 0xeb, 0xcd), + ("blue", 0x00, 0x00, 0xff), + ("blueviolet", 0x8a, 0x2b, 0xe2), + ("brown", 0xa5, 0x2a, 0x2a), + ("burlywood", 0xde, 0xb8, 0x87), + ("cadetblue", 0x5f, 0x9e, 0xa0), + ("chartreuse", 0x7c, 0xfc, 0x00), + ("chocolate", 0xd2, 0x69, 0x1e), + ("coral", 0xff, 0x7f, 0x50), + ("cornflowerblue", 0x64, 0x95, 0xed), + ("cornsilk", 0xff, 0xf8, 0xdc), + ("crimson", 0xdc, 0x14, 0x3c), + ("cyan", 0x00, 0xff, 0xff), + ("darkblue", 0x00, 0x00, 0x8b), + ("darkcyan", 0x00, 0x8b, 0x8b), + ("darkgoldenrod", 0xb8, 0x86, 0x0b), + ("darkgray", 0xa9, 0xa9, 0xa9), + ("darkgreen", 0x00, 0x80, 0x00), + ("darkgrey", 0xa9, 0xa9, 0xa9), + ("darkkhaki", 0xbd, 0xb7, 0x6b), + ("darkmagenta", 0x8b, 0x00, 0x8b), + ("darkolivegreen", 0x55, 0x6b, 0x2f), + ("darkorange", 0xff, 0x8c, 0x00), + ("darkorchid", 0x99, 0x32, 0xcc), + ("darkred", 0x8b, 0x00, 0x00), + ("darksalmon", 0xe9, 0x96, 0x7a), + ("darkseagreen", 0x8f, 0xbc, 0x8f), + ("darkslateblue", 0x48, 0x3d, 0x8b), + ("darkslategray", 0x2f, 0x4f, 0x4f), + ("darkslategrey", 0x2f, 0x4f, 0x4f), + ("darkturquoise", 0x00, 0xce, 0xd1), + ("darkviolet", 0x94, 0x00, 0xd3), + ("deeppink", 0xff, 0x14, 0x93), + ("deepskyblue", 0x00, 0xbf, 0xff), + ("dimgray", 0x69, 0x69, 0x69), + ("dimgrey", 0x69, 0x69, 0x69), + ("dodgerblue", 0x1e, 0x90, 0xff), + ("firebrick", 0xb2, 0x22, 0x22), + ("floralwhite", 0xff, 0xfa, 0xf0), + ("forestgreen", 0x22, 0x8b, 0x22), + ("fuchsia", 0xff, 0x00, 0xff), + ("gainsboro", 0xdc, 0xdc, 0xdc), + ("ghostwhite", 0xf8, 0xf8, 0xff), + ("gold", 0xff, 0xd7, 0x00), + ("goldenrod", 0xda, 0xa5, 0x20), + ("gray", 0x80, 0x80, 0x80), + ("green", 0x00, 0x80, 0x00), + ("greenyellow", 0xad, 0xff, 0x2f), + ("grey", 0x80, 0x80, 0x80), + ("honeydew", 0xf0, 0xff, 0xf0), + ("hotpink", 0xff, 0x69, 0xb4), + ("indianred", 0xcd, 0x5c, 0x5c), + ("indigo", 0x4b, 0x00, 0x82), + ("ivory", 0xff, 0xff, 0xf0), + ("khaki", 0xf0, 0xe6, 0x8c), + ("lavender", 0xe6, 0xe6, 0xfa), + ("lavenderblush", 0xff, 0xf0, 0xf5), + ("lawngreen", 0x7c, 0xfc, 0x00), + ("lemonchiffon", 0xff, 0xfa, 0xcd), + ("lightblue", 0xad, 0xd8, 0xe6), + ("lightcoral", 0xf0, 0x80, 0x80), + ("lightcyan", 0xe0, 0xff, 0xff), + ("lightgoldenrodyellow", 0xfa, 0xfa, 0xd2), + ("lightgray", 0xd3, 0xd3, 0xd3), + ("lightgreen", 0x90, 0xee, 0x90), + ("lightgrey", 0xd3, 0xd3, 0xd3), + ("lightpink", 0xff, 0xb6, 0xc1), + ("lightsalmon", 0xff, 0xa0, 0x7a), + ("lightseagreen", 0x20, 0xb2, 0xaa), + ("lightskyblue", 0x87, 0xce, 0xfa), + ("lightslategray", 0x77, 0x88, 0x99), + ("lightslategrey", 0x77, 0x88, 0x99), + ("lightsteelblue", 0xb0, 0xc4, 0xde), + ("lightyellow", 0xff, 0xff, 0xe0), + ("lime", 0x00, 0xff, 0x00), + ("limegreen", 0x32, 0xcd, 0x32), + ("linen", 0xfa, 0xf0, 0xe6), + ("magenta", 0xff, 0x00, 0xff), + ("maroon", 0x80, 0x00, 0x00), + ("mediumaquamarine", 0x66, 0xcd, 0xaa), + ("mediumblue", 0x00, 0x00, 0xcd), + ("mediumorchid", 0xba, 0x55, 0xd3), + ("mediumpurple", 0x93, 0x70, 0xdb), + ("mediumseagreen", 0x3c, 0xb3, 0x71), + ("mediumslateblue", 0x7b, 0x68, 0xee), + ("mediumspringgreen", 0x00, 0xfa, 0x9a), + ("mediumturquoise", 0x48, 0xd1, 0xcc), + ("mediumvioletred", 0xc7, 0x15, 0x85), + ("midnightblue", 0x19, 0x19, 0x70), + ("mintcream", 0xf5, 0xff, 0xfa), + ("mistyrose", 0xff, 0xe4, 0xe1), + ("moccasin", 0xff, 0xe4, 0xb5), + ("navajowhite", 0xff, 0xde, 0xad), + ("navy", 0x00, 0x00, 0x80), + ("oldlace", 0xfd, 0xf5, 0xe6), + ("olive", 0x80, 0x80, 0x00), + ("olivedrab", 0x6b, 0x8e, 0x23), + ("orange", 0xff, 0xa5, 0x00), + ("orangered", 0xff, 0x45, 0x00), + ("orchid", 0xda, 0x70, 0xd6), + ("palegoldenrod", 0xee, 0xe8, 0xaa), + ("palegreen", 0x98, 0xfb, 0x98), + ("paleturquoise", 0xaf, 0xee, 0xee), + ("palevioletred", 0xdb, 0x70, 0x93), + ("papayawhip", 0xff, 0xef, 0xd5), + ("peachpuff", 0xff, 0xda, 0xb9), + ("peru", 0xcd, 0x85, 0x3f), + ("pink", 0xff, 0xc0, 0xcb), + ("plum", 0xdd, 0xa0, 0xdd), + ("powderblue", 0xb0, 0xe0, 0xe6), + ("purple", 0x80, 0x00, 0x80), + ("rebeccapurple", 0x66, 0x33, 0x99), + ("red", 0xff, 0x00, 0x00), + ("rosybrown", 0xbc, 0x8f, 0x8f), + ("royalblue", 0x41, 0x69, 0xe1), + ("saddlebrown", 0x8b, 0x45, 0x13), + ("salmon", 0xfa, 0x80, 0x72), + ("sandybrown", 0xf4, 0xa4, 0x60), + ("seagreen", 0x2e, 0x8b, 0x57), + ("seashell", 0xff, 0xf5, 0xee), + ("sienna", 0xa0, 0x52, 0x2d), + ("silver", 0xc0, 0xc0, 0xc0), + ("skyblue", 0x87, 0xce, 0xeb), + ("slateblue", 0x6a, 0x5a, 0xcd), + ("slategray", 0x70, 0x80, 0x90), + ("slategrey", 0x70, 0x80, 0x90), + ("snow", 0xff, 0xfa, 0xfa), + ("springgreen", 0x00, 0xff, 0x7f), + ("steelblue", 0x46, 0x82, 0xb4), + ("tan", 0xd2, 0xb4, 0x8c), + ("teal", 0x00, 0x80, 0x80), + ("thistle", 0xd8, 0xbf, 0xd8), + ("tomato", 0xff, 0x63, 0x47), + ("turquoise", 0x40, 0xe0, 0xd0), + ("violet", 0xee, 0x82, 0xee), + ("wheat", 0xf5, 0xde, 0xb3), + ("white", 0xff, 0xff, 0xff), + ("whitesmoke", 0xf5, 0xf5, 0xf5), + ("yellow", 0xff, 0xff, 0x00), + ("yellowgreen", 0x9a, 0xcd, 0x32), +]; + +fn named_color(name: &str) -> Option<Rgba> { + NAMED_COLORS + .iter() + .find(|(keyword, ..)| keyword.eq_ignore_ascii_case(name)) + .map(|&(_, r, g, b)| Rgba::opaque(r, g, b)) +} + +/// hex 记法:`#rgb` `#rgba` `#rrggbb` `#rrggbbaa`(CSS Color 4 §5.2)。 +fn parse_hex(hash: &str) -> Result<Rgba, ()> { + fn hex_digit(c: u8) -> Option<u8> { + match c { + b'0'..=b'9' => Some(c - b'0'), + b'a'..=b'f' => Some(c - b'a' + 10), + b'A'..=b'F' => Some(c - b'A' + 10), + _ => None, + } + } + let bytes = hash.as_bytes(); + let parse_pair = |slice: &[u8]| -> Option<u8> { + Some(hex_digit(*slice.first()?)? * 16 + hex_digit(*slice.get(1)?)?) + }; + match bytes.len() { + 3 => { + let digits: Option<Vec<u8>> = bytes.iter().map(|&c| hex_digit(c)).collect(); + let d = digits.ok_or(())?; + Ok(Rgba::opaque(d[0] * 17, d[1] * 17, d[2] * 17)) + } + 4 => { + let digits: Option<Vec<u8>> = bytes.iter().map(|&c| hex_digit(c)).collect(); + let d = digits.ok_or(())?; + Ok(Rgba { + r: d[0] * 17, + g: d[1] * 17, + b: d[2] * 17, + a: d[3] * 17, + }) + } + 6 => Ok(Rgba::opaque( + parse_pair(&bytes[0..2]).ok_or(())?, + parse_pair(&bytes[2..4]).ok_or(())?, + parse_pair(&bytes[4..6]).ok_or(())?, + )), + 8 => Ok(Rgba { + r: parse_pair(&bytes[0..2]).ok_or(())?, + g: parse_pair(&bytes[2..4]).ok_or(())?, + b: parse_pair(&bytes[4..6]).ok_or(())?, + a: parse_pair(&bytes[6..8]).ok_or(())?, + }), + _ => Err(()), + } +} + +/// 颜色分量:数字或百分比,可选 `none` 视为本轮不支持。 +enum Component { + Number(f32), + Percentage(f32), +} + +fn parse_component(input: &mut Parser<'_>) -> Result<Component, ()> { + match input.next().map_err(|_| ())? { + Token::Number { value, .. } => Ok(Component::Number(*value)), + Token::Percentage { unit_value, .. } => Ok(Component::Percentage(*unit_value * 100.0)), + _ => Err(()), + } +} + +/// alpha 分量:数字(0–1)或百分比(0–100%)。 +fn parse_alpha(input: &mut Parser<'_>) -> Result<f32, ()> { + let component = parse_component(input)?; + Ok(match component { + Component::Number(value) => value, + Component::Percentage(value) => value / 100.0, + }) +} + +/// 分量 → 8bit 通道:数字按 0–255、百分比按 0–100% 折算后 clamp 并四舍五入 +/// (CSS Color 4:rgb() 分量超出范围时 clamp 到设备无关 0–255)。 +fn component_to_byte(component: Component) -> u8 { + let raw = match component { + Component::Number(value) => value, + Component::Percentage(value) => value * 255.0 / 100.0, + }; + raw.clamp(0.0, 255.0).round() as u8 +} + +/// rgb() / rgba() 的参数:现代空白语法(可带 `/ alpha`)与 legacy 逗号语法 +/// (CSS Color 4 §5.3)。 +fn parse_rgb_arguments(input: &mut Parser<'_>) -> Result<Rgba, ()> { + let first = parse_component(input)?; + let comma = input.try_parse(Parser::expect_comma).is_ok(); + + let (red, green, blue, alpha) = if comma { + let green = parse_component(input)?; + input.expect_comma().map_err(|_| ())?; + let blue = parse_component(input)?; + let alpha = if input.try_parse(Parser::expect_comma).is_ok() { + parse_alpha(input)? + } else { + 1.0 + }; + (first, green, blue, alpha) + } else { + let green = parse_component(input)?; + let blue = parse_component(input)?; + let alpha = if input.try_parse(|i| i.expect_delim('/')).is_ok() { + parse_alpha(input)? + } else { + 1.0 + }; + (first, green, blue, alpha) + }; + + if input.expect_exhausted().is_err() { + return Err(()); + } + Ok(Rgba { + r: component_to_byte(red), + g: component_to_byte(green), + b: component_to_byte(blue), + a: (alpha.clamp(0.0, 1.0) * 255.0).round() as u8, + }) +} + +/// hsl() / hsla() 的参数(CSS Color 4 §7)。 +fn parse_hsl_arguments(input: &mut Parser<'_>) -> Result<Rgba, ()> { + let hue = parse_hue(input)?; + let comma = input.try_parse(Parser::expect_comma).is_ok(); + let (saturation, lightness, alpha) = if comma { + let saturation = parse_percentage(input)?; + input.expect_comma().map_err(|_| ())?; + let lightness = parse_percentage(input)?; + let alpha = if input.try_parse(Parser::expect_comma).is_ok() { + parse_alpha(input)? + } else { + 1.0 + }; + (saturation, lightness, alpha) + } else { + let saturation = parse_percentage(input)?; + let lightness = parse_percentage(input)?; + let alpha = if input.try_parse(|i| i.expect_delim('/')).is_ok() { + parse_alpha(input)? + } else { + 1.0 + }; + (saturation, lightness, alpha) + }; + if input.expect_exhausted().is_err() { + return Err(()); + } + Ok(hsl_to_rgb( + hue, + saturation / 100.0, + lightness / 100.0, + alpha, + )) +} + +/// `<hue>`:裸数字(度)或角度 dimension。 +fn parse_hue(input: &mut Parser<'_>) -> Result<f32, ()> { + match input.next().map_err(|_| ())? { + Token::Number { value, .. } => Ok(*value), + Token::Dimension { value, unit, .. } => { + if unit.eq_ignore_ascii_case("deg") { + Ok(*value) + } else if unit.eq_ignore_ascii_case("grad") { + Ok(*value * 360.0 / 400.0) + } else if unit.eq_ignore_ascii_case("rad") { + Ok(value.to_degrees()) + } else if unit.eq_ignore_ascii_case("turn") { + Ok(*value * 360.0) + } else { + Err(()) + } + } + _ => Err(()), + } +} + +/// 百分比的数值(`50%` → `50.0`),与 [`Component::Percentage`] 一致。 +fn parse_percentage(input: &mut Parser<'_>) -> Result<f32, ()> { + match input.next().map_err(|_| ())? { + Token::Percentage { unit_value, .. } => Ok(*unit_value * 100.0), + _ => Err(()), + } +} + +/// HSL → sRGB(CSS Color 4 §7.1 的转换算法)。 +fn hsl_to_rgb(hue: f32, saturation: f32, lightness: f32, alpha: f32) -> Rgba { + let t2 = if lightness <= 0.5 { + lightness * (1.0 + saturation) + } else { + lightness + saturation - lightness * saturation + }; + let t1 = 2.0 * lightness - t2; + let channel = |offset: f32| -> u8 { + let h = (hue.rem_euclid(360.0) + offset).rem_euclid(360.0); + let value = if h < 60.0 { + t1 + (t2 - t1) * h / 60.0 + } else if h < 180.0 { + t2 + } else if h < 240.0 { + t1 + (t2 - t1) * (240.0 - h) / 60.0 + } else { + t1 + }; + (value.clamp(0.0, 1.0) * 255.0).round() as u8 + }; + Rgba { + r: channel(120.0), + g: channel(0.0), + b: channel(-120.0), + a: (alpha.clamp(0.0, 1.0) * 255.0).round() as u8, + } +} + +#[allow(clippy::too_many_lines)] +#[cfg(test)] +mod tests { + use super::*; + + /// 单值解析入口:解析整段文本后要求耗尽。 + fn parse_typed(property: PropertyId, text: &str) -> Result<PropertyValue, ()> { + let mut parser = Parser::new(text); + let value = parse_property_value(property, &mut parser)?; + parser.expect_exhausted().map_err(|_| ())?; + Ok(value) + } + + fn parse_one(property: PropertyId, text: &str) -> PropertyValue { + parse_typed(property, text).expect("value should parse") + } + + fn parse_err(property: PropertyId, text: &str) { + assert!( + parse_typed(property, text).is_err(), + "{text} should not parse" + ); + } + + #[test] + fn position_inset_flex_grid_properties_parse() { + use PropertyValue::{ + AlignItems, AlignSelf, FlexDirection, FlexShrink, FlexWrap, Gap, GridAutoFlow, + GridTrack as GridTrackValue, Inset, JustifyContent, Position, + }; + // position + assert_eq!( + parse_one(PropertyId::Position, "absolute"), + Position(PositionValue::Absolute) + ); + assert_eq!( + parse_one(PropertyId::Position, "FIXED"), + Position(PositionValue::Fixed) + ); + parse_err(PropertyId::Position, "sticky"); + + // inset(四边 longhand 共用 InsetValue) + assert_eq!( + parse_one(PropertyId::Top, "10px"), + Inset(InsetValue::Length(10.0)) + ); + assert_eq!( + parse_one(PropertyId::Left, "50%"), + Inset(InsetValue::Percent(0.5)) + ); + assert_eq!( + parse_one(PropertyId::Bottom, "auto"), + Inset(InsetValue::Auto) + ); + + // flex-direction / flex-wrap / flex-shrink + assert_eq!( + parse_one(PropertyId::FlexDirection, "column"), + FlexDirection(FlexDirectionValue::Column) + ); + assert_eq!( + parse_one(PropertyId::FlexWrap, "wrap-reverse"), + FlexWrap(FlexWrapValue::WrapReverse) + ); + assert_eq!(parse_one(PropertyId::FlexShrink, "2"), FlexShrink(2.0)); + parse_err(PropertyId::FlexShrink, "-1"); + + // align-items / justify-content / align-self(兼容 start/end) + assert_eq!( + parse_one(PropertyId::AlignItems, "center"), + AlignItems(AlignItemsValue::Center) + ); + assert_eq!( + parse_one(PropertyId::AlignItems, "start"), + AlignItems(AlignItemsValue::FlexStart) + ); + assert_eq!( + parse_one(PropertyId::JustifyContent, "space-between"), + JustifyContent(JustifyContentValue::SpaceBetween) + ); + assert_eq!( + parse_one(PropertyId::AlignSelf, "auto"), + AlignSelf(AlignSelfValue::Auto) + ); + + // gap(auto 非法) + assert_eq!( + parse_one(PropertyId::RowGap, "8px"), + Gap(GapValue::Length(8.0)) + ); + assert_eq!( + parse_one(PropertyId::ColumnGap, "normal"), + Gap(GapValue::Normal) + ); + parse_err(PropertyId::RowGap, "auto"); + + // grid-auto-flow(可选 dense 后缀) + assert_eq!( + parse_one(PropertyId::GridAutoFlow, "row dense"), + GridAutoFlow(GridAutoFlowValue::RowDense) + ); + assert_eq!( + parse_one(PropertyId::GridAutoFlow, "column"), + GridAutoFlow(GridAutoFlowValue::Column) + ); + + // grid 轨道列表(含 minmax 与 fr) + assert_eq!( + parse_one(PropertyId::GridTemplateColumns, "100px 1fr auto"), + GridTrackValue(GridTrackList { + tracks: vec![ + GridTrack::Length(100.0), + GridTrack::Fr(1.0), + GridTrack::Auto, + ] + }) + ); + assert_eq!( + parse_one(PropertyId::GridTemplateRows, "minmax(50px, 1fr)"), + GridTrackValue(GridTrackList { + tracks: vec![GridTrack::MinMax( + Box::new(GridTrack::Length(50.0)), + Box::new(GridTrack::Fr(1.0)), + )] + }) + ); + // 无空白分隔 / 未知轨道关键字 → 整条声明无效 + parse_err(PropertyId::GridTemplateColumns, "100px2px"); + parse_err(PropertyId::GridTemplateColumns, "auto bogus"); + // gridshorthand:gap 两值、inset 四值 + } + + #[test] + fn gap_and_inset_shorthands_expand() { + let sheet = + crate::parser::Stylesheet::parse("div { gap: 10px 20px; inset: 1px 2px 3px 4px; }"); + let declarations = &sheet.rules()[0].declarations(); + assert_eq!(declarations.len(), 6); + let get = |property: PropertyId| { + declarations + .iter() + .find(|d| d.property == property) + .map(|d| &d.value) + }; + assert_eq!( + get(PropertyId::RowGap), + Some(&DeclaredValue::Typed(PropertyValue::Gap(GapValue::Length( + 10.0 + )))) + ); + assert_eq!( + get(PropertyId::ColumnGap), + Some(&DeclaredValue::Typed(PropertyValue::Gap(GapValue::Length( + 20.0 + )))) + ); + assert_eq!( + get(PropertyId::Top), + Some(&DeclaredValue::Typed(PropertyValue::Inset( + InsetValue::Length(1.0) + ))) + ); + assert_eq!( + get(PropertyId::Left), + Some(&DeclaredValue::Typed(PropertyValue::Inset( + InsetValue::Length(4.0) + ))) + ); + } + + #[test] + fn property_id_lookup_is_ascii_case_insensitive() { + assert_eq!( + PropertyId::from_name("FONT-SIZE"), + Some(PropertyId::FontSize) + ); + assert_eq!(PropertyId::from_name("color"), Some(PropertyId::Color)); + assert_eq!(PropertyId::from_name("grid-area"), None); + assert_eq!(PropertyId::FontSize.as_str(), "font-size"); + } + + #[test] + fn box_sizing_overflow_and_min_max_parse() { + assert_eq!( + parse_one(PropertyId::BoxSizing, "border-box"), + PropertyValue::BoxSizing(BoxSizingValue::BorderBox) + ); + assert_eq!( + parse_one(PropertyId::BoxSizing, "CONTENT-BOX"), + PropertyValue::BoxSizing(BoxSizingValue::ContentBox) + ); + parse_err(PropertyId::BoxSizing, "padding-box"); + + assert_eq!( + parse_one(PropertyId::Overflow, "hidden"), + PropertyValue::Overflow(OverflowValue::Hidden) + ); + assert_eq!( + parse_one(PropertyId::Overflow, "visible"), + PropertyValue::Overflow(OverflowValue::Visible) + ); + // 偏差:auto/scroll/clip 暂不建模,按无效声明丢弃 + parse_err(PropertyId::Overflow, "auto"); + parse_err(PropertyId::Overflow, "scroll"); + parse_err(PropertyId::Overflow, "clip"); + + assert_eq!( + parse_one(PropertyId::MinWidth, "40px"), + PropertyValue::Size(SizeValue::Length(40.0)) + ); + assert_eq!( + parse_one(PropertyId::MaxWidth, "50%"), + PropertyValue::Size(SizeValue::Percent(0.5)) + ); + assert_eq!( + parse_one(PropertyId::MinHeight, "auto"), + PropertyValue::Size(SizeValue::Auto) + ); + assert_eq!( + parse_one(PropertyId::MaxHeight, "0"), + PropertyValue::Size(SizeValue::Length(0.0)) + ); + // 负尺寸非法 + parse_err(PropertyId::MaxWidth, "-10px"); + } + + #[test] + fn color_hex_forms() { + assert_eq!( + parse_one(PropertyId::Color, "#fff"), + PropertyValue::Color(Rgba::opaque(255, 255, 255)) + ); + assert_eq!( + parse_one(PropertyId::Color, "#0000"), + PropertyValue::Color(Rgba { + r: 0, + g: 0, + b: 0, + a: 0 + }) + ); + assert_eq!( + parse_one(PropertyId::Color, "#336699"), + PropertyValue::Color(Rgba::opaque(0x33, 0x66, 0x99)) + ); + assert_eq!( + parse_one(PropertyId::Color, "#33669980"), + PropertyValue::Color(Rgba { + r: 0x33, + g: 0x66, + b: 0x99, + a: 0x80 + }) + ); + parse_err(PropertyId::Color, "#ff"); + parse_err(PropertyId::Color, "#ffggzz"); + } + + #[test] + fn color_named_and_transparent() { + assert_eq!( + parse_one(PropertyId::Color, "rebeccapurple"), + PropertyValue::Color(Rgba::opaque(0x66, 0x33, 0x99)) + ); + assert_eq!( + parse_one(PropertyId::Color, "BLACK"), + PropertyValue::Color(Rgba::opaque(0, 0, 0)) + ); + assert_eq!( + parse_one(PropertyId::Color, "transparent"), + PropertyValue::Color(Rgba::transparent()) + ); + parse_err(PropertyId::Color, "notacolor"); + parse_err(PropertyId::Color, "currentcolor"); + } + + #[test] + fn color_rgb_legacy_and_modern() { + assert_eq!( + parse_one(PropertyId::Color, "rgb(255, 0, 128)"), + PropertyValue::Color(Rgba::opaque(255, 0, 128)) + ); + assert_eq!( + parse_one(PropertyId::Color, "rgba(255, 0, 128, 0.5)"), + PropertyValue::Color(Rgba { + r: 255, + g: 0, + b: 128, + a: 128 + }) + ); + assert_eq!( + parse_one(PropertyId::Color, "rgb(255 0 128)"), + PropertyValue::Color(Rgba::opaque(255, 0, 128)) + ); + assert_eq!( + parse_one(PropertyId::Color, "rgb(255 0 128 / 50%)"), + PropertyValue::Color(Rgba { + r: 255, + g: 0, + b: 128, + a: 128 + }) + ); + assert_eq!( + parse_one(PropertyId::Color, "rgb(50% 0% 100%)"), + PropertyValue::Color(Rgba::opaque(128, 0, 255)) + ); + // 超范围 clamp(CSS Color 4) + assert_eq!( + parse_one(PropertyId::Color, "rgb(-20 300 128)"), + PropertyValue::Color(Rgba::opaque(0, 255, 128)) + ); + parse_err(PropertyId::Color, "rgb(255 0)"); + parse_err(PropertyId::Color, "rgb(255, 0, 128 0.5)"); + } + + #[test] + fn color_hsl() { + assert_eq!( + parse_one(PropertyId::Color, "hsl(120, 100%, 50%)"), + PropertyValue::Color(Rgba::opaque(0, 255, 0)) + ); + assert_eq!( + parse_one(PropertyId::Color, "hsl(120 100% 50%)"), + PropertyValue::Color(Rgba::opaque(0, 255, 0)) + ); + assert_eq!( + parse_one(PropertyId::Color, "hsla(0, 0%, 0%, 0.5)"), + PropertyValue::Color(Rgba { + r: 0, + g: 0, + b: 0, + a: 128 + }) + ); + // 色相取模 + assert_eq!( + parse_one(PropertyId::Color, "hsl(480 100% 50%)"), + PropertyValue::Color(Rgba::opaque(0, 255, 0)) + ); + parse_err(PropertyId::Color, "hsl(120 50 50%)"); + } + + #[test] + fn font_size_forms() { + assert_eq!( + parse_one(PropertyId::FontSize, "16px"), + PropertyValue::FontSize(FontSizeValue::Px(16.0)) + ); + assert_eq!( + parse_one(PropertyId::FontSize, "12pt"), + PropertyValue::FontSize(FontSizeValue::Px(16.0)) + ); + assert_eq!( + parse_one(PropertyId::FontSize, "1.5em"), + PropertyValue::FontSize(FontSizeValue::Em(1.5)) + ); + assert_eq!( + parse_one(PropertyId::FontSize, "120%"), + PropertyValue::FontSize(FontSizeValue::Percent(1.2)) + ); + assert_eq!( + parse_one(PropertyId::FontSize, "0"), + PropertyValue::FontSize(FontSizeValue::Px(0.0)) + ); + assert_eq!( + parse_one(PropertyId::FontSize, "x-large"), + PropertyValue::FontSize(FontSizeValue::Absolute(AbsoluteSize::XLarge)) + ); + assert_eq!( + parse_one(PropertyId::FontSize, "larger"), + PropertyValue::FontSize(FontSizeValue::Larger) + ); + parse_err(PropertyId::FontSize, "16"); + parse_err(PropertyId::FontSize, "2rem"); + parse_err(PropertyId::FontSize, "medium small"); + } + + #[test] + fn absolute_size_table_matches_spec_factors() { + // CSS Fonts 4 §2.5.1 scaling factors + assert_eq!(AbsoluteSize::XxSmall.factor(), 0.6); + assert_eq!(AbsoluteSize::XSmall.factor(), 0.75); + assert_eq!(AbsoluteSize::Small.factor(), 8.0 / 9.0); + assert_eq!(AbsoluteSize::Medium.factor(), 1.0); + assert_eq!(AbsoluteSize::Large.factor(), 1.2); + assert_eq!(AbsoluteSize::XLarge.factor(), 1.5); + assert_eq!(AbsoluteSize::XxLarge.factor(), 2.0); + assert_eq!(AbsoluteSize::XxxLarge.factor(), 3.0); + } + + #[test] + fn font_weight_forms() { + assert_eq!( + parse_one(PropertyId::FontWeight, "400"), + PropertyValue::FontWeight(FontWeightValue::Weight(400.0)) + ); + assert_eq!( + parse_one(PropertyId::FontWeight, "normal"), + PropertyValue::FontWeight(FontWeightValue::Weight(400.0)) + ); + assert_eq!( + parse_one(PropertyId::FontWeight, "bold"), + PropertyValue::FontWeight(FontWeightValue::Weight(700.0)) + ); + assert_eq!( + parse_one(PropertyId::FontWeight, "bolder"), + PropertyValue::FontWeight(FontWeightValue::Bolder) + ); + parse_err(PropertyId::FontWeight, "0"); + parse_err(PropertyId::FontWeight, "1001"); + parse_err(PropertyId::FontWeight, "bold 700"); + } + + #[test] + fn font_family_forms() { + assert_eq!( + parse_one(PropertyId::FontFamily, "serif"), + PropertyValue::FontFamily(vec![FontFamilyValue::Generic("serif")]) + ); + assert_eq!( + parse_one(PropertyId::FontFamily, "SANS-SERIF"), + PropertyValue::FontFamily(vec![FontFamilyValue::Generic("sans-serif")]) + ); + // 带引号的 serif 是普通族名,不是 generic + assert_eq!( + parse_one(PropertyId::FontFamily, "\"serif\""), + PropertyValue::FontFamily(vec![FontFamilyValue::Family("serif".into())]) + ); + assert_eq!( + parse_one(PropertyId::FontFamily, "Times New Roman, Arial, sans-serif"), + PropertyValue::FontFamily(vec![ + FontFamilyValue::Family("Times New Roman".into()), + FontFamilyValue::Family("Arial".into()), + FontFamilyValue::Generic("sans-serif"), + ]) + ); + parse_err(PropertyId::FontFamily, ""); + parse_err(PropertyId::FontFamily, "Times \"New\" Roman"); + parse_err(PropertyId::FontFamily, "12px"); + } + + #[test] + fn keyword_properties() { + assert_eq!( + parse_one(PropertyId::Display, "none"), + PropertyValue::Display(DisplayValue::None) + ); + assert_eq!( + parse_one(PropertyId::Display, "FLEX"), + PropertyValue::Display(DisplayValue::Flex) + ); + assert_eq!( + parse_one(PropertyId::Display, "table-cell"), + PropertyValue::Display(DisplayValue::TableInternal("table-cell")) + ); + parse_err(PropertyId::Display, "ruby"); + parse_err(PropertyId::Display, "block flex"); + + assert_eq!( + parse_one(PropertyId::TextAlign, "center"), + PropertyValue::TextAlign(TextAlignValue::Center) + ); + assert_eq!( + parse_one(PropertyId::TextAlign, "match-parent"), + PropertyValue::TextAlign(TextAlignValue::MatchParent) + ); + parse_err(PropertyId::TextAlign, "middle"); + + assert_eq!( + parse_one(PropertyId::FontStyle, "italic"), + PropertyValue::FontStyle(FontStyleValue::Italic) + ); + assert_eq!( + parse_one(PropertyId::FontStyle, "oblique"), + PropertyValue::FontStyle(FontStyleValue::Oblique(None)) + ); + assert_eq!( + parse_one(PropertyId::FontStyle, "oblique 30deg"), + PropertyValue::FontStyle(FontStyleValue::Oblique(Some(30.0))) + ); + parse_err(PropertyId::FontStyle, "oblique 30px"); + } + + #[test] + fn flex_property_forms() { + // flex-grow:<number [0,∞]>(CSS Flexbox §7.1) + assert_eq!( + parse_one(PropertyId::FlexGrow, "2.5"), + PropertyValue::FlexGrow(2.5) + ); + assert_eq!( + parse_one(PropertyId::FlexGrow, "0"), + PropertyValue::FlexGrow(0.0) + ); + parse_err(PropertyId::FlexGrow, "-1"); + parse_err(PropertyId::FlexGrow, "auto"); + parse_err(PropertyId::FlexGrow, "1 2"); + + // flex-basis:auto | <length-percentage>(CSS Flexbox §7.2) + assert_eq!( + parse_one(PropertyId::FlexBasis, "auto"), + PropertyValue::FlexBasis(SizeValue::Auto) + ); + assert_eq!( + parse_one(PropertyId::FlexBasis, "0"), + PropertyValue::FlexBasis(SizeValue::Length(0.0)) + ); + assert_eq!( + parse_one(PropertyId::FlexBasis, "100px"), + PropertyValue::FlexBasis(SizeValue::Length(100.0)) + ); + assert_eq!( + parse_one(PropertyId::FlexBasis, "50%"), + PropertyValue::FlexBasis(SizeValue::Percent(0.5)) + ); + parse_err(PropertyId::FlexBasis, "-5px"); + parse_err(PropertyId::FlexBasis, "content"); + } + + #[test] + fn declared_value_css_wide_keywords() { + fn parse_declared(text: &str) -> Result<(DeclaredValue, bool), ()> { + let mut parser = Parser::new(text); + parse_declared_value(PropertyId::Color, &mut parser) + } + assert_eq!( + parse_declared("inherit"), + Ok((DeclaredValue::CssWide(CssWideKeyword::Inherit), false)) + ); + assert_eq!( + parse_declared("INITIAL !important"), + Ok((DeclaredValue::CssWide(CssWideKeyword::Initial), true)) + ); + assert_eq!( + parse_declared("unset"), + Ok((DeclaredValue::CssWide(CssWideKeyword::Unset), false)) + ); + assert_eq!( + parse_declared("revert"), + Ok((DeclaredValue::CssWide(CssWideKeyword::Revert), false)) + ); + // CSS-wide 关键字后不允许拼接其他值 + assert!(parse_declared("inherit red").is_err()); + assert_eq!( + parse_declared("#fff"), + Ok(( + DeclaredValue::Typed(PropertyValue::Color(Rgba::opaque(255, 255, 255))), + false + )) + ); + assert_eq!( + parse_declared("#fff !important"), + Ok(( + DeclaredValue::Typed(PropertyValue::Color(Rgba::opaque(255, 255, 255))), + true + )) + ); + assert!(parse_declared("#fff important").is_err()); + assert!(parse_declared("#fff ! bogus").is_err()); + } +} diff --git a/crates/nexty-css/.mimosa/hook-state/session_164476f9d97ffaabe4f6dc9715b6aad5.json b/crates/nexty-css/.mimosa/hook-state/session_164476f9d97ffaabe4f6dc9715b6aad5.json new file mode 100644 index 0000000..9cfd86e --- /dev/null +++ b/crates/nexty-css/.mimosa/hook-state/session_164476f9d97ffaabe4f6dc9715b6aad5.json @@ -0,0 +1 @@ +{"touched":["D:\\Nexty\\crates\\nexty-css\\src\\lib.rs","D:\\Nexty\\crates\\nexty-css\\src\\value.rs","D:\\Nexty\\crates\\nexty-css\\src\\cascade.rs"],"bashMutation":false,"reportedFindings":[],"findingEvents":[],"baseline":{"storageId":"mvmgp416-93016-2afbe7aa51","createdAt":"2026-10-24T13:56:03.882Z","files":{"src/lib.rs":{"existed":true,"snapshot":"b1a35a68f14e696205874893c07fd24fdb88882b47c23cc0e0c80a30c7d53759.source"},"src/value.rs":{"existed":true,"snapshot":"be1c878c753064b7eaddf4a10ba4215a93dd1817d31e6788691cdb29752fd612.source"},"src/cascade.rs":{"existed":true,"snapshot":"01bd7f2baaf2335e56694f02b60c806c80651a6e5acc29a13d3c84bf63ac1cdd.source"}},"complete":false,"candidateLimit":5000,"discoveredFiles":0,"capturedFiles":3,"truncated":false,"omittedAtLeast":0,"firstOmitted":"","errors":[{"stage":"baseline-capture","target":".","reason":"global task baseline was unavailable; captured only the touched file"},{"stage":"baseline-snapshot","target":"../nexty-layout/src/inline/mod.rs","reason":"file is outside project"},{"stage":"baseline-snapshot","target":"../nexty-layout/src/inline/mod.rs","reason":"file is outside project"},{"stage":"baseline-snapshot","target":"../nexty-layout/src/inline/mod.rs","reason":"file is outside project"},{"stage":"baseline-snapshot","target":"../nexty-layout/src/style_map.rs","reason":"file is outside project"},{"stage":"baseline-snapshot","target":"../nexty-layout/src/style_map.rs","reason":"file is outside project"},{"stage":"baseline-snapshot","target":"../nexty-layout/src/tree_build.rs","reason":"file is outside project"},{"stage":"baseline-snapshot","target":"../nexty-layout/src/tree_build.rs","reason":"file is outside project"},{"stage":"baseline-snapshot","target":"../nexty-layout/src/tree_build.rs","reason":"file is outside project"},{"stage":"baseline-snapshot","target":"../nexty-layout/src/tree_build.rs","reason":"file is outside project"},{"stage":"baseline-snapshot","target":"../nexty-layout/tests/layout.rs","reason":"file is outside project"}]},"stateErrors":[],"omittedReportedFindings":0,"omittedFindingEvents":0,"processing":null,"updatedAt":"2026-10-24T14:07:25.549Z"} \ No newline at end of file diff --git a/crates/nexty-css/.mimosa/hook-state/session_164476f9d97ffaabe4f6dc9715b6aad5.mvmgp416-93016-2afbe7aa51.baseline/01bd7f2baaf2335e56694f02b60c806c80651a6e5acc29a13d3c84bf63ac1cdd.source b/crates/nexty-css/.mimosa/hook-state/session_164476f9d97ffaabe4f6dc9715b6aad5.mvmgp416-93016-2afbe7aa51.baseline/01bd7f2baaf2335e56694f02b60c806c80651a6e5acc29a13d3c84bf63ac1cdd.source new file mode 100644 index 0000000..ba51617 --- /dev/null +++ b/crates/nexty-css/.mimosa/hook-state/session_164476f9d97ffaabe4f6dc9715b6aad5.mvmgp416-93016-2afbe7aa51.baseline/01bd7f2baaf2335e56694f02b60c806c80651a6e5acc29a13d3c84bf63ac1cdd.source @@ -0,0 +1,1656 @@ +//! 自研 cascade 与 computed style。 +//! +//! 行为 ground truth: +//! - 级联排序:[CSS Cascading and Inheritance Level 5 §6](https://drafts.csswg.org/css-cascade-5/#cascading) +//! - 继承 / 初始值:[CSS Cascade 5 §7](https://drafts.csswg.org/css-cascade-5/#defaulting) +//! - 字号计算:[CSS Fonts 4 §2.5](https://drafts.csswg.org/css-fonts-4/#font-size-prop) +//! - 相对字重:[CSS Fonts 4 §2.2.1](https://drafts.csswg.org/css-fonts-4/#relative-weights) +//! +//! 本轮只有 author origin(UA 样式表未引入),故排序桶为: +//! importance → 内联样式 → 特异度 → 源顺序。`revert` 回退到 UA origin, +//! 而 UA 无声明,等价于 initial。 + +use std::collections::HashMap; + +use nexty_dom::{Document, NodeId, NodeKind}; + +use crate::parser::{Declaration, MediaViewport, Stylesheet, parse_inline_style}; +use crate::selector::match_element_selectors; +use crate::value::{ + AbsoluteSize, AlignItemsValue, AlignSelfValue, BorderColorValue, BorderStyle, BorderWidthValue, + BoxSizingValue, CssWideKeyword, DeclaredValue, DisplayValue, FlexDirectionValue, FlexWrapValue, + FontFamilyValue, FontSizeValue, FontStyleValue, FontWeightValue, GapValue, GridAutoFlowValue, + GridTrackList, InsetValue, JustifyContentValue, LineHeightValue, MarginValue, MAX_CSS_LENGTH, + OverflowValue, OverflowWrapValue, PaddingValue, PositionValue, PropertyId, PropertyValue, Rgba, + SizeValue, TextAlignValue, ViewportUnit, WhiteSpaceValue, WordBreakValue, +}; + +/// 本层 UA 的 medium 字号基准(CSS Fonts 4 §2.5:initial 值由 UA 决定, +/// 对齐浏览器默认 16px;绝对尺寸关键字按 §2.5.1 缩放系数相对它计算)。 +pub(crate) const MEDIUM_FONT_SIZE: f32 = 16.0; + +/// 一个元素的 computed style(属性集随管线逐轮扩展)。 +#[derive(Debug, Clone, PartialEq)] +pub struct ComputedStyle { + /// `display`。 + pub display: DisplayValue, + /// `color`。 + pub color: Rgba, + /// `background-color`。 + pub background_color: Rgba, + /// 计算字号(CSS px)。 + pub font_size: f32, + /// 计算字重(1–1000)。 + pub font_weight: f32, + /// `font-style`。 + pub font_style: FontStyleValue, + /// `font-family` 列表。 + pub font_family: Vec<FontFamilyValue>, + /// `text-align`。 + pub text_align: TextAlignValue, + /// `line-height`(数值/normal 保持原样;长度为绝对 px; + /// 百分比与 em 已按本元素 font-size 折算)。 + pub line_height: LineHeightValue, + /// `white-space`(CSS Text 3 §3.1)。 + pub white_space: WhiteSpaceValue, + /// `overflow-wrap`(CSS Text 3 §5.4)。 + pub overflow_wrap: OverflowWrapValue, + /// `word-break`(CSS Text 3 §5.1)。 + pub word_break: WordBreakValue, + /// `width`(百分比由 layout 解析)。 + pub width: SizeValue, + /// `height`(百分比由 layout 解析)。 + pub height: SizeValue, + /// `min-width`(CSS 2.1 §10.4)。 + pub min_width: SizeValue, + /// `max-width`(CSS 2.1 §10.4)。 + pub max_width: SizeValue, + /// `min-height`(CSS 2.1 §10.7)。 + pub min_height: SizeValue, + /// `max-height`(CSS 2.1 §10.7)。 + pub max_height: SizeValue, + /// `box-sizing`(CSS Sizing 4 §5.3)。 + pub box_sizing: BoxSizingValue, + /// `overflow`(CSS Overflow 3 §3;仅裁剪标记,裁剪未实现)。 + pub overflow: OverflowValue, + /// `flex-grow`(CSS Flexbox §7.1,initial 0)。 + pub flex_grow: f32, + /// `flex-basis`(CSS Flexbox §7.2,initial auto)。 + pub flex_basis: SizeValue, + /// `position`(CSS Position 3 §2,initial static)。 + pub position: PositionValue, + /// 四边 inset(top / right / bottom / left;百分比与 auto 由 layout 解析)。 + pub inset: Edges<InsetValue>, + /// `flex-direction`(CSS Flexbox §8.3.1,initial row)。 + pub flex_direction: FlexDirectionValue, + /// `flex-wrap`(CSS Flexbox §8.4.1,initial nowrap)。 + pub flex_wrap: FlexWrapValue, + /// `flex-shrink`(CSS Flexbox §7.2,initial 1)。 + pub flex_shrink: f32, + /// `align-items`(CSS Box Alignment §7,initial stretch)。 + pub align_items: AlignItemsValue, + /// `justify-content`(CSS Box Alignment §8,initial flex-start)。 + pub justify_content: JustifyContentValue, + /// `align-self`(CSS Box Alignment §7,initial auto)。 + pub align_self: AlignSelfValue, + /// `grid-template-columns`(CSS Grid §7.2,initial 空)。 + pub grid_template_columns: GridTrackList, + /// `grid-template-rows`(CSS Grid §7.3,initial 空)。 + pub grid_template_rows: GridTrackList, + /// `row-gap`(CSS Box Alignment §6,initial normal)。 + pub row_gap: GapValue, + /// `column-gap`(CSS Box Alignment §6,initial normal)。 + pub column_gap: GapValue, + /// `grid-auto-flow`(CSS Grid §7.7,initial row)。 + pub grid_auto_flow: GridAutoFlowValue, + /// 四边 margin(百分比与 auto 由 layout 解析)。 + pub margin: Edges<MarginValue>, + /// 四边 padding(百分比由 layout 解析)。 + pub padding: Edges<PaddingValue>, + /// 四边 border 宽度(computed 值:style 为 none/hidden 时为 0)。 + pub border_width: Edges<f32>, + /// 四边 border 样式。 + pub border_style: Edges<BorderStyle>, + /// 四边 border 颜色(currentcolor 已按本元素 color 解析)。 + pub border_color: Edges<Rgba>, +} + +/// 四边值(top / right / bottom / left)。 +#[derive(Debug, Clone, Copy, PartialEq)] +pub struct Edges<T> { + /// 上边。 + pub top: T, + /// 右边。 + pub right: T, + /// 下边。 + pub bottom: T, + /// 左边。 + pub left: T, +} + +impl<T: Copy> Edges<T> { + /// 用同一值填充四边。 + #[must_use] + pub const fn splat(value: T) -> Self { + Self { + top: value, + right: value, + bottom: value, + left: value, + } + } +} + +impl ComputedStyle { + /// 全部属性取 initial 值。 + /// + /// initial 值逐条对应各属性规范;UA 相关的(`color` 的 `CanvasText`、 + /// `font-family` 的 UA 默认、`font-size` 的 medium、`line-height` 的 + /// normal)取本层固定选择:黑色、serif、16px。 + #[must_use] + pub fn initial() -> Self { + Self { + display: DisplayValue::Inline, + color: Rgba::opaque(0, 0, 0), + background_color: Rgba::transparent(), + font_size: MEDIUM_FONT_SIZE, + font_weight: 400.0, + font_style: FontStyleValue::Normal, + font_family: vec![FontFamilyValue::Generic("serif")], + text_align: TextAlignValue::Start, + line_height: LineHeightValue::Normal, + white_space: WhiteSpaceValue::Normal, + overflow_wrap: OverflowWrapValue::Normal, + word_break: WordBreakValue::Normal, + width: SizeValue::Auto, + height: SizeValue::Auto, + min_width: SizeValue::Auto, + max_width: SizeValue::Auto, + min_height: SizeValue::Auto, + max_height: SizeValue::Auto, + box_sizing: BoxSizingValue::ContentBox, + overflow: OverflowValue::Visible, + flex_grow: 0.0, + flex_basis: SizeValue::Auto, + position: PositionValue::Static, + inset: Edges::splat(InsetValue::Auto), + flex_direction: FlexDirectionValue::Row, + flex_wrap: FlexWrapValue::NoWrap, + flex_shrink: 1.0, + align_items: AlignItemsValue::Stretch, + justify_content: JustifyContentValue::FlexStart, + align_self: AlignSelfValue::Auto, + grid_template_columns: GridTrackList::default(), + grid_template_rows: GridTrackList::default(), + row_gap: GapValue::Normal, + column_gap: GapValue::Normal, + grid_auto_flow: GridAutoFlowValue::Row, + margin: Edges::splat(MarginValue::Length(0.0)), + padding: Edges::splat(PaddingValue::Length(0.0)), + border_width: Edges::splat(0.0), + border_style: Edges::splat(BorderStyle::None), + border_color: Edges::splat(Rgba::opaque(0, 0, 0)), + } + } +} + +impl PropertyId { + /// 属性是否继承(各属性规范 "Inherited" 行)。 + #[must_use] + pub fn inherited(self) -> bool { + matches!( + self, + Self::Color + | Self::FontSize + | Self::FontWeight + | Self::FontStyle + | Self::FontFamily + | Self::TextAlign + | Self::LineHeight + | Self::WhiteSpace + | Self::OverflowWrap + | Self::WordBreak + ) + } +} + +/// 全部属性的固定枚举顺序。 +/// +/// 顺序承载计算依赖:`FontSize` 先于 `LineHeight`(百分比按自身字号折算)、 +/// `Color` 先于 border 颜色(currentcolor)、border style 先于 width +/// (none/hidden 时宽度归零)。 +const PROPERTY_ORDER: [PropertyId; 58] = [ + PropertyId::Display, + PropertyId::Color, + PropertyId::BackgroundColor, + PropertyId::FontSize, + PropertyId::FontWeight, + PropertyId::FontStyle, + PropertyId::FontFamily, + PropertyId::TextAlign, + PropertyId::LineHeight, + PropertyId::WhiteSpace, + PropertyId::OverflowWrap, + PropertyId::WordBreak, + PropertyId::Width, + PropertyId::Height, + PropertyId::MinWidth, + PropertyId::MaxWidth, + PropertyId::MinHeight, + PropertyId::MaxHeight, + PropertyId::BoxSizing, + PropertyId::Overflow, + PropertyId::FlexGrow, + PropertyId::FlexBasis, + PropertyId::Position, + PropertyId::Top, + PropertyId::Right, + PropertyId::Bottom, + PropertyId::Left, + PropertyId::FlexDirection, + PropertyId::FlexWrap, + PropertyId::FlexShrink, + PropertyId::AlignItems, + PropertyId::JustifyContent, + PropertyId::AlignSelf, + PropertyId::GridTemplateColumns, + PropertyId::GridTemplateRows, + PropertyId::RowGap, + PropertyId::ColumnGap, + PropertyId::GridAutoFlow, + PropertyId::MarginTop, + PropertyId::MarginRight, + PropertyId::MarginBottom, + PropertyId::MarginLeft, + PropertyId::PaddingTop, + PropertyId::PaddingRight, + PropertyId::PaddingBottom, + PropertyId::PaddingLeft, + PropertyId::BorderTopStyle, + PropertyId::BorderRightStyle, + PropertyId::BorderBottomStyle, + PropertyId::BorderLeftStyle, + PropertyId::BorderTopWidth, + PropertyId::BorderRightWidth, + PropertyId::BorderBottomWidth, + PropertyId::BorderLeftWidth, + PropertyId::BorderTopColor, + PropertyId::BorderRightColor, + PropertyId::BorderBottomColor, + PropertyId::BorderLeftColor, +]; + +/// 级联 origin 桶(CSS Cascade 5 §6.4,仅 UA 与 author 两个 origin; +/// user origin 尚未引入)。 +/// +/// 值越大优先级越高:UA 普通 < author 普通 < author `!important` < +/// UA `!important`。 +#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord)] +enum OriginBucket { + UaNormal = 0, + AuthorNormal = 1, + AuthorImportant = 2, + UaImportant = 3, +} + +/// 级联排序键(CSS Cascade 5 §6.4)。 +/// +/// 字典序即优先级:先 origin/importance 桶;author 声明中内联样式排在 +/// 样式表声明之后(§6.4 style attribute);然后按特异度、规则顺序、声明顺序。 +#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord)] +struct CascadeKey { + bucket: OriginBucket, + inline: bool, + specificity: u32, + rule_order: usize, + declaration_order: usize, +} + +/// 级联 origin(CSS Cascade 5 §6.4;user origin 尚未引入)。 +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +enum Origin { + Ua, + Author, +} + +/// origin + importance → 排序桶:UA 普通 < author 普通 < author `!important` +/// < UA `!important`。 +fn bucket_of(origin: Origin, important: bool) -> OriginBucket { + match (origin, important) { + (Origin::Ua, false) => OriginBucket::UaNormal, + (Origin::Author, false) => OriginBucket::AuthorNormal, + (Origin::Author, true) => OriginBucket::AuthorImportant, + (Origin::Ua, true) => OriginBucket::UaImportant, + } +} + +/// 收集一个 origin 样式表中命中元素的全部声明。 +fn collect_origin_declarations( + document: &Document, + element: NodeId, + sheet: &Stylesheet, + origin: Origin, + matched: &mut Vec<(CascadeKey, Declaration)>, +) { + for (rule_order, rule) in sheet.rules().iter().enumerate() { + // 规则内多个选择器都能命中时,取特异度最高者 + // (CSS Cascade 5:声明的特异度取其匹配选择器中的最大值)。 + let specificity = rule + .selectors() + .iter() + .filter(|parsed| { + match_element_selectors(std::slice::from_ref(parsed), document, element) + }) + .map(|parsed| parsed.specificity) + .max(); + if let Some(specificity) = specificity { + for (declaration_order, declaration) in rule.declarations().iter().enumerate() { + matched.push(( + CascadeKey { + bucket: bucket_of(origin, declaration.important), + inline: false, + specificity, + rule_order, + declaration_order, + }, + declaration.clone(), + )); + } + } + } +} + +/// 对单个元素做级联,产出 computed style。 +/// +/// `ua_sheet` 是 UA origin 样式表(浏览器默认样式),参与级联但优先级 +/// 低于 author 声明(UA `!important` 最高,见 [`OriginBucket`])。 +/// `parent` 是树序父元素的 computed style(元素没有元素祖先时为 `None`)。 +/// 各属性:级联胜者 → CSS-wide 关键字 → 继承 → initial。 +/// 无视口信息:视口单位原样保留(见 [`cascade_in`])。 +#[must_use] +pub fn cascade( + document: &Document, + element: NodeId, + stylesheets: &[&Stylesheet], + ua_sheet: Option<&Stylesheet>, + parent: Option<&ComputedStyle>, +) -> ComputedStyle { + cascade_in(document, element, stylesheets, ua_sheet, parent, None) +} + +/// [`cascade`] 的带视口版本:视口单位(vw/vh/vmin/vmax)在 computed 阶段 +/// 按给定视口折算为绝对 px(CSS Values 4 §6.2:1v* = 视口对应边的 1%)。 +/// 未提供视口时视口单位原样保留,由消费方按降级值处理。 +#[must_use] +pub fn cascade_in( + document: &Document, + element: NodeId, + stylesheets: &[&Stylesheet], + ua_sheet: Option<&Stylesheet>, + parent: Option<&ComputedStyle>, + viewport: Option<MediaViewport>, +) -> ComputedStyle { + let mut matched: Vec<(CascadeKey, Declaration)> = Vec::new(); + + if let Some(ua) = ua_sheet { + collect_origin_declarations(document, element, ua, Origin::Ua, &mut matched); + } + // 规则顺序跨样式表连续编号:样式表按传入顺序、规则按源顺序 + for (rule_order, rule) in stylesheets + .iter() + .flat_map(|sheet| sheet.rules()) + .enumerate() + { + let specificity = rule + .selectors() + .iter() + .filter(|parsed| { + match_element_selectors(std::slice::from_ref(parsed), document, element) + }) + .map(|parsed| parsed.specificity) + .max(); + if let Some(specificity) = specificity { + for (declaration_order, declaration) in rule.declarations().iter().enumerate() { + matched.push(( + CascadeKey { + bucket: bucket_of(Origin::Author, declaration.important), + inline: false, + specificity, + rule_order, + declaration_order, + }, + declaration.clone(), + )); + } + } + } + + // 内联 style 属性:author origin,普通声明排在全部样式表声明之后 + if let Some(style_attribute) = style_attribute_of(document, element) { + for (declaration_order, declaration) in + parse_inline_style(&style_attribute).into_iter().enumerate() + { + matched.push(( + CascadeKey { + bucket: bucket_of(Origin::Author, declaration.important), + inline: true, + specificity: 0, + rule_order: usize::MAX, + declaration_order, + }, + declaration, + )); + } + } + + resolve_all(&matched, parent, viewport) +} + +/// 按树序计算整份文档的 computed style(父先于子)。 +/// +/// `<template>` 的内容子树是惰性片段,不参与级联,跳过。 +#[must_use] +pub fn compute_document_styles( + document: &Document, + stylesheets: &[&Stylesheet], + ua_sheet: Option<&Stylesheet>, +) -> HashMap<NodeId, ComputedStyle> { + compute_document_styles_in(document, stylesheets, ua_sheet, None) +} + +/// [`compute_document_styles`] 的带视口版本:视口单位(vw/vh/vmin/vmax) +/// 在 computed 阶段按给定视口折算为绝对 px(CSS Values 4 §6.2)。 +/// 未提供视口时视口单位原样保留,由消费方按降级值处理。 +#[must_use] +pub fn compute_document_styles_in( + document: &Document, + stylesheets: &[&Stylesheet], + ua_sheet: Option<&Stylesheet>, + viewport: Option<MediaViewport>, +) -> HashMap<NodeId, ComputedStyle> { + let mut styles = HashMap::new(); + walk( + document, + document.root(), + None, + stylesheets, + ua_sheet, + viewport, + &mut styles, + ); + styles +} + +fn walk( + document: &Document, + node: NodeId, + parent: Option<&ComputedStyle>, + stylesheets: &[&Stylesheet], + ua_sheet: Option<&Stylesheet>, + viewport: Option<MediaViewport>, + out: &mut HashMap<NodeId, ComputedStyle>, +) { + for child in document.children(node) { + if matches!(document.node(child), Some(NodeKind::Element(_))) { + let style = cascade_in(document, child, stylesheets, ua_sheet, parent, viewport); + walk( + document, + child, + Some(&style), + stylesheets, + ua_sheet, + viewport, + out, + ); + out.insert(child, style); + } + } +} + +/// 元素的 style 属性值。 +fn style_attribute_of(document: &Document, element: NodeId) -> Option<String> { + match document.node(element) { + Some(NodeKind::Element(data)) => data + .attributes + .iter() + .find(|attr| attr.namespace == nexty_dom::Namespace::None && attr.name == "style") + .map(|attr| attr.value.clone()), + _ => None, + } +} + +/// 某属性在级联中的胜者声明。 +fn winner(property: PropertyId, matched: &[(CascadeKey, Declaration)]) -> Option<&Declaration> { + matched + .iter() + .filter(|(_, declaration)| declaration.property == property) + .max_by_key(|(key, _)| *key) + .map(|(_, declaration)| declaration) +} + +/// 胜者决定该属性的来源。 +enum Decision<'a> { + /// 使用级联胜者的属性值。 + Use(&'a PropertyValue), + /// 取父元素的 computed value;无父元素则取 initial。 + Parent, + /// 取 initial 值。 + Initial, +} + +fn decide<'a>( + property: PropertyId, + winner: Option<&'a Declaration>, + parent: Option<&ComputedStyle>, +) -> Decision<'a> { + let has_parent = parent.is_some(); + match winner { + Some(Declaration { + value: DeclaredValue::Typed(value), + .. + }) => Decision::Use(value), + Some(Declaration { + value: DeclaredValue::CssWide(keyword), + .. + }) => match keyword { + // revert 回退到 UA origin;本层 UA 无声明,等价 initial + CssWideKeyword::Initial | CssWideKeyword::Revert => Decision::Initial, + CssWideKeyword::Inherit => Decision::Parent, + CssWideKeyword::Unset => { + if property.inherited() && has_parent { + Decision::Parent + } else { + Decision::Initial + } + } + }, + // 无声明:继承属性取父值,否则取 initial(CSS Cascade 5 §7) + None => { + if property.inherited() && has_parent { + Decision::Parent + } else { + Decision::Initial + } + } + } +} + +/// 视口单位折算为 px:1v* = 视口对应边的 1%(CSS Values 4 §6.2)。 +/// +/// 折算乘积同样过卫生钳:巨数量 × 视口基数不得产生 `inf`。 +fn viewport_px(amount: f32, unit: ViewportUnit, viewport: MediaViewport) -> f32 { + let base = match unit { + ViewportUnit::Vw => viewport.width, + ViewportUnit::Vh => viewport.height, + ViewportUnit::Vmin => viewport.width.min(viewport.height), + ViewportUnit::Vmax => viewport.width.max(viewport.height), + }; + clamp_computed(amount * base / 100.0) +} + +/// 计算出口的长度卫生:有限值 clamp 到上限;±inf 钳到边界;NaN 归 0 +/// (相对单位乘积可能越过解析期的钳值,计算值必须仍落在预算内)。 +fn clamp_computed(value: f32) -> f32 { + if value.is_nan() { + 0.0 + } else { + value.clamp(-MAX_CSS_LENGTH, MAX_CSS_LENGTH) + } +} + +macro_rules! resolve_viewport { + ($fn_name:ident, $enum:ident) => { + fn $fn_name(value: $enum, viewport: Option<MediaViewport>) -> $enum { + match value { + $enum::Viewport(amount, unit) => match viewport { + Some(vp) => $enum::Length(viewport_px(amount, unit, vp)), + None => $enum::Viewport(amount, unit), + }, + other => other, + } + } + }; +} + +resolve_viewport!(resolve_size, SizeValue); +resolve_viewport!(resolve_inset, InsetValue); +resolve_viewport!(resolve_margin, MarginValue); +resolve_viewport!(resolve_padding, PaddingValue); +resolve_viewport!(resolve_gap, GapValue); + +/// 逐属性解析出 computed style。 +fn resolve_all( + matched: &[(CascadeKey, Declaration)], + parent: Option<&ComputedStyle>, + viewport: Option<MediaViewport>, +) -> ComputedStyle { + let initial = ComputedStyle::initial(); + let mut style = initial.clone(); + let parent_font_size = parent.map_or(MEDIUM_FONT_SIZE, |p| p.font_size); + let parent_font_weight = parent.map_or(400.0, |p| p.font_weight); + + for property in PROPERTY_ORDER { + let decision = decide(property, winner(property, matched), parent); + match (property, decision) { + (PropertyId::Display, Decision::Use(PropertyValue::Display(value))) => { + style.display = *value; + } + (PropertyId::TextAlign, Decision::Use(PropertyValue::TextAlign(value))) => { + style.text_align = *value; + } + (PropertyId::FontStyle, Decision::Use(PropertyValue::FontStyle(value))) => { + style.font_style = *value; + } + (PropertyId::Color, Decision::Use(PropertyValue::Color(value))) => { + style.color = *value; + } + (PropertyId::BackgroundColor, Decision::Use(PropertyValue::Color(value))) => { + style.background_color = *value; + } + (PropertyId::FontSize, Decision::Use(PropertyValue::FontSize(value))) => { + style.font_size = compute_font_size(value, parent_font_size); + } + (PropertyId::FontWeight, Decision::Use(PropertyValue::FontWeight(value))) => { + style.font_weight = compute_font_weight(value, parent_font_weight); + } + (PropertyId::FontFamily, Decision::Use(PropertyValue::FontFamily(value))) => { + style.font_family = value.clone(); + } + (PropertyId::LineHeight, Decision::Use(PropertyValue::LineHeight(value))) => { + // CSS 2.1 §10.8.1:百分比/em 的 computed 值为绝对长度 + //(按本元素自身 font-size,已在 PROPERTY_ORDER 中先求) + style.line_height = match *value { + LineHeightValue::Percent(fraction) => { + LineHeightValue::Length(clamp_computed(style.font_size * fraction)) + } + LineHeightValue::Em(em) => { + LineHeightValue::Length(clamp_computed(style.font_size * em)) + } + other => other, + }; + } + (PropertyId::WhiteSpace, Decision::Use(PropertyValue::WhiteSpace(value))) => { + style.white_space = *value; + } + (PropertyId::OverflowWrap, Decision::Use(PropertyValue::OverflowWrap(value))) => { + style.overflow_wrap = *value; + } + (PropertyId::WordBreak, Decision::Use(PropertyValue::WordBreak(value))) => { + style.word_break = *value; + } + (PropertyId::Width, Decision::Use(PropertyValue::Size(value))) => { + style.width = resolve_size(*value, viewport); + } + (PropertyId::Height, Decision::Use(PropertyValue::Size(value))) => { + style.height = resolve_size(*value, viewport); + } + (PropertyId::MinWidth, Decision::Use(PropertyValue::Size(value))) => { + style.min_width = resolve_size(*value, viewport); + } + (PropertyId::MaxWidth, Decision::Use(PropertyValue::Size(value))) => { + style.max_width = resolve_size(*value, viewport); + } + (PropertyId::MinHeight, Decision::Use(PropertyValue::Size(value))) => { + style.min_height = resolve_size(*value, viewport); + } + (PropertyId::MaxHeight, Decision::Use(PropertyValue::Size(value))) => { + style.max_height = resolve_size(*value, viewport); + } + (PropertyId::BoxSizing, Decision::Use(PropertyValue::BoxSizing(value))) => { + style.box_sizing = *value; + } + (PropertyId::Overflow, Decision::Use(PropertyValue::Overflow(value))) => { + style.overflow = *value; + } + (PropertyId::FlexGrow, Decision::Use(PropertyValue::FlexGrow(value))) => { + style.flex_grow = *value; + } + (PropertyId::FlexBasis, Decision::Use(PropertyValue::FlexBasis(value))) => { + style.flex_basis = *value; + } + (PropertyId::Position, Decision::Use(PropertyValue::Position(value))) => { + style.position = *value; + } + (PropertyId::Top, Decision::Use(PropertyValue::Inset(value))) => { + style.inset.top = resolve_inset(*value, viewport); + } + (PropertyId::Right, Decision::Use(PropertyValue::Inset(value))) => { + style.inset.right = resolve_inset(*value, viewport); + } + (PropertyId::Bottom, Decision::Use(PropertyValue::Inset(value))) => { + style.inset.bottom = resolve_inset(*value, viewport); + } + (PropertyId::Left, Decision::Use(PropertyValue::Inset(value))) => { + style.inset.left = resolve_inset(*value, viewport); + } + (PropertyId::FlexDirection, Decision::Use(PropertyValue::FlexDirection(value))) => { + style.flex_direction = *value; + } + (PropertyId::FlexWrap, Decision::Use(PropertyValue::FlexWrap(value))) => { + style.flex_wrap = *value; + } + (PropertyId::FlexShrink, Decision::Use(PropertyValue::FlexShrink(value))) => { + style.flex_shrink = *value; + } + (PropertyId::AlignItems, Decision::Use(PropertyValue::AlignItems(value))) => { + style.align_items = *value; + } + (PropertyId::JustifyContent, Decision::Use(PropertyValue::JustifyContent(value))) => { + style.justify_content = *value; + } + (PropertyId::AlignSelf, Decision::Use(PropertyValue::AlignSelf(value))) => { + style.align_self = *value; + } + (PropertyId::GridTemplateColumns, Decision::Use(PropertyValue::GridTrack(value))) => { + style.grid_template_columns = value.clone(); + } + (PropertyId::GridTemplateRows, Decision::Use(PropertyValue::GridTrack(value))) => { + style.grid_template_rows = value.clone(); + } + (PropertyId::RowGap, Decision::Use(PropertyValue::Gap(value))) => { + style.row_gap = resolve_gap(*value, viewport); + } + (PropertyId::ColumnGap, Decision::Use(PropertyValue::Gap(value))) => { + style.column_gap = resolve_gap(*value, viewport); + } + (PropertyId::GridAutoFlow, Decision::Use(PropertyValue::GridAutoFlow(value))) => { + style.grid_auto_flow = *value; + } + (PropertyId::MarginTop, Decision::Use(PropertyValue::Margin(value))) => { + style.margin.top = resolve_margin(*value, viewport); + } + (PropertyId::MarginRight, Decision::Use(PropertyValue::Margin(value))) => { + style.margin.right = resolve_margin(*value, viewport); + } + (PropertyId::MarginBottom, Decision::Use(PropertyValue::Margin(value))) => { + style.margin.bottom = resolve_margin(*value, viewport); + } + (PropertyId::MarginLeft, Decision::Use(PropertyValue::Margin(value))) => { + style.margin.left = resolve_margin(*value, viewport); + } + (PropertyId::PaddingTop, Decision::Use(PropertyValue::Padding(value))) => { + style.padding.top = resolve_padding(*value, viewport); + } + (PropertyId::PaddingRight, Decision::Use(PropertyValue::Padding(value))) => { + style.padding.right = resolve_padding(*value, viewport); + } + (PropertyId::PaddingBottom, Decision::Use(PropertyValue::Padding(value))) => { + style.padding.bottom = resolve_padding(*value, viewport); + } + (PropertyId::PaddingLeft, Decision::Use(PropertyValue::Padding(value))) => { + style.padding.left = resolve_padding(*value, viewport); + } + (PropertyId::BorderTopStyle, Decision::Use(PropertyValue::BorderStyle(value))) => { + style.border_style.top = *value; + } + (PropertyId::BorderRightStyle, Decision::Use(PropertyValue::BorderStyle(value))) => { + style.border_style.right = *value; + } + (PropertyId::BorderBottomStyle, Decision::Use(PropertyValue::BorderStyle(value))) => { + style.border_style.bottom = *value; + } + (PropertyId::BorderLeftStyle, Decision::Use(PropertyValue::BorderStyle(value))) => { + style.border_style.left = *value; + } + (PropertyId::BorderTopWidth, Decision::Use(PropertyValue::BorderWidth(value))) => { + style.border_width.top = used_border_width(*value, style.border_style.top); + } + (PropertyId::BorderRightWidth, Decision::Use(PropertyValue::BorderWidth(value))) => { + style.border_width.right = used_border_width(*value, style.border_style.right); + } + (PropertyId::BorderBottomWidth, Decision::Use(PropertyValue::BorderWidth(value))) => { + style.border_width.bottom = used_border_width(*value, style.border_style.bottom); + } + (PropertyId::BorderLeftWidth, Decision::Use(PropertyValue::BorderWidth(value))) => { + style.border_width.left = used_border_width(*value, style.border_style.left); + } + (PropertyId::BorderTopColor, Decision::Use(PropertyValue::BorderColor(value))) => { + style.border_color.top = resolve_border_color(*value, style.color); + } + (PropertyId::BorderRightColor, Decision::Use(PropertyValue::BorderColor(value))) => { + style.border_color.right = resolve_border_color(*value, style.color); + } + (PropertyId::BorderBottomColor, Decision::Use(PropertyValue::BorderColor(value))) => { + style.border_color.bottom = resolve_border_color(*value, style.color); + } + (PropertyId::BorderLeftColor, Decision::Use(PropertyValue::BorderColor(value))) => { + style.border_color.left = resolve_border_color(*value, style.color); + } + // 关键字与继承:按属性回退 + (property, decision @ (Decision::Parent | Decision::Initial)) => { + let source = match decision { + Decision::Parent => parent.unwrap_or(&initial), + _ => &initial, + }; + match property { + PropertyId::Display => style.display = source.display, + PropertyId::Color => style.color = source.color, + PropertyId::BackgroundColor => style.background_color = source.background_color, + PropertyId::FontSize => style.font_size = source.font_size, + PropertyId::FontWeight => style.font_weight = source.font_weight, + PropertyId::FontStyle => style.font_style = source.font_style, + PropertyId::FontFamily => style.font_family = source.font_family.clone(), + PropertyId::TextAlign => style.text_align = source.text_align, + PropertyId::LineHeight => style.line_height = source.line_height, + PropertyId::WhiteSpace => style.white_space = source.white_space, + PropertyId::OverflowWrap => style.overflow_wrap = source.overflow_wrap, + PropertyId::WordBreak => style.word_break = source.word_break, + PropertyId::Width => style.width = source.width, + PropertyId::Height => style.height = source.height, + PropertyId::MinWidth => style.min_width = source.min_width, + PropertyId::MaxWidth => style.max_width = source.max_width, + PropertyId::MinHeight => style.min_height = source.min_height, + PropertyId::MaxHeight => style.max_height = source.max_height, + PropertyId::BoxSizing => style.box_sizing = source.box_sizing, + PropertyId::Overflow => style.overflow = source.overflow, + PropertyId::FlexGrow => style.flex_grow = source.flex_grow, + PropertyId::FlexBasis => style.flex_basis = source.flex_basis, + PropertyId::Position => style.position = source.position, + PropertyId::Top => style.inset.top = source.inset.top, + PropertyId::Right => style.inset.right = source.inset.right, + PropertyId::Bottom => style.inset.bottom = source.inset.bottom, + PropertyId::Left => style.inset.left = source.inset.left, + PropertyId::FlexDirection => style.flex_direction = source.flex_direction, + PropertyId::FlexWrap => style.flex_wrap = source.flex_wrap, + PropertyId::FlexShrink => style.flex_shrink = source.flex_shrink, + PropertyId::AlignItems => style.align_items = source.align_items, + PropertyId::JustifyContent => style.justify_content = source.justify_content, + PropertyId::AlignSelf => style.align_self = source.align_self, + PropertyId::GridTemplateColumns => { + style.grid_template_columns = source.grid_template_columns.clone() + } + PropertyId::GridTemplateRows => { + style.grid_template_rows = source.grid_template_rows.clone() + } + PropertyId::RowGap => style.row_gap = source.row_gap, + PropertyId::ColumnGap => style.column_gap = source.column_gap, + PropertyId::GridAutoFlow => style.grid_auto_flow = source.grid_auto_flow, + PropertyId::MarginTop => style.margin.top = source.margin.top, + PropertyId::MarginRight => style.margin.right = source.margin.right, + PropertyId::MarginBottom => style.margin.bottom = source.margin.bottom, + PropertyId::MarginLeft => style.margin.left = source.margin.left, + PropertyId::PaddingTop => style.padding.top = source.padding.top, + PropertyId::PaddingRight => style.padding.right = source.padding.right, + PropertyId::PaddingBottom => style.padding.bottom = source.padding.bottom, + PropertyId::PaddingLeft => style.padding.left = source.padding.left, + PropertyId::BorderTopStyle => style.border_style.top = source.border_style.top, + PropertyId::BorderRightStyle => { + style.border_style.right = source.border_style.right; + } + PropertyId::BorderBottomStyle => { + style.border_style.bottom = source.border_style.bottom; + } + PropertyId::BorderLeftStyle => { + style.border_style.left = source.border_style.left; + } + PropertyId::BorderTopWidth => style.border_width.top = source.border_width.top, + PropertyId::BorderRightWidth => { + style.border_width.right = source.border_width.right; + } + PropertyId::BorderBottomWidth => { + style.border_width.bottom = source.border_width.bottom; + } + PropertyId::BorderLeftWidth => { + style.border_width.left = source.border_width.left; + } + PropertyId::BorderTopColor => style.border_color.top = source.border_color.top, + PropertyId::BorderRightColor => { + style.border_color.right = source.border_color.right; + } + PropertyId::BorderBottomColor => { + style.border_color.bottom = source.border_color.bottom; + } + PropertyId::BorderLeftColor => { + style.border_color.left = source.border_color.left; + } + } + } + // 声明值与属性不匹配只可能来自程序错误;保持 initial 值 + _ => {} + } + } + style +} + +/// border-*-width 的 computed 值:style 为 none/hidden 时为 0 +/// (CSS 2.1 §8.5.4)。 +fn used_border_width(value: BorderWidthValue, border_style: BorderStyle) -> f32 { + if border_style.visible() { + value.px() + } else { + 0.0 + } +} + +/// border-*-color 的 computed 值:currentcolor 按本元素 color 解析。 +fn resolve_border_color(value: BorderColorValue, color: Rgba) -> Rgba { + match value { + BorderColorValue::Rgba(rgba) => rgba, + BorderColorValue::CurrentColor => color, + } +} + +/// `font-size` 计算值(CSS Fonts 4 §2.5:长度/百分比相对父元素计算字号)。 +/// +/// 相对单位乘积过卫生钳:继承链上的巨数 em/百分比不得算出 `inf`。 +fn compute_font_size(value: &FontSizeValue, parent_font_size: f32) -> f32 { + clamp_computed(match value { + FontSizeValue::Px(px) => *px, + FontSizeValue::Em(em) => parent_font_size * em, + FontSizeValue::Percent(fraction) => parent_font_size * fraction, + FontSizeValue::Absolute(size) => MEDIUM_FONT_SIZE * size.factor(), + FontSizeValue::Larger => adjacent_size(parent_font_size, true), + FontSizeValue::Smaller => adjacent_size(parent_font_size, false), + }) +} + +/// `larger` / `smaller`:父字号恰为绝对尺寸表项时取相邻项 +/// (CSS Fonts 4 §2.5),否则按规范允许的简单比例 1.2 缩放。 +fn adjacent_size(parent_font_size: f32, larger: bool) -> f32 { + const TOLERANCE: f32 = 0.01; + let index = AbsoluteSize::ORDERED + .iter() + .position(|size| (MEDIUM_FONT_SIZE * size.factor() - parent_font_size).abs() <= TOLERANCE); + match index { + Some(index) if larger && index + 1 < AbsoluteSize::ORDERED.len() => { + MEDIUM_FONT_SIZE * AbsoluteSize::ORDERED[index + 1].factor() + } + Some(index) if !larger && index > 0 => { + MEDIUM_FONT_SIZE * AbsoluteSize::ORDERED[index - 1].factor() + } + // 表外或已到表端:简单比例 + _ => { + if larger { + parent_font_size * 1.2 + } else { + parent_font_size / 1.2 + } + } + } +} + +/// `font-weight` 计算值(CSS Fonts 4 §2.2)。 +fn compute_font_weight(value: &FontWeightValue, parent_font_weight: f32) -> f32 { + match value { + FontWeightValue::Weight(weight) => weight.clamp(1.0, 1000.0), + FontWeightValue::Bolder => relative_weight(parent_font_weight, true), + FontWeightValue::Lighter => relative_weight(parent_font_weight, false), + } +} + +/// bolder / lighter 相对映射表(CSS Fonts 4 §2.2.1)。 +fn relative_weight(parent_weight: f32, bolder: bool) -> f32 { + if parent_weight < 100.0 { + if bolder { 400.0 } else { parent_weight } + } else if parent_weight < 350.0 { + if bolder { 400.0 } else { 100.0 } + } else if parent_weight < 550.0 { + if bolder { 700.0 } else { 100.0 } + } else if parent_weight < 750.0 { + if bolder { 900.0 } else { 400.0 } + } else if parent_weight < 900.0 { + if bolder { 900.0 } else { 700.0 } + } else { + // bolder:无更粗字重,保持不变;lighter:700 + if bolder { parent_weight } else { 700.0 } + } +} + +#[cfg(test)] +mod tests { + use super::*; + use crate::html_ua_stylesheet; + use crate::test_support::{build_document, find_first_by_name}; + use crate::value::GridTrack; + + fn style_of(html: &str, sheets: &[&str], name: &str) -> ComputedStyle { + let document = build_document(html); + let parsed: Vec<Stylesheet> = sheets.iter().map(|css| Stylesheet::parse(css)).collect(); + let refs: Vec<&Stylesheet> = parsed.iter().collect(); + let element = find_first_by_name(&document, name).expect("element"); + cascade(&document, element, &refs, None, None) + } + + /// 视口 800×600:vw/vh/vmin/vmax 按对应边 1% 折算为绝对 px。 + #[test] + fn viewport_units_resolve_against_viewport() { + let document = build_document("<div></div>"); + let sheet = Stylesheet::parse( + "div { width: 50vw; min-height: 10vh; margin: 1vmin auto; \ + padding: 1vmax; top: 2vw; row-gap: 3vh }", + ); + let refs = vec![&sheet]; + let div = find_first_by_name(&document, "div").expect("div"); + let viewport = MediaViewport { + width: 800.0, + height: 600.0, + }; + let style = cascade_in(&document, div, &refs, None, None, Some(viewport)); + assert_eq!(style.width, SizeValue::Length(400.0), "50vw = 400px"); + assert_eq!(style.min_height, SizeValue::Length(60.0), "10vh = 60px"); + assert_eq!( + style.margin.top, + MarginValue::Length(6.0), + "1vmin = 6px(短边 600)" + ); + assert_eq!(style.margin.left, MarginValue::Auto, "非视口成分不受影响"); + assert_eq!( + style.padding.top, + PaddingValue::Length(8.0), + "1vmax = 8px(长边 800)" + ); + assert_eq!(style.inset.top, InsetValue::Length(16.0), "2vw = 16px"); + assert_eq!(style.row_gap, GapValue::Length(18.0), "3vh = 18px"); + } + + /// 无视口信息:视口单位原样保留在 computed style 里(消费方降级)。 + #[test] + fn viewport_units_stay_unresolved_without_viewport() { + let style = style_of( + "<div></div>", + &["div { width: 50vw; margin-top: 2vh }"], + "div", + ); + assert_eq!(style.width, SizeValue::Viewport(50.0, ViewportUnit::Vw)); + assert_eq!( + style.margin.top, + MarginValue::Viewport(2.0, ViewportUnit::Vh) + ); + } + + #[test] + fn no_declarations_fall_back_to_inheritance_and_initial() { + let document = build_document("<div style=\"color: red\"><p>x</p></div>"); + let refs: Vec<&Stylesheet> = vec![]; + let div = find_first_by_name(&document, "div").expect("div"); + let div_style = cascade(&document, div, &refs, None, None); + assert_eq!(div_style.color, Rgba::opaque(255, 0, 0), "内联样式生效"); + assert_eq!( + div_style.background_color, + Rgba::transparent(), + "非继承属性取 initial" + ); + + let p = find_first_by_name(&document, "p").expect("p"); + let p_style = cascade(&document, p, &refs, None, Some(&div_style)); + assert_eq!(p_style.color, Rgba::opaque(255, 0, 0), "继承属性取父值"); + assert_eq!(p_style.background_color, Rgba::transparent()); + assert_eq!(p_style.font_size, 16.0); + } + + #[test] + fn specificity_beats_source_order() { + let style = style_of( + "<p class=\"a\">x</p>", + &["p { color: red } .a { color: blue }"], + "p", + ); + assert_eq!(style.color, Rgba::opaque(0, 0, 255)); + } + + #[test] + fn source_order_breaks_ties() { + let style = style_of( + "<p class=\"a\">x</p>", + &[".a { color: blue } p.a { color: red }"], + "p", + ); + assert_eq!(style.color, Rgba::opaque(255, 0, 0)); + } + + #[test] + fn important_beats_specificity() { + let style = style_of( + "<p class=\"a\">x</p>", + &["p.a { color: red } p { color: blue !important }"], + "p", + ); + assert_eq!(style.color, Rgba::opaque(0, 0, 255)); + } + + #[test] + fn inline_style_ordering() { + // 内联普通声明压过样式表普通声明 + let style = style_of("<p style=\"color: red\">x</p>", &["p { color: blue }"], "p"); + assert_eq!(style.color, Rgba::opaque(255, 0, 0)); + + // 样式表 !important 压过内联普通声明 + let style = style_of( + "<p style=\"color: red\">x</p>", + &["p { color: blue !important }"], + "p", + ); + assert_eq!(style.color, Rgba::opaque(0, 0, 255)); + + // 内联 !important 压过样式表 !important + let style = style_of( + "<p style=\"color: red !important\">x</p>", + &["p { color: blue !important }"], + "p", + ); + assert_eq!(style.color, Rgba::opaque(255, 0, 0)); + } + + #[test] + fn matching_rule_selectors_use_max_specificity() { + let style = style_of( + "<p class=\"x\">x</p>", + &["p, .x { color: red } p { color: blue }"], + "p", + ); + assert_eq!(style.color, Rgba::opaque(255, 0, 0)); + } + + #[test] + fn font_size_resolves_against_parent() { + // em / 百分比相对父元素计算字号 + let mut document = build_document( + "<div style=\"font-size: 20px\"><p style=\"font-size: 1.5em\">x</p></div>", + ); + let parsed = Stylesheet::parse(""); + let div = find_first_by_name(&document, "div").expect("div"); + let div_style = cascade(&document, div, &[&parsed], None, None); + assert_eq!(div_style.font_size, 20.0); + let p = find_first_by_name(&document, "p").expect("p"); + let p_style = cascade(&document, p, &[&parsed], None, Some(&div_style)); + assert_eq!(p_style.font_size, 30.0); + + // 继承的是计算值:孙辈再乘 em 时基于 30px + let span = document.create_node(nexty_dom::NodeKind::Element(nexty_dom::ElementData { + name: "span".into(), + namespace: nexty_dom::Namespace::Html, + attributes: Vec::new(), + })); + document.insert_node(span, p, None); + let span_style = cascade(&document, span, &[&parsed], None, Some(&p_style)); + assert_eq!(span_style.font_size, 30.0, "继承计算字号而非声明值"); + } + + #[test] + fn font_size_keywords_and_relative() { + let style = style_of("<p>x</p>", &["p { font-size: x-large }"], "p"); + assert_eq!(style.font_size, 24.0); + + // larger:父字号在表内时取下一项 + let document = build_document( + "<div style=\"font-size: large\"><p style=\"font-size: larger\">x</p></div>", + ); + let parsed = Stylesheet::parse(""); + let div_style = cascade( + &document, + find_first_by_name(&document, "div").unwrap(), + &[&parsed], + None, + None, + ); + let p_style = cascade( + &document, + find_first_by_name(&document, "p").unwrap(), + &[&parsed], + None, + Some(&div_style), + ); + assert_eq!( + p_style.font_size, + MEDIUM_FONT_SIZE * 1.5, + "large(1.2) → larger(1.5)" + ); + + // 表外字号用 1.2 比例 + let document = build_document( + "<div style=\"font-size: 100px\"><p style=\"font-size: smaller\">x</p></div>", + ); + let div_style = cascade( + &document, + find_first_by_name(&document, "div").unwrap(), + &[&parsed], + None, + None, + ); + let p_style = cascade( + &document, + find_first_by_name(&document, "p").unwrap(), + &[&parsed], + None, + Some(&div_style), + ); + assert!((p_style.font_size - 100.0 / 1.2).abs() < 1e-4); + } + + #[test] + fn font_weight_relative_table() { + // CSS Fonts 4 §2.2.1 映射表 + let cases: [(f32, &str, f32); 6] = [ + (50.0, "bolder", 400.0), + (200.0, "bolder", 400.0), + (400.0, "bolder", 700.0), + (600.0, "bolder", 900.0), + (950.0, "bolder", 950.0), + (950.0, "lighter", 700.0), + ]; + for (parent_weight, keyword, expected) in cases { + let document = build_document(&format!( + "<div style=\"font-weight: {parent_weight}\"><p style=\"font-weight: {keyword}\">x</p></div>" + )); + let parsed = Stylesheet::parse(""); + let div_style = cascade( + &document, + find_first_by_name(&document, "div").unwrap(), + &[&parsed], + None, + None, + ); + assert_eq!(div_style.font_weight, parent_weight); + let p_style = cascade( + &document, + find_first_by_name(&document, "p").unwrap(), + &[&parsed], + None, + Some(&div_style), + ); + assert_eq!( + p_style.font_weight, expected, + "{keyword} from {parent_weight}" + ); + } + } + + #[test] + fn css_wide_keywords() { + // inherit:无父元素 → initial + let style = style_of("<p style=\"color: inherit\">x</p>", &[], "p"); + assert_eq!(style.color, Rgba::opaque(0, 0, 0)); + + // unset:继承属性取父值 + let document = + build_document("<div style=\"color: red\"><p style=\"color: unset\">x</p></div>"); + let parsed = Stylesheet::parse(""); + let div_style = cascade( + &document, + find_first_by_name(&document, "div").unwrap(), + &[&parsed], + None, + None, + ); + let p_style = cascade( + &document, + find_first_by_name(&document, "p").unwrap(), + &[&parsed], + None, + Some(&div_style), + ); + assert_eq!(p_style.color, Rgba::opaque(255, 0, 0)); + + // unset:非继承属性取 initial + let style = style_of( + "<p style=\"background-color: unset\" class=\"x\">x</p>", + &["p.x { background-color: red }"], + "p", + ); + assert_eq!(style.background_color, Rgba::transparent()); + + // initial:显式回到 initial + let style = style_of( + "<p style=\"color: initial\">x</p>", + &["p { color: red }"], + "p", + ); + assert_eq!(style.color, Rgba::opaque(0, 0, 0)); + + // revert:回退到 UA origin(本层无 UA 声明 → initial) + let style = style_of( + "<p style=\"color: revert\">x</p>", + &["p { color: red }"], + "p", + ); + assert_eq!(style.color, Rgba::opaque(0, 0, 0)); + } + + #[test] + fn document_styles_walk_parents_first() { + let document = + build_document("<body><div style=\"color: red\"><p><em>x</em></p></div></body>"); + let sheet = Stylesheet::parse("em { font-style: italic }"); + let styles = compute_document_styles(&document, &[&sheet], None); + + let div = find_first_by_name(&document, "div").expect("div"); + let p = find_first_by_name(&document, "p").expect("p"); + let em = find_first_by_name(&document, "em").expect("em"); + + assert_eq!(styles[&div].color, Rgba::opaque(255, 0, 0)); + assert_eq!(styles[&p].color, Rgba::opaque(255, 0, 0), "p 继承 div"); + assert_eq!(styles[&em].color, Rgba::opaque(255, 0, 0), "em 继承 p"); + assert_eq!( + styles[&em].font_style, + FontStyleValue::Italic, + "样式表命中 em" + ); + // body 自身也在结果里 + let body = find_first_by_name(&document, "body").expect("body"); + assert_eq!(styles[&body].font_style, FontStyleValue::Normal); + } + + #[test] + fn multiple_stylesheets_cascade_in_order() { + let document = build_document("<p>x</p>"); + let first = Stylesheet::parse("p { color: red }"); + let second = Stylesheet::parse("p { color: blue }"); + let style = cascade( + &document, + find_first_by_name(&document, "p").unwrap(), + &[&first, &second], + None, + None, + ); + assert_eq!(style.color, Rgba::opaque(0, 0, 255), "后传入的样式表胜出"); + } + + #[test] + fn where_has_zero_specificity_is_takes_argument_max() { + // Selectors 4::where() 特异度为 0;:is() 取参数中的最大特异度 + let document = build_document("<p id=\"a\" class=\"x\">x</p>"); + let sheet = Stylesheet::parse( + "p { color: red } :where(p.x) { color: blue } :is(#a) { color: green }", + ); + let style = cascade( + &document, + find_first_by_name(&document, "p").unwrap(), + &[&sheet], + None, + None, + ); + // :is(#a) 特异度 (1,0,0) 压过其余两条 + assert_eq!(style.color, Rgba::opaque(0, 128, 0)); + + let sheet = Stylesheet::parse("p { color: red } :where(p.x) { color: blue }"); + let style = cascade( + &document, + find_first_by_name(&document, "p").unwrap(), + &[&sheet], + None, + None, + ); + // :where(p.x) 特异度为 0,p (0,0,1) 按源顺序在后仍胜出 + assert_eq!(style.color, Rgba::opaque(255, 0, 0)); + } + + #[test] + fn ua_origin_ordering_matches_cascade_5() { + let ua_block = Stylesheet::parse("div { display: block }"); + let ua_important_none = Stylesheet::parse("div { display: none !important }"); + let div = || build_document("<div>x</div>"); + + // UA normal < author normal + let document = div(); + let author = Stylesheet::parse("div { display: inline }"); + let style = cascade( + &document, + find_first_by_name(&document, "div").unwrap(), + &[], + Some(&ua_block), + None, + ); + assert_eq!( + style.display, + DisplayValue::Block, + "无 author 声明时 UA 生效" + ); + let style = cascade( + &document, + find_first_by_name(&document, "div").unwrap(), + &[&author], + Some(&ua_block), + None, + ); + assert_eq!( + style.display, + DisplayValue::Inline, + "author normal 压过 UA normal" + ); + + // author normal < author important < UA important + let document = div(); + let author_normal = Stylesheet::parse("div { display: block }"); + let style = cascade( + &document, + find_first_by_name(&document, "div").unwrap(), + &[&author_normal], + Some(&ua_important_none), + None, + ); + assert_eq!( + style.display, + DisplayValue::None, + "UA !important 压过 author normal" + ); + + let document = div(); + let author_important = Stylesheet::parse("div { display: block !important }"); + let style = cascade( + &document, + find_first_by_name(&document, "div").unwrap(), + &[&author_important], + Some(&ua_important_none), + None, + ); + assert_eq!( + style.display, + DisplayValue::None, + "UA !important 压过 author !important" + ); + } + + #[test] + fn html_ua_stylesheet_provides_rendering_defaults() { + let document = + build_document("<div><p>x</p></div><head></head><ul><li>item</li></ul><b>bold</b>"); + let styles = compute_document_styles(&document, &[], Some(html_ua_stylesheet())); + let display_of = |name: &str| { + let node = find_first_by_name(&document, name).expect(name); + styles[&node].display + }; + assert_eq!(display_of("div"), DisplayValue::Block); + assert_eq!(display_of("p"), DisplayValue::Block); + assert_eq!(display_of("head"), DisplayValue::None); + assert_eq!(display_of("li"), DisplayValue::ListItem); + assert_eq!( + display_of("b"), + DisplayValue::Inline, + "未列入 UA 表的元素保持 initial" + ); + + // author normal 声明覆盖 UA 默认 margin + let sheet = Stylesheet::parse("body { margin: 0 }"); + let styles = compute_document_styles(&document, &[&sheet], Some(html_ua_stylesheet())); + let body = find_first_by_name(&document, "body").expect("body"); + assert_eq!( + styles[&body].margin, + crate::Edges::splat(MarginValue::Length(0.0)) + ); + } + + #[test] + fn border_width_folds_style_and_currentcolor_resolves() { + // style 缺省为 none → computed 宽度 0(CSS 2.1 §8.5.4) + let style = style_of("<p>x</p>", &["p { border: 4px }"], "p"); + assert_eq!(style.border_width, Edges::splat(0.0)); + assert_eq!(style.border_style, Edges::splat(BorderStyle::None)); + + // style 可见 → 宽度生效;currentcolor 按本元素 color 解析 + let style = style_of( + "<p>x</p>", + &[ + "p { border: 2px solid; color: red; border-top-color: currentcolor; border-left-color: green }", + ], + "p", + ); + assert_eq!(style.border_width, Edges::splat(2.0)); + assert_eq!(style.border_style.top, BorderStyle::Solid); + assert_eq!( + style.border_color.top, + Rgba::opaque(255, 0, 0), + "currentcolor" + ); + assert_eq!(style.border_color.left, Rgba::opaque(0, 128, 0)); + assert_eq!( + style.border_color.bottom, + Rgba::opaque(255, 0, 0), + "border 简写缺省 color = currentcolor" + ); + } + + #[test] + fn line_height_computes_percent_and_em_to_absolute() { + let style = style_of( + "<p>x</p>", + &["p { font-size: 20px; line-height: 150% }"], + "p", + ); + assert_eq!(style.line_height, LineHeightValue::Length(30.0)); + + let style = style_of( + "<p>x</p>", + &["p { font-size: 20px; line-height: 1.2em }"], + "p", + ); + assert_eq!(style.line_height, LineHeightValue::Length(24.0)); + + // 数值保持数值:无单位数值按数值继承 + let document = build_document( + "<div style=\"font-size: 10px; line-height: 2\"><p style=\"font-size: 20px\">x</p></div>", + ); + let parsed = Stylesheet::parse(""); + let div = find_first_by_name(&document, "div").expect("div"); + let div_style = cascade(&document, div, &[&parsed], None, None); + let p = find_first_by_name(&document, "p").expect("p"); + let p_style = cascade(&document, p, &[&parsed], None, Some(&div_style)); + assert_eq!(div_style.line_height, LineHeightValue::Number(2.0)); + assert_eq!( + p_style.line_height, + LineHeightValue::Number(2.0), + "数值 line-height 以数值继承,不随父字号折算" + ); + } + + #[test] + fn box_model_properties_reach_computed_style() { + let style = style_of( + "<p style=\"margin: 10px 20%; padding: 5px; width: 300px; height: 50%\">x</p>", + &[], + "p", + ); + assert_eq!( + style.margin, + Edges { + top: MarginValue::Length(10.0), + right: MarginValue::Percent(0.2), + bottom: MarginValue::Length(10.0), + left: MarginValue::Percent(0.2), + } + ); + assert_eq!(style.padding, Edges::splat(PaddingValue::Length(5.0))); + assert_eq!(style.width, SizeValue::Length(300.0)); + assert_eq!(style.height, SizeValue::Percent(0.5)); + } + + #[test] + fn layout_properties_reach_computed_style() { + let style = style_of( + "<div style=\"position: absolute; top: 10px; right: 20%; bottom: auto; left: 5px;\ + flex-direction: column; flex-wrap: wrap; flex-shrink: 2;\ + align-items: center; justify-content: space-between; align-self: flex-end;\ + row-gap: 8px; column-gap: 4px; grid-auto-flow: row dense;\ + grid-template-columns: 100px 1fr; grid-template-rows: auto\">x</div>", + &[], + "div", + ); + assert_eq!(style.position, PositionValue::Absolute); + assert_eq!( + style.inset, + Edges { + top: InsetValue::Length(10.0), + right: InsetValue::Percent(0.2), + bottom: InsetValue::Auto, + left: InsetValue::Length(5.0), + } + ); + assert_eq!(style.flex_direction, FlexDirectionValue::Column); + assert_eq!(style.flex_wrap, FlexWrapValue::Wrap); + assert_eq!(style.flex_shrink, 2.0); + assert_eq!(style.align_items, AlignItemsValue::Center); + assert_eq!(style.justify_content, JustifyContentValue::SpaceBetween); + assert_eq!(style.align_self, AlignSelfValue::FlexEnd); + assert_eq!(style.row_gap, GapValue::Length(8.0)); + assert_eq!(style.column_gap, GapValue::Length(4.0)); + assert_eq!(style.grid_auto_flow, GridAutoFlowValue::RowDense); + assert_eq!( + style.grid_template_columns, + GridTrackList { + tracks: vec![GridTrack::Length(100.0), GridTrack::Fr(1.0)] + } + ); + assert_eq!( + style.grid_template_rows, + GridTrackList { + tracks: vec![GridTrack::Auto] + } + ); + } + + /// `white-space` / `overflow-wrap` / `word-break` 均继承,initial 为 `normal`。 + #[test] + fn text_breaking_properties_inherit() { + let document = build_document( + "<div style=\"white-space: nowrap; overflow-wrap: break-word; word-break: break-all\">\ + <p>x</p></div><span>y</span>", + ); + let parsed = Stylesheet::parse(""); + let div_style = cascade( + &document, + find_first_by_name(&document, "div").unwrap(), + &[&parsed], + None, + None, + ); + assert_eq!(div_style.white_space, WhiteSpaceValue::Nowrap); + assert_eq!(div_style.overflow_wrap, OverflowWrapValue::BreakWord); + assert_eq!(div_style.word_break, WordBreakValue::BreakAll); + + let p_style = cascade( + &document, + find_first_by_name(&document, "p").unwrap(), + &[&parsed], + None, + Some(&div_style), + ); + assert_eq!( + p_style.white_space, + WhiteSpaceValue::Nowrap, + "子继承 nowrap" + ); + assert_eq!(p_style.overflow_wrap, OverflowWrapValue::BreakWord); + assert_eq!(p_style.word_break, WordBreakValue::BreakAll); + + // 无声明:initial 为 normal + let style = style_of("<span>y</span>", &[], "span"); + assert_eq!(style.white_space, WhiteSpaceValue::Normal); + assert_eq!(style.overflow_wrap, OverflowWrapValue::Normal); + assert_eq!(style.word_break, WordBreakValue::Normal); + } + + /// UA 表给 `<pre>` 系元素 `white-space: pre`,author 声明可覆盖。 + #[test] + fn ua_stylesheet_sets_white_space_pre() { + let document = build_document("<pre>a\nb</pre><div>c</div>"); + let styles = compute_document_styles(&document, &[], Some(html_ua_stylesheet())); + let pre = find_first_by_name(&document, "pre").expect("pre"); + assert_eq!(styles[&pre].white_space, WhiteSpaceValue::Pre); + let div = find_first_by_name(&document, "div").expect("div"); + assert_eq!(styles[&div].white_space, WhiteSpaceValue::Normal); + + // author 普通声明压过 UA + let sheet = Stylesheet::parse("pre { white-space: pre-wrap }"); + let styles = compute_document_styles(&document, &[&sheet], Some(html_ua_stylesheet())); + assert_eq!(styles[&pre].white_space, WhiteSpaceValue::PreWrap); + } +} diff --git a/crates/nexty-css/.mimosa/hook-state/session_164476f9d97ffaabe4f6dc9715b6aad5.mvmgp416-93016-2afbe7aa51.baseline/b1a35a68f14e696205874893c07fd24fdb88882b47c23cc0e0c80a30c7d53759.source b/crates/nexty-css/.mimosa/hook-state/session_164476f9d97ffaabe4f6dc9715b6aad5.mvmgp416-93016-2afbe7aa51.baseline/b1a35a68f14e696205874893c07fd24fdb88882b47c23cc0e0c80a30c7d53759.source new file mode 100644 index 0000000..a5ba83c --- /dev/null +++ b/crates/nexty-css/.mimosa/hook-state/session_164476f9d97ffaabe4f6dc9715b6aad5.mvmgp416-93016-2afbe7aa51.baseline/b1a35a68f14e696205874893c07fd24fdb88882b47c23cc0e0c80a30c7d53759.source @@ -0,0 +1,50 @@ +//! Nexty CSS 层 facade:解析、选择器匹配与自研 cascade。 +//! +//! 上游:`cssparser` + `selectors`(均 MPL-2.0),只用于解析与选择器匹配; +//! cascade 与 computed style 自研,可从 MusKitty 迁移已有实现。决策见 +//! `docs/decisions/2026-10-01-crate-selection.md`。 +//! +//! 行为 ground truth:CSS Syntax、Selectors、CSS Cascade 规范。 +//! +//! 已落地:属性值模型与逐属性解析(`value`)、选择器解析与 arena DOM 匹配 +//! (`selector`)、样式表与声明块解析(`parser`)、自研 cascade 与 computed +//! style(`cascade`)、UA 默认样式表(`ua`)。 +//! +//! **Feature**:按上表的五个模块一一对应,默认全开。依赖链为 +//! `values` → `selectors` → `stylesheets` → {`cascade`, `ua-stylesheet`}, +//! 各 feature 按需上拉依赖(见 Cargo.toml)。 + +#![forbid(unsafe_code)] + +#[cfg(feature = "cascade")] +mod cascade; +#[cfg(feature = "stylesheets")] +mod parser; +#[cfg(feature = "selectors")] +mod selector; +#[cfg(test)] +mod test_support; +#[cfg(feature = "ua-stylesheet")] +mod ua; +#[cfg(feature = "values")] +mod value; + +#[cfg(feature = "cascade")] +pub use cascade::{ + ComputedStyle, Edges, cascade, cascade_in, compute_document_styles, compute_document_styles_in, +}; +#[cfg(feature = "stylesheets")] +pub use parser::{Declaration, MediaViewport, StyleRule, Stylesheet, parse_inline_style}; +#[cfg(feature = "selectors")] +pub use selector::{SelectorError, matches_selector}; +#[cfg(feature = "ua-stylesheet")] +pub use ua::html_ua_stylesheet; +#[cfg(feature = "values")] +pub use value::{ + AbsoluteSize, AlignItemsValue, AlignSelfValue, BorderColorValue, BorderStyle, BorderWidthValue, + BoxSizingValue, CssWideKeyword, DeclaredValue, DisplayValue, FlexDirectionValue, FlexWrapValue, + FontFamilyValue, FontSizeValue, FontStyleValue, FontWeightValue, GapValue, GridAutoFlowValue, + GridTrack, GridTrackList, InsetValue, JustifyContentValue, LineHeightValue, MarginValue, + OverflowValue, OverflowWrapValue, PaddingValue, PositionValue, PropertyId, PropertyValue, Rgba, + SizeValue, TextAlignValue, ViewportUnit, WhiteSpaceValue, WordBreakValue, +}; diff --git a/crates/nexty-css/.mimosa/hook-state/session_164476f9d97ffaabe4f6dc9715b6aad5.mvmgp416-93016-2afbe7aa51.baseline/be1c878c753064b7eaddf4a10ba4215a93dd1817d31e6788691cdb29752fd612.source b/crates/nexty-css/.mimosa/hook-state/session_164476f9d97ffaabe4f6dc9715b6aad5.mvmgp416-93016-2afbe7aa51.baseline/be1c878c753064b7eaddf4a10ba4215a93dd1817d31e6788691cdb29752fd612.source new file mode 100644 index 0000000..cbfe603 --- /dev/null +++ b/crates/nexty-css/.mimosa/hook-state/session_164476f9d97ffaabe4f6dc9715b6aad5.mvmgp416-93016-2afbe7aa51.baseline/be1c878c753064b7eaddf4a10ba4215a93dd1817d31e6788691cdb29752fd612.source @@ -0,0 +1,3181 @@ +//! 属性值模型与逐属性解析。 +//! +//! 行为 ground truth: +//! - CSS-wide 关键字:[CSS Cascading and Inheritance Level 5 §6](https://drafts.csswg.org/css-cascade-5/#defaulting-keywords) +//! - 颜色:[CSS Color Module Level 4](https://drafts.csswg.org/css-color-4/)(hex / rgb() / hsl() / 命名色) +//! - 字号:[CSS Fonts Module Level 4 §2.5](https://drafts.csswg.org/css-fonts-4/#font-size-prop) +//! - 字重:[CSS Fonts Module Level 4 §2.2](https://drafts.csswg.org/css-fonts-4/#font-weight-numeric) +//! - 字体族:[CSS Fonts Module Level 4 §2.3](https://drafts.csswg.org/css-fonts-4/#font-family-prop) +//! - font 简写:[CSS Fonts Module Level 4 §3.3](https://drafts.csswg.org/css-fonts-4/#font-prop) +//! - display:[CSS Display Module Level 3](https://drafts.csswg.org/css-display-3/#the-display-properties) +//! - text-align:[CSS Text Module Level 4](https://drafts.csswg.org/css-text-4/#text-align-property) +//! +//! 已知偏差(按需再补,见本轮 goal.md 非目标):`rem` / `ex` / `ch` 等 +//! 相对单位、`currentcolor`、`color-mix()` 等函数色、`display` 的多关键字 +//! 语法与 ruby 内部盒、`var()` 均视为无效声明(浏览器会接受其中的合法值)。 +//! 视口单位(`vw`/`vh`/`vmin`/`vmax`)只在盒级长度属性(width/height/min/max、 +//! inset、margin、padding、gap)上接受;`font-size` / `border-width` / +//! `line-height` 上的视口单位视为无效声明。 +//! `font` 简写里无对应 longhand 的成分——`<font-variant-css2>`(`small-caps`) +//! 与 `<font-width-css3>`(宽度关键字/百分比)——按语法接受后丢弃(无渲染 +//! 效果但声明不整体失效);系统字体关键字(`caption` / `menu` 等)整条无效。 +//! +//! **Feature**:本模块受 `values` feature 控制(由 lib.rs 装配)。其中的 +//! `parse_*` 逐属性解析函数供 `parser` / `cascade` 模块消费,故当上层 feature +//! 关闭时这些内部函数没有调用方——此时按模块整体抑制 dead_code。 + +#![cfg_attr(not(feature = "stylesheets"), allow(dead_code))] + +use cssparser::{ParseError, Parser, Token, parse_important}; + +/// 非预乘 sRGB 颜色。 +/// +/// 对应 CSS Color 4 的 [`<color>`](https://drafts.csswg.org/css-color-4/#color-syntax) +/// 解析结果;alpha 与各通道均量化到 8bit。 +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +pub struct Rgba { + /// 红通道。 + pub r: u8, + /// 绿通道。 + pub g: u8, + /// 蓝通道。 + pub b: u8, + /// alpha 通道。 + pub a: u8, +} + +impl Rgba { + /// 不透明颜色。 + #[must_use] + pub const fn opaque(r: u8, g: u8, b: u8) -> Self { + Self { r, g, b, a: 0xff } + } + + /// 全透明黑,即 CSS 关键字 `transparent` + /// ([CSS Color 4 §5.5](https://drafts.csswg.org/css-color-4/#transparent-color))。 + #[must_use] + pub const fn transparent() -> Self { + Self { + r: 0, + g: 0, + b: 0, + a: 0, + } + } +} + +/// 级联引擎认识的最小属性集合。 +/// +/// 只覆盖当前管线需要的属性;新属性随消费方(layout / text / paint)落地时加入, +/// 不预先铺满。属性元数据(inherited / initial)见 `cascade` 模块。 +#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)] +pub enum PropertyId { + /// `display`。 + Display, + /// `color`。 + Color, + /// `background-color`。 + BackgroundColor, + /// `font-size`。 + FontSize, + /// `font-weight`。 + FontWeight, + /// `font-style`。 + FontStyle, + /// `font-family`。 + FontFamily, + /// `text-align`。 + TextAlign, + /// `line-height`。 + LineHeight, + /// `white-space`。 + WhiteSpace, + /// `overflow-wrap`。 + OverflowWrap, + /// `word-break`。 + WordBreak, + /// `width`。 + Width, + /// `height`。 + Height, + /// `min-width`。 + MinWidth, + /// `max-width`。 + MaxWidth, + /// `min-height`。 + MinHeight, + /// `max-height`。 + MaxHeight, + /// `box-sizing`。 + BoxSizing, + /// `overflow`。 + Overflow, + /// `flex-grow`。 + FlexGrow, + /// `flex-basis`。 + FlexBasis, + /// `position`。 + Position, + /// `top`。 + Top, + /// `right`。 + Right, + /// `bottom`。 + Bottom, + /// `left`。 + Left, + /// `flex-direction`。 + FlexDirection, + /// `flex-wrap`。 + FlexWrap, + /// `flex-shrink`。 + FlexShrink, + /// `align-items`。 + AlignItems, + /// `justify-content`。 + JustifyContent, + /// `align-self`。 + AlignSelf, + /// `grid-template-columns`。 + GridTemplateColumns, + /// `grid-template-rows`。 + GridTemplateRows, + /// `row-gap`。 + RowGap, + /// `column-gap`。 + ColumnGap, + /// `grid-auto-flow`。 + GridAutoFlow, + /// `margin-top`。 + MarginTop, + /// `margin-right`。 + MarginRight, + /// `margin-bottom`。 + MarginBottom, + /// `margin-left`。 + MarginLeft, + /// `padding-top`。 + PaddingTop, + /// `padding-right`。 + PaddingRight, + /// `padding-bottom`。 + PaddingBottom, + /// `padding-left`。 + PaddingLeft, + /// `border-top-style`。 + BorderTopStyle, + /// `border-right-style`。 + BorderRightStyle, + /// `border-bottom-style`。 + BorderBottomStyle, + /// `border-left-style`。 + BorderLeftStyle, + /// `border-top-width`。 + BorderTopWidth, + /// `border-right-width`。 + BorderRightWidth, + /// `border-bottom-width`。 + BorderBottomWidth, + /// `border-left-width`。 + BorderLeftWidth, + /// `border-top-color`。 + BorderTopColor, + /// `border-right-color`。 + BorderRightColor, + /// `border-bottom-color`。 + BorderBottomColor, + /// `border-left-color`。 + BorderLeftColor, +} + +impl PropertyId { + /// 属性的规范名(小写)。 + #[must_use] + pub fn as_str(self) -> &'static str { + match self { + PropertyId::Display => "display", + PropertyId::Color => "color", + PropertyId::BackgroundColor => "background-color", + PropertyId::FontSize => "font-size", + PropertyId::FontWeight => "font-weight", + PropertyId::FontStyle => "font-style", + PropertyId::FontFamily => "font-family", + PropertyId::TextAlign => "text-align", + PropertyId::LineHeight => "line-height", + PropertyId::WhiteSpace => "white-space", + PropertyId::OverflowWrap => "overflow-wrap", + PropertyId::WordBreak => "word-break", + PropertyId::Width => "width", + PropertyId::Height => "height", + PropertyId::MinWidth => "min-width", + PropertyId::MaxWidth => "max-width", + PropertyId::MinHeight => "min-height", + PropertyId::MaxHeight => "max-height", + PropertyId::BoxSizing => "box-sizing", + PropertyId::Overflow => "overflow", + PropertyId::FlexGrow => "flex-grow", + PropertyId::FlexBasis => "flex-basis", + PropertyId::Position => "position", + PropertyId::Top => "top", + PropertyId::Right => "right", + PropertyId::Bottom => "bottom", + PropertyId::Left => "left", + PropertyId::FlexDirection => "flex-direction", + PropertyId::FlexWrap => "flex-wrap", + PropertyId::FlexShrink => "flex-shrink", + PropertyId::AlignItems => "align-items", + PropertyId::JustifyContent => "justify-content", + PropertyId::AlignSelf => "align-self", + PropertyId::GridTemplateColumns => "grid-template-columns", + PropertyId::GridTemplateRows => "grid-template-rows", + PropertyId::RowGap => "row-gap", + PropertyId::ColumnGap => "column-gap", + PropertyId::GridAutoFlow => "grid-auto-flow", + PropertyId::MarginTop => "margin-top", + PropertyId::MarginRight => "margin-right", + PropertyId::MarginBottom => "margin-bottom", + PropertyId::MarginLeft => "margin-left", + PropertyId::PaddingTop => "padding-top", + PropertyId::PaddingRight => "padding-right", + PropertyId::PaddingBottom => "padding-bottom", + PropertyId::PaddingLeft => "padding-left", + PropertyId::BorderTopStyle => "border-top-style", + PropertyId::BorderRightStyle => "border-right-style", + PropertyId::BorderBottomStyle => "border-bottom-style", + PropertyId::BorderLeftStyle => "border-left-style", + PropertyId::BorderTopWidth => "border-top-width", + PropertyId::BorderRightWidth => "border-right-width", + PropertyId::BorderBottomWidth => "border-bottom-width", + PropertyId::BorderLeftWidth => "border-left-width", + PropertyId::BorderTopColor => "border-top-color", + PropertyId::BorderRightColor => "border-right-color", + PropertyId::BorderBottomColor => "border-bottom-color", + PropertyId::BorderLeftColor => "border-left-color", + } + } + + /// 按属性名查 [`PropertyId`],ASCII case-insensitive + /// (CSS Syntax:声明名匹配大小写不敏感)。 + #[must_use] + pub fn from_name(name: &str) -> Option<Self> { + const ALL: [PropertyId; 58] = [ + PropertyId::Display, + PropertyId::Color, + PropertyId::BackgroundColor, + PropertyId::FontSize, + PropertyId::FontWeight, + PropertyId::FontStyle, + PropertyId::FontFamily, + PropertyId::TextAlign, + PropertyId::LineHeight, + PropertyId::WhiteSpace, + PropertyId::OverflowWrap, + PropertyId::WordBreak, + PropertyId::Width, + PropertyId::Height, + PropertyId::MinWidth, + PropertyId::MaxWidth, + PropertyId::MinHeight, + PropertyId::MaxHeight, + PropertyId::BoxSizing, + PropertyId::Overflow, + PropertyId::FlexGrow, + PropertyId::FlexBasis, + PropertyId::Position, + PropertyId::Top, + PropertyId::Right, + PropertyId::Bottom, + PropertyId::Left, + PropertyId::FlexDirection, + PropertyId::FlexWrap, + PropertyId::FlexShrink, + PropertyId::AlignItems, + PropertyId::JustifyContent, + PropertyId::AlignSelf, + PropertyId::GridTemplateColumns, + PropertyId::GridTemplateRows, + PropertyId::RowGap, + PropertyId::ColumnGap, + PropertyId::GridAutoFlow, + PropertyId::MarginTop, + PropertyId::MarginRight, + PropertyId::MarginBottom, + PropertyId::MarginLeft, + PropertyId::PaddingTop, + PropertyId::PaddingRight, + PropertyId::PaddingBottom, + PropertyId::PaddingLeft, + PropertyId::BorderTopStyle, + PropertyId::BorderRightStyle, + PropertyId::BorderBottomStyle, + PropertyId::BorderLeftStyle, + PropertyId::BorderTopWidth, + PropertyId::BorderRightWidth, + PropertyId::BorderBottomWidth, + PropertyId::BorderLeftWidth, + PropertyId::BorderTopColor, + PropertyId::BorderRightColor, + PropertyId::BorderBottomColor, + PropertyId::BorderLeftColor, + ]; + ALL.into_iter() + .find(|id| id.as_str().eq_ignore_ascii_case(name)) + } +} + +/// CSS-wide 关键字 +/// ([CSS Cascade 5 §6.1](https://drafts.csswg.org/css-cascade-5/#defaulting-keywords))。 +/// +/// 对任何属性都合法,求值语义由 cascade 模块实现。 +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +pub enum CssWideKeyword { + /// `initial`。 + Initial, + /// `inherit`。 + Inherit, + /// `unset`。 + Unset, + /// `revert`。 + Revert, +} + +/// 一条声明按属性解析后的值。 +#[derive(Debug, Clone, PartialEq)] +pub enum DeclaredValue { + /// CSS-wide 关键字(对任意属性合法)。 + CssWide(CssWideKeyword), + /// 按属性语法解析出的值。 + Typed(PropertyValue), +} + +/// 各属性解析后的值。 +/// +/// 每个变体对应 [`PropertyId`] 中一个属性的可接受语法;不在集合内的值按 +/// 无效声明处理(整体丢弃,声明级恢复,见 CSS Syntax §5.5)。 +#[derive(Debug, Clone, PartialEq)] +pub enum PropertyValue { + /// `display` 关键字。 + Display(DisplayValue), + /// `text-align` 关键字。 + TextAlign(TextAlignValue), + /// `font-style` 关键字。 + FontStyle(FontStyleValue), + /// 颜色值。 + Color(Rgba), + /// `font-size` 值。 + FontSize(FontSizeValue), + /// `font-weight` 值。 + FontWeight(FontWeightValue), + /// `font-family` 字体族列表。 + FontFamily(Vec<FontFamilyValue>), + /// `line-height` 值。 + LineHeight(LineHeightValue), + /// `white-space` 关键字。 + WhiteSpace(WhiteSpaceValue), + /// `overflow-wrap` 关键字。 + OverflowWrap(OverflowWrapValue), + /// `word-break` 关键字。 + WordBreak(WordBreakValue), + /// `width` / `height` 值(min-width / max-width / min-height / max-height + /// 复用同一语法)。 + Size(SizeValue), + /// `box-sizing` 关键字。 + BoxSizing(BoxSizingValue), + /// `overflow` 关键字。 + Overflow(OverflowValue), + /// `flex-grow` 数值。 + FlexGrow(f32), + /// `flex-basis` 值(auto | <length-percentage>)。 + FlexBasis(SizeValue), + /// `position` 关键字。 + Position(PositionValue), + /// `top` / `right` / `bottom` / `left` 值。 + Inset(InsetValue), + /// `flex-direction` 关键字。 + FlexDirection(FlexDirectionValue), + /// `flex-wrap` 关键字。 + FlexWrap(FlexWrapValue), + /// `flex-shrink` 数值。 + FlexShrink(f32), + /// `align-items` 关键字。 + AlignItems(AlignItemsValue), + /// `justify-content` 关键字。 + JustifyContent(JustifyContentValue), + /// `align-self` 关键字。 + AlignSelf(AlignSelfValue), + /// `grid-template-columns` / `grid-template-rows` 轨道列表。 + GridTrack(GridTrackList), + /// `row-gap` / `column-gap` 值。 + Gap(GapValue), + /// `grid-auto-flow` 关键字。 + GridAutoFlow(GridAutoFlowValue), + /// margin 值(四边共用)。 + Margin(MarginValue), + /// padding 值(四边共用)。 + Padding(PaddingValue), + /// border-*-width 值。 + BorderWidth(BorderWidthValue), + /// border-*-style 关键字。 + BorderStyle(BorderStyle), + /// border-*-color 值。 + BorderColor(BorderColorValue), +} + +/// `display` 的单关键字值 +/// ([CSS Display 3 §2](https://drafts.csswg.org/css-display-3/#the-display-properties))。 +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +pub enum DisplayValue { + /// `inline`(initial)。 + Inline, + /// `block`。 + Block, + /// `list-item`。 + ListItem, + /// `inline-block`。 + InlineBlock, + /// `flow-root`。 + FlowRoot, + /// `flex`。 + Flex, + /// `inline-flex`。 + InlineFlex, + /// `grid`。 + Grid, + /// `inline-grid`。 + InlineGrid, + /// `table`。 + Table, + /// `inline-table`。 + InlineTable, + /// 表格内部盒(`table-row-group` / `table-header-group` / + /// `table-footer-group` / `table-row` / `table-cell` / + /// `table-column-group` / `table-column` / `table-caption`)。 + TableInternal(&'static str), + /// `contents`。 + Contents, + /// `none`。 + None, +} + +/// `text-align` 值 +/// ([CSS Text 4](https://drafts.csswg.org/css-text-4/#text-align-property))。 +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +pub enum TextAlignValue { + /// `start`(initial)。 + Start, + /// `end`。 + End, + /// `left`。 + Left, + /// `right`。 + Right, + /// `center`。 + Center, + /// `justify`。 + Justify, + /// `match-parent`。 + MatchParent, + /// `justify-all`。 + JustifyAll, +} + +/// `white-space` 值 +/// ([CSS Text 3 §3.1](https://drafts.csswg.org/css-text-3/#white-space-property))。 +/// +/// 本层按单属性实现(CSS Text 4 的 `white-space-collapse` + `text-wrap-mode` +/// 拆分记为偏差)。语义: +/// +/// | 值 | 空白 | 软换行 | +/// | --- | --- | --- | +/// | `normal`(initial) | 折叠 | 允许 | +/// | `nowrap` | 折叠 | 禁止 | +/// | `pre` | 保留(`\n` 强断) | 禁止 | +/// | `pre-wrap` | 保留(`\n` 强断) | 允许 | +/// | `pre-line` | 折叠空格、保留 `\n`(强断) | 允许 | +/// | `break-spaces` | 保留(含行尾,`\n` 强断) | 允许(每个空格后) | +#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)] +pub enum WhiteSpaceValue { + /// `normal`(initial)。 + #[default] + Normal, + /// `nowrap`。 + Nowrap, + /// `pre`。 + Pre, + /// `pre-wrap`。 + PreWrap, + /// `pre-line`。 + PreLine, + /// `break-spaces`。 + BreakSpaces, +} + +impl WhiteSpaceValue { + /// 是否折叠可折叠空白(空格 / 制表 / 段内换行)。 + #[must_use] + pub fn collapses(self) -> bool { + matches!(self, Self::Normal | Self::Nowrap | Self::PreLine) + } + + /// 是否保留段内换行(`\n` 作为强断行)。 + #[must_use] + pub fn preserves_newlines(self) -> bool { + !matches!(self, Self::Normal | Self::Nowrap) + } + + /// 是否允许软换行(UAX#14 断点)。 + #[must_use] + pub fn wraps(self) -> bool { + !matches!(self, Self::Nowrap | Self::Pre) + } +} + +/// `overflow-wrap` 值 +/// ([CSS Text 3 §5.4](https://drafts.csswg.org/css-text-3/#overflow-wrap-property))。 +#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)] +pub enum OverflowWrapValue { + /// `normal`(initial):只在 UAX#14 允许的位置断行。 + #[default] + Normal, + /// `break-word`:溢出时可在任意字形簇之间断行;不参与 min-content。 + BreakWord, + /// `anywhere`:溢出时可断,且断点参与 min-content。 + Anywhere, +} + +/// `word-break` 值 +/// ([CSS Text 3 §5.1](https://drafts.csswg.org/css-text-3/#word-break-property))。 +#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)] +pub enum WordBreakValue { + /// `normal`(initial)。 + #[default] + Normal, + /// `break-all`:在相邻 typographic letter unit 之间允许断行 + /// (不切开字形簇)。 + BreakAll, + /// `keep-all`:禁止 CJK 等词内部断行。 + KeepAll, +} + +/// `font-style` 值 +/// ([CSS Fonts 4 §2.1](https://drafts.csswg.org/css-fonts-4/#font-style-prop))。 +#[derive(Debug, Clone, Copy, PartialEq)] +pub enum FontStyleValue { + /// `normal`(initial)。 + Normal, + /// `italic`。 + Italic, + /// `oblique`,可选倾斜角(角度制;`oblique none` 为 `None`)。 + Oblique(Option<f32>), +} + +/// `font-size` 的绝对尺寸关键字及其缩放系数 +/// ([CSS Fonts 4 §2.5.1](https://drafts.csswg.org/css-fonts-4/#absolute-size-mapping): +/// medium 为基准 1,其余为规范给出的 scaling factor)。 +#[derive(Debug, Clone, Copy, PartialEq)] +pub enum AbsoluteSize { + /// `xx-small`(3/5)。 + XxSmall, + /// `x-small`(3/4)。 + XSmall, + /// `small`(8/9)。 + Small, + /// `medium`(1)。 + Medium, + /// `large`(6/5)。 + Large, + /// `x-large`(3/2)。 + XLarge, + /// `xx-large`(2/1)。 + XxLarge, + /// `xxx-large`(3/1)。 + XxxLarge, +} + +impl AbsoluteSize { + /// 相对 medium 的缩放系数。 + #[must_use] + pub fn factor(self) -> f32 { + match self { + AbsoluteSize::XxSmall => 3.0 / 5.0, + AbsoluteSize::XSmall => 3.0 / 4.0, + AbsoluteSize::Small => 8.0 / 9.0, + AbsoluteSize::Medium => 1.0, + AbsoluteSize::Large => 6.0 / 5.0, + AbsoluteSize::XLarge => 1.5, + AbsoluteSize::XxLarge => 2.0, + AbsoluteSize::XxxLarge => 3.0, + } + } + + /// 绝对尺寸关键字的有序表,供 `larger` / `smaller` 取相邻项。 + pub const ORDERED: [AbsoluteSize; 8] = [ + AbsoluteSize::XxSmall, + AbsoluteSize::XSmall, + AbsoluteSize::Small, + AbsoluteSize::Medium, + AbsoluteSize::Large, + AbsoluteSize::XLarge, + AbsoluteSize::XxLarge, + AbsoluteSize::XxxLarge, + ]; +} + +/// `font-size` 值 +/// ([CSS Fonts 4 §2.5](https://drafts.csswg.org/css-fonts-4/#font-size-prop))。 +#[derive(Debug, Clone, Copy, PartialEq)] +pub enum FontSizeValue { + /// 绝对长度(已折算为 CSS px)。 + Px(f32), + /// 相对父元素计算字号的 em。 + Em(f32), + /// 相对父元素计算字号的百分比,以小数存储(`120%` → `1.2`)。 + Percent(f32), + /// 绝对尺寸关键字。 + Absolute(AbsoluteSize), + /// `larger`。 + Larger, + /// `smaller`。 + Smaller, +} + +/// `font-weight` 值 +/// ([CSS Fonts 4 §2.2](https://drafts.csswg.org/css-fonts-4/#font-weight-numeric))。 +#[derive(Debug, Clone, Copy, PartialEq)] +pub enum FontWeightValue { + /// 数值字重,1–1000(`normal` = 400、`bold` = 700 已在解析期折算)。 + Weight(f32), + /// `bolder`:相对继承值。 + Bolder, + /// `lighter`:相对继承值。 + Lighter, +} + +/// 字体族列表中的一项 +/// ([CSS Fonts 4 §2.3](https://drafts.csswg.org/css-fonts-4/#font-family-prop))。 +/// +/// 带引号的 `"serif"` 是名为 serif 的普通字体族,只有不带引号的 +/// generic 关键字才映射到 [`FontFamilyValue`] 的 generic 变体。 +#[derive(Debug, Clone, PartialEq, Eq)] +pub enum FontFamilyValue { + /// generic 族(`serif` / `sans-serif` / `cursive` / `fantasy` / + /// `monospace` / `system-ui` / `ui-serif` / `ui-sans-serif` / + /// `ui-monospace` / `ui-rounded` / `math` / `emoji` / `fangsong`)。 + Generic(&'static str), + /// 具名字体族。 + Family(String), +} + +/// `line-height` 值 +/// ([CSS 2.1 §10.8.1](https://www.w3.org/TR/CSS21/visudet.html#line-height))。 +/// +/// 数值保持数值(以自身数值继承,子元素按自身 font-size 求值); +/// 百分比与 em 在 computed 阶段按元素自身 font-size 折算(cascade 模块)。 +#[derive(Debug, Clone, Copy, PartialEq)] +pub enum LineHeightValue { + /// `normal`(initial,约 1.2,具体由 UA 决定)。 + Normal, + /// 无单位数值(可为 0,不可为负)。 + Number(f32), + /// 绝对长度(已折算为 CSS px)。 + Length(f32), + /// 相对自身 font-size 的 em。 + Em(f32), + /// 百分比(以小数存储,`150%` → `1.5`;computed 阶段乘 font-size)。 + Percent(f32), +} + +/// `width` / `height` 值 +/// ([CSS 2.1 §10.2](https://www.w3.org/TR/CSS21/visudet.html#the-width-property)、 +/// [§10.5](https://www.w3.org/TR/CSS21/visudet.html#the-height-property))。 +/// +/// 百分比由 layout 相对包含块宽度解析;负值非法(声明无效)。 +#[derive(Debug, Clone, Copy, PartialEq)] +pub enum SizeValue { + /// `auto`(initial)。 + Auto, + /// 绝对长度(CSS px)。 + Length(f32), + /// 百分比(以小数存储)。 + Percent(f32), + /// 视口单位(`50vw` → `Viewport(50.0, Vw)`);cascade 在 computed 阶段 + /// 按视口尺寸折算为 [`SizeValue::Length`],无视口信息时原样保留。 + Viewport(f32, ViewportUnit), +} + +/// `box-sizing` 值 +/// ([CSS Sizing 4 §5.3](https://drafts.csswg.org/css-sizing-4/#box-sizing))。 +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +pub enum BoxSizingValue { + /// `content-box`(initial):width/height 指内容盒。 + ContentBox, + /// `border-box`:width/height 指边框盒。 + BorderBox, +} + +/// `overflow` 值 +/// ([CSS Overflow 3 §3](https://drafts.csswg.org/css-overflow-3/#overflow-control))。 +/// +/// 本层只建模 visible / hidden 的裁剪标记;`auto` / `scroll` / `clip` +/// 暂按无效声明丢弃(回退 initial `visible`,见模块偏差)。 +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +pub enum OverflowValue { + /// `visible`(initial):内容溢出可见。 + Visible, + /// `hidden`:内容裁剪标记(裁剪实现待 paint/layout 接入)。 + Hidden, +} + +/// `position` 值 +/// ([CSS Position 3 §2](https://drafts.csswg.org/css-position-3/#position-properties))。 +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +pub enum PositionValue { + /// `static`(initial):常规流,不建立包含块。 + Static, + /// `relative`:相对自身偏移,仍占常规流空间。 + Relative, + /// `absolute`:相对最近定位祖先(无则视口)定位,脱离常规流。 + Absolute, + /// `fixed`:相对视口定位(本布局层按 absolute 处理)。 + Fixed, +} + +/// `top` / `right` / `bottom` / `left` 值(inset) +/// ([CSS Position 3 §3](https://drafts.csswg.org/css-position-3/#insets))。 +#[derive(Debug, Clone, Copy, PartialEq)] +pub enum InsetValue { + /// 绝对长度(CSS px)。 + Length(f32), + /// 百分比(相对包含块对应轴尺寸;本层仅垂直相对高度,水平相对宽度, + /// 由 layout 解析)。 + Percent(f32), + /// `auto`(initial)。 + Auto, + /// 视口单位;cascade 在 computed 阶段折算(同 [`SizeValue::Viewport`])。 + Viewport(f32, ViewportUnit), +} + +/// `flex-direction` 值 +/// ([CSS Flexbox §8.3.1](https://drafts.csswg.org/css-flexbox/#flex-direction-property))。 +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +pub enum FlexDirectionValue { + /// `row`(initial)。 + Row, + /// `row-reverse`。 + RowReverse, + /// `column`。 + Column, + /// `column-reverse`。 + ColumnReverse, +} + +/// `flex-wrap` 值 +/// ([CSS Flexbox §8.4.1](https://drafts.csswg.org/css-flexbox/#flex-wrap-property))。 +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +pub enum FlexWrapValue { + /// `nowrap`(initial):单行。 + NoWrap, + /// `wrap`:多行。 + Wrap, + /// `wrap-reverse`:多行反向。 + WrapReverse, +} + +/// `align-items` / `align-self` 的 cross-axis 对齐值 +/// ([CSS Box Alignment §7](https://drafts.csswg.org/css-align-3/#align-items-property))。 +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +pub enum AlignItemsValue { + /// `stretch`(initial)。 + Stretch, + /// `flex-start` / `start`。 + FlexStart, + /// `flex-end` / `end`。 + FlexEnd, + /// `center`。 + Center, + /// `baseline`。 + Baseline, +} + +/// `justify-content` 的主轴对齐值 +/// ([CSS Box Alignment §8](https://drafts.csswg.org/css-align-3/#justify-content-property))。 +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +pub enum JustifyContentValue { + /// `flex-start` / `start`(initial)。 + FlexStart, + /// `flex-end` / `end`。 + FlexEnd, + /// `center`。 + Center, + /// `space-between`。 + SpaceBetween, + /// `space-around`。 + SpaceAround, + /// `space-evenly`。 + SpaceEvenly, +} + +/// `align-self` 值(在 `align-items` 基础上多一个 `auto` 回退父值)。 +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +pub enum AlignSelfValue { + /// `auto`(initial):回退到父 `align-items`。 + Auto, + /// 同 [`AlignItemsValue::Stretch`]。 + Stretch, + /// 同 [`AlignItemsValue::FlexStart`]。 + FlexStart, + /// 同 [`AlignItemsValue::FlexEnd`]。 + FlexEnd, + /// 同 [`AlignItemsValue::Center`]。 + Center, + /// 同 [`AlignItemsValue::Baseline`]。 + Baseline, +} + +/// `gap` 值 +/// ([CSS Box Alignment §6](https://drafts.csswg.org/css-align-3/#gap-shorthand))。 +#[derive(Debug, Clone, Copy, PartialEq)] +pub enum GapValue { + /// 绝对长度(CSS px)。 + Length(f32), + /// 百分比(相对包含块对应轴尺寸)。 + Percent(f32), + /// `normal`(initial):退化为 0。 + Normal, + /// 视口单位;cascade 在 computed 阶段折算(同 [`SizeValue::Viewport`])。 + Viewport(f32, ViewportUnit), +} + +/// `grid-auto-flow` 值 +/// ([CSS Grid §7.7](https://drafts.csswg.org/css-grid/#grid-auto-flow-property))。 +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +pub enum GridAutoFlowValue { + /// `row`(initial)。 + Row, + /// `column`。 + Column, + /// `row dense`。 + RowDense, + /// `column dense`。 + ColumnDense, +} + +/// 一条 grid 轨道的轨道尺寸函数(简化版)。 +/// +/// 仅覆盖布局几何需要的子集:固定长度、百分比、弹性系数 `fr`、自适应 +/// `auto`、以及两段式 `minmax(a, b)`(a/b 各为长度/百分比/fr/auto)。 +#[derive(Debug, Clone, PartialEq)] +pub enum GridTrack { + /// 固定长度(CSS px)。 + Length(f32), + /// 百分比(相对网格容器尺寸)。 + Percent(f32), + /// 弹性系数 `fr`(参与剩余空间分配)。 + Fr(f32), + /// `auto`:内容驱动尺寸。 + Auto, + /// `minmax(a, b)`。 + MinMax(Box<GridTrack>, Box<GridTrack>), +} + +/// `grid-template-columns` / `grid-template-rows` 的轨道列表。 +#[derive(Debug, Clone, PartialEq, Default)] +pub struct GridTrackList { + /// 轨道序列;空表示未显式指定(用隐式轨道)。 + pub tracks: Vec<GridTrack>, +} + +/// `margin-*` 值 +/// ([CSS 2.1 §8.3](https://www.w3.org/TR/CSS21/box.html#margin-properties))。 +/// +/// 可为负;百分比由 layout 相对包含块宽度解析。 +#[derive(Debug, Clone, Copy, PartialEq)] +pub enum MarginValue { + /// 绝对长度(CSS px,可负)。 + Length(f32), + /// 百分比(以小数存储)。 + Percent(f32), + /// `auto`(initial;块级布局中解析为 0 或剩余空间)。 + Auto, + /// 视口单位;cascade 在 computed 阶段折算(同 [`SizeValue::Viewport`])。 + Viewport(f32, ViewportUnit), +} + +/// `padding-*` 值 +/// ([CSS 2.1 §8.4](https://www.w3.org/TR/CSS21/box.html#padding-properties))。 +/// +/// 不接受 auto,负值非法;百分比由 layout 相对包含块宽度解析。 +#[derive(Debug, Clone, Copy, PartialEq)] +pub enum PaddingValue { + /// 绝对长度(CSS px,非负)。 + Length(f32), + /// 百分比(以小数存储)。 + Percent(f32), + /// 视口单位;cascade 在 computed 阶段折算(同 [`SizeValue::Viewport`])。 + Viewport(f32, ViewportUnit), +} + +/// `border-*-width` 值 +/// ([CSS 2.1 §8.5.4](https://www.w3.org/TR/CSS21/box.html#border-width-properties))。 +/// +/// 关键字在解析期折算(thin 1px / medium 3px / thick 5px,与浏览器默认一致); +/// computed 阶段 style 为 none/hidden 时归零(cascade 模块)。 +#[derive(Debug, Clone, Copy, PartialEq)] +pub enum BorderWidthValue { + /// 绝对长度(CSS px,非负)。 + Length(f32), + /// `thin`(1px)。 + Thin, + /// `medium`(initial,3px)。 + Medium, + /// `thick`(5px)。 + Thick, +} + +impl BorderWidthValue { + /// 关键字/长度 → CSS px。 + #[must_use] + pub fn px(self) -> f32 { + match self { + BorderWidthValue::Length(px) => px, + BorderWidthValue::Thin => 1.0, + BorderWidthValue::Medium => 3.0, + BorderWidthValue::Thick => 5.0, + } + } +} + +/// `border-*-style` 关键字 +/// ([CSS 2.1 §8.5.3](https://www.w3.org/TR/CSS21/box.html#border-style-properties))。 +/// +/// 全部 10 个关键字都按规范接受;绘制端当前只区分 none/hidden 与可见边框 +/// (`solid` 语义),其余样式的绘制待 paint 层扩展。 +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +pub enum BorderStyle { + /// `none`(initial)。 + None, + /// `hidden`。 + Hidden, + /// `solid`。 + Solid, + /// `dashed`。 + Dashed, + /// `dotted`。 + Dotted, + /// `double`。 + Double, + /// `groove`。 + Groove, + /// `ridge`。 + Ridge, + /// `inset`。 + Inset, + /// `outset`。 + Outset, +} + +impl BorderStyle { + /// 是否画出可见边框(none/hidden 之外)。 + #[must_use] + pub fn visible(self) -> bool { + !matches!(self, BorderStyle::None | BorderStyle::Hidden) + } +} + +/// `border-*-color` 值 +/// ([CSS 2.1 §8.5.2](https://www.w3.org/TR/CSS21/box.html#border-color-properties))。 +/// +/// `currentcolor` 在 computed 阶段按本元素 `color` 解析(cascade 模块)。 +#[derive(Debug, Clone, Copy, PartialEq)] +pub enum BorderColorValue { + /// 具体颜色。 + Rgba(Rgba), + /// `currentcolor`。 + CurrentColor, +} + +/// 把声明值解析为 [`DeclaredValue`]:先识别 CSS-wide 关键字,再按属性语法解析。 +/// +/// `input` 已由调用方限定在本条声明的值范围内(分号 / 块尾之前)。 +/// 返回值连同该声明是否带 `!important`(CSS Cascade 5 §5.1);返回 `Err` +/// 表示整条声明无效。 +pub(crate) fn parse_declared_value( + property: PropertyId, + input: &mut Parser<'_>, +) -> Result<(DeclaredValue, bool), ()> { + if let Ok(keyword) = input.try_parse(parse_css_wide_keyword) { + let important = input.try_parse(parse_important).is_ok(); + // CSS-wide 关键字不允许再拼接其他值 + // (CSS Cascade 5:关键字是完整的 <declaration-value>)。 + if input.expect_exhausted().is_err() { + return Err(()); + } + return Ok((DeclaredValue::CssWide(keyword), important)); + } + let value = parse_property_value(property, input)?; + let important = input.try_parse(parse_important).is_ok(); + if input.expect_exhausted().is_err() { + return Err(()); + } + Ok((DeclaredValue::Typed(value), important)) +} + +/// 解析 CSS-wide 关键字(ASCII case-insensitive)。 +pub(crate) fn parse_css_wide_keyword(input: &mut Parser<'_>) -> Result<CssWideKeyword, ()> { + let Token::Ident(name) = input.next().map_err(|_| ())? else { + return Err(()); + }; + if name.eq_ignore_ascii_case("initial") { + Ok(CssWideKeyword::Initial) + } else if name.eq_ignore_ascii_case("inherit") { + Ok(CssWideKeyword::Inherit) + } else if name.eq_ignore_ascii_case("unset") { + Ok(CssWideKeyword::Unset) + } else if name.eq_ignore_ascii_case("revert") { + Ok(CssWideKeyword::Revert) + } else { + Err(()) + } +} + +/// 按属性语法解析值。 +fn parse_property_value(property: PropertyId, input: &mut Parser<'_>) -> Result<PropertyValue, ()> { + match property { + PropertyId::Display => parse_display(input).map(PropertyValue::Display), + PropertyId::TextAlign => parse_text_align(input).map(PropertyValue::TextAlign), + PropertyId::FontStyle => parse_font_style(input).map(PropertyValue::FontStyle), + PropertyId::Color => parse_color(input).map(PropertyValue::Color), + PropertyId::FontSize => parse_font_size(input).map(PropertyValue::FontSize), + PropertyId::FontWeight => parse_font_weight(input).map(PropertyValue::FontWeight), + PropertyId::FontFamily => parse_font_family(input).map(PropertyValue::FontFamily), + PropertyId::BackgroundColor => parse_color(input).map(PropertyValue::Color), + PropertyId::LineHeight => parse_line_height(input).map(PropertyValue::LineHeight), + PropertyId::WhiteSpace => parse_white_space(input).map(PropertyValue::WhiteSpace), + PropertyId::OverflowWrap => parse_overflow_wrap(input).map(PropertyValue::OverflowWrap), + PropertyId::WordBreak => parse_word_break(input).map(PropertyValue::WordBreak), + PropertyId::Width + | PropertyId::Height + | PropertyId::MinWidth + | PropertyId::MaxWidth + | PropertyId::MinHeight + | PropertyId::MaxHeight => parse_size(input).map(PropertyValue::Size), + PropertyId::BoxSizing => parse_box_sizing(input).map(PropertyValue::BoxSizing), + PropertyId::Overflow => parse_overflow(input).map(PropertyValue::Overflow), + PropertyId::FlexGrow => parse_flex_grow(input).map(PropertyValue::FlexGrow), + PropertyId::FlexBasis => parse_size(input).map(PropertyValue::FlexBasis), + PropertyId::Position => parse_position(input).map(PropertyValue::Position), + PropertyId::Top | PropertyId::Right | PropertyId::Bottom | PropertyId::Left => { + parse_inset(input).map(PropertyValue::Inset) + } + PropertyId::FlexDirection => parse_flex_direction(input).map(PropertyValue::FlexDirection), + PropertyId::FlexWrap => parse_flex_wrap(input).map(PropertyValue::FlexWrap), + PropertyId::FlexShrink => parse_flex_shrink(input).map(PropertyValue::FlexShrink), + PropertyId::AlignItems => parse_align_items(input).map(PropertyValue::AlignItems), + PropertyId::JustifyContent => { + parse_justify_content(input).map(PropertyValue::JustifyContent) + } + PropertyId::AlignSelf => parse_align_self(input).map(PropertyValue::AlignSelf), + PropertyId::GridTemplateColumns | PropertyId::GridTemplateRows => { + parse_grid_track_list(input).map(PropertyValue::GridTrack) + } + PropertyId::RowGap | PropertyId::ColumnGap => parse_gap(input).map(PropertyValue::Gap), + PropertyId::GridAutoFlow => parse_grid_auto_flow(input).map(PropertyValue::GridAutoFlow), + PropertyId::MarginTop + | PropertyId::MarginRight + | PropertyId::MarginBottom + | PropertyId::MarginLeft => parse_margin(input).map(PropertyValue::Margin), + PropertyId::PaddingTop + | PropertyId::PaddingRight + | PropertyId::PaddingBottom + | PropertyId::PaddingLeft => parse_padding(input).map(PropertyValue::Padding), + PropertyId::BorderTopWidth + | PropertyId::BorderRightWidth + | PropertyId::BorderBottomWidth + | PropertyId::BorderLeftWidth => parse_border_width(input).map(PropertyValue::BorderWidth), + PropertyId::BorderTopStyle + | PropertyId::BorderRightStyle + | PropertyId::BorderBottomStyle + | PropertyId::BorderLeftStyle => parse_border_style(input).map(PropertyValue::BorderStyle), + PropertyId::BorderTopColor + | PropertyId::BorderRightColor + | PropertyId::BorderBottomColor + | PropertyId::BorderLeftColor => parse_border_color(input).map(PropertyValue::BorderColor), + } +} + +/// `line-height`:normal | <number [0,∞]> | <length> | <percentage> +/// (CSS 2.1 §10.8.1)。 +fn parse_line_height(input: &mut Parser<'_>) -> Result<LineHeightValue, ()> { + match input.next().map_err(|_| ())? { + Token::Ident(name) if name.eq_ignore_ascii_case("normal") => Ok(LineHeightValue::Normal), + Token::Number { value, .. } => { + sanitize_number(*value).filter(|value| *value >= 0.0).map(LineHeightValue::Number).ok_or(()) + } + Token::Percentage { unit_value, .. } => { + sanitize_number(*unit_value).map(LineHeightValue::Percent).ok_or(()) + } + Token::Dimension { value, unit, .. } => { + if unit.eq_ignore_ascii_case("em") { + sanitize_number(*value).map(LineHeightValue::Em).ok_or(()) + } else { + length_to_px(*value, unit) + .map(LineHeightValue::Length) + .ok_or(()) + } + } + _ => Err(()), + } +} + +/// `white-space`:CSS Text 3 §3.1 的六个关键字。 +/// +/// Level 4 拆分的 `white-space-collapse` / `text-wrap-mode` 未实现;两个关键字 +/// 连写(如 `pre nowrap`)按非法值整条丢弃。 +fn parse_white_space(input: &mut Parser<'_>) -> Result<WhiteSpaceValue, ()> { + let Token::Ident(name) = input.next().map_err(|_| ())? else { + return Err(()); + }; + if name.eq_ignore_ascii_case("normal") { + Ok(WhiteSpaceValue::Normal) + } else if name.eq_ignore_ascii_case("nowrap") { + Ok(WhiteSpaceValue::Nowrap) + } else if name.eq_ignore_ascii_case("pre") { + Ok(WhiteSpaceValue::Pre) + } else if name.eq_ignore_ascii_case("pre-wrap") { + Ok(WhiteSpaceValue::PreWrap) + } else if name.eq_ignore_ascii_case("pre-line") { + Ok(WhiteSpaceValue::PreLine) + } else if name.eq_ignore_ascii_case("break-spaces") { + Ok(WhiteSpaceValue::BreakSpaces) + } else { + Err(()) + } +} + +/// `overflow-wrap`:normal | break-word | anywhere(CSS Text 3 §5.4)。 +fn parse_overflow_wrap(input: &mut Parser<'_>) -> Result<OverflowWrapValue, ()> { + let Token::Ident(name) = input.next().map_err(|_| ())? else { + return Err(()); + }; + if name.eq_ignore_ascii_case("normal") { + Ok(OverflowWrapValue::Normal) + } else if name.eq_ignore_ascii_case("break-word") { + Ok(OverflowWrapValue::BreakWord) + } else if name.eq_ignore_ascii_case("anywhere") { + Ok(OverflowWrapValue::Anywhere) + } else { + Err(()) + } +} + +/// `word-break`:normal | break-all | keep-all(CSS Text 3 §5.1)。 +fn parse_word_break(input: &mut Parser<'_>) -> Result<WordBreakValue, ()> { + let Token::Ident(name) = input.next().map_err(|_| ())? else { + return Err(()); + }; + if name.eq_ignore_ascii_case("normal") { + Ok(WordBreakValue::Normal) + } else if name.eq_ignore_ascii_case("break-all") { + Ok(WordBreakValue::BreakAll) + } else if name.eq_ignore_ascii_case("keep-all") { + Ok(WordBreakValue::KeepAll) + } else { + Err(()) + } +} + +/// `width` / `height`:<length> | <percentage> | auto,负值非法。 +fn parse_size(input: &mut Parser<'_>) -> Result<SizeValue, ()> { + match input.next().map_err(|_| ())? { + Token::Ident(name) if name.eq_ignore_ascii_case("auto") => Ok(SizeValue::Auto), + Token::Number { value: 0.0, .. } => Ok(SizeValue::Length(0.0)), + Token::Percentage { unit_value, .. } => { + sanitize_number(*unit_value).map(SizeValue::Percent).ok_or(()) + } + Token::Dimension { value, unit, .. } => { + if *value < 0.0 { + return Err(()); + } + if let Some((amount, unit)) = viewport_length(*value, unit) { + return sanitize_number(amount) + .map(|amount| SizeValue::Viewport(amount, unit)) + .ok_or(()); + } + length_to_px(*value, unit).map(SizeValue::Length).ok_or(()) + } + _ => Err(()), + } +} + +/// `box-sizing`:content-box | border-box(ASCII case-insensitive)。 +fn parse_box_sizing(input: &mut Parser<'_>) -> Result<BoxSizingValue, ()> { + match input.next().map_err(|_| ())? { + Token::Ident(name) if name.eq_ignore_ascii_case("content-box") => { + Ok(BoxSizingValue::ContentBox) + } + Token::Ident(name) if name.eq_ignore_ascii_case("border-box") => { + Ok(BoxSizingValue::BorderBox) + } + _ => Err(()), + } +} + +/// `overflow`:visible | hidden(偏差:auto/scroll/clip 暂按无效丢弃)。 +fn parse_overflow(input: &mut Parser<'_>) -> Result<OverflowValue, ()> { + match input.next().map_err(|_| ())? { + Token::Ident(name) if name.eq_ignore_ascii_case("visible") => Ok(OverflowValue::Visible), + Token::Ident(name) if name.eq_ignore_ascii_case("hidden") => Ok(OverflowValue::Hidden), + _ => Err(()), + } +} + +/// `flex-grow`:<number [0,∞]>(CSS Flexbox §7.1;负数非法)。 +fn parse_flex_grow(input: &mut Parser<'_>) -> Result<f32, ()> { + match input.next().map_err(|_| ())? { + Token::Number { value, .. } if *value >= 0.0 => sanitize_number(*value).ok_or(()), + _ => Err(()), + } +} + +/// `position`:static | relative | absolute | fixed(ASCII case-insensitive)。 +/// +/// `fixed` 在本布局层按 `absolute` 处理(相对视口定位的包含块由 layout 提供)。 +fn parse_position(input: &mut Parser<'_>) -> Result<PositionValue, ()> { + let Token::Ident(name) = input.next().map_err(|_| ())? else { + return Err(()); + }; + if name.eq_ignore_ascii_case("static") { + Ok(PositionValue::Static) + } else if name.eq_ignore_ascii_case("relative") { + Ok(PositionValue::Relative) + } else if name.eq_ignore_ascii_case("absolute") { + Ok(PositionValue::Absolute) + } else if name.eq_ignore_ascii_case("fixed") { + Ok(PositionValue::Fixed) + } else { + Err(()) + } +} + +/// `top` / `right` / `bottom` / `left`:<length> | <percentage> | auto。 +fn parse_inset(input: &mut Parser<'_>) -> Result<InsetValue, ()> { + match input.next().map_err(|_| ())? { + Token::Ident(name) if name.eq_ignore_ascii_case("auto") => Ok(InsetValue::Auto), + Token::Number { value: 0.0, .. } => Ok(InsetValue::Length(0.0)), + Token::Percentage { unit_value, .. } => { + sanitize_number(*unit_value).map(InsetValue::Percent).ok_or(()) + } + Token::Dimension { value, unit, .. } => { + if let Some((amount, unit)) = viewport_length(*value, unit) { + return sanitize_number(amount) + .map(|amount| InsetValue::Viewport(amount, unit)) + .ok_or(()); + } + length_to_px(*value, unit).map(InsetValue::Length).ok_or(()) + } + _ => Err(()), + } +} + +/// `flex-direction`:row | row-reverse | column | column-reverse。 +fn parse_flex_direction(input: &mut Parser<'_>) -> Result<FlexDirectionValue, ()> { + let Token::Ident(name) = input.next().map_err(|_| ())? else { + return Err(()); + }; + if name.eq_ignore_ascii_case("row") { + Ok(FlexDirectionValue::Row) + } else if name.eq_ignore_ascii_case("row-reverse") { + Ok(FlexDirectionValue::RowReverse) + } else if name.eq_ignore_ascii_case("column") { + Ok(FlexDirectionValue::Column) + } else if name.eq_ignore_ascii_case("column-reverse") { + Ok(FlexDirectionValue::ColumnReverse) + } else { + Err(()) + } +} + +/// `flex-wrap`:nowrap | wrap | wrap-reverse。 +fn parse_flex_wrap(input: &mut Parser<'_>) -> Result<FlexWrapValue, ()> { + let Token::Ident(name) = input.next().map_err(|_| ())? else { + return Err(()); + }; + if name.eq_ignore_ascii_case("nowrap") { + Ok(FlexWrapValue::NoWrap) + } else if name.eq_ignore_ascii_case("wrap") { + Ok(FlexWrapValue::Wrap) + } else if name.eq_ignore_ascii_case("wrap-reverse") { + Ok(FlexWrapValue::WrapReverse) + } else { + Err(()) + } +} + +/// `flex-shrink`:<number [0,∞]>(CSS Flexbox §7.2;负数非法)。 +fn parse_flex_shrink(input: &mut Parser<'_>) -> Result<f32, ()> { + match input.next().map_err(|_| ())? { + Token::Number { value, .. } if *value >= 0.0 => sanitize_number(*value).ok_or(()), + _ => Err(()), + } +} + +/// `align-items`:stretch | flex-start | flex-end | center | baseline +/// (兼容 `start` / `end` 取 flex-* 语义;CSS Box Alignment §7)。 +fn parse_align_items(input: &mut Parser<'_>) -> Result<AlignItemsValue, ()> { + let Token::Ident(name) = input.next().map_err(|_| ())? else { + return Err(()); + }; + if name.eq_ignore_ascii_case("stretch") { + Ok(AlignItemsValue::Stretch) + } else if name.eq_ignore_ascii_case("flex-start") || name.eq_ignore_ascii_case("start") { + Ok(AlignItemsValue::FlexStart) + } else if name.eq_ignore_ascii_case("flex-end") || name.eq_ignore_ascii_case("end") { + Ok(AlignItemsValue::FlexEnd) + } else if name.eq_ignore_ascii_case("center") { + Ok(AlignItemsValue::Center) + } else if name.eq_ignore_ascii_case("baseline") { + Ok(AlignItemsValue::Baseline) + } else { + Err(()) + } +} + +/// `justify-content`:flex-start | flex-end | center | space-between | +/// space-around | space-evenly(兼容 `start` / `end`)。 +fn parse_justify_content(input: &mut Parser<'_>) -> Result<JustifyContentValue, ()> { + let Token::Ident(name) = input.next().map_err(|_| ())? else { + return Err(()); + }; + if name.eq_ignore_ascii_case("flex-start") || name.eq_ignore_ascii_case("start") { + Ok(JustifyContentValue::FlexStart) + } else if name.eq_ignore_ascii_case("flex-end") || name.eq_ignore_ascii_case("end") { + Ok(JustifyContentValue::FlexEnd) + } else if name.eq_ignore_ascii_case("center") { + Ok(JustifyContentValue::Center) + } else if name.eq_ignore_ascii_case("space-between") { + Ok(JustifyContentValue::SpaceBetween) + } else if name.eq_ignore_ascii_case("space-around") { + Ok(JustifyContentValue::SpaceAround) + } else if name.eq_ignore_ascii_case("space-evenly") { + Ok(JustifyContentValue::SpaceEvenly) + } else { + Err(()) + } +} + +/// `align-self`:auto | stretch | flex-start | flex-end | center | baseline。 +fn parse_align_self(input: &mut Parser<'_>) -> Result<AlignSelfValue, ()> { + let Token::Ident(name) = input.next().map_err(|_| ())? else { + return Err(()); + }; + if name.eq_ignore_ascii_case("auto") { + Ok(AlignSelfValue::Auto) + } else if name.eq_ignore_ascii_case("stretch") { + Ok(AlignSelfValue::Stretch) + } else if name.eq_ignore_ascii_case("flex-start") || name.eq_ignore_ascii_case("start") { + Ok(AlignSelfValue::FlexStart) + } else if name.eq_ignore_ascii_case("flex-end") || name.eq_ignore_ascii_case("end") { + Ok(AlignSelfValue::FlexEnd) + } else if name.eq_ignore_ascii_case("center") { + Ok(AlignSelfValue::Center) + } else if name.eq_ignore_ascii_case("baseline") { + Ok(AlignSelfValue::Baseline) + } else { + Err(()) + } +} + +/// `row-gap` / `column-gap`:<length> | <percentage> | normal +/// (CSS Box Alignment §6;`auto` 不是合法 gap 值,按无效声明丢弃)。 +fn parse_gap(input: &mut Parser<'_>) -> Result<GapValue, ()> { + match input.next().map_err(|_| ())? { + Token::Ident(name) if name.eq_ignore_ascii_case("normal") => Ok(GapValue::Normal), + Token::Number { value: 0.0, .. } => Ok(GapValue::Length(0.0)), + Token::Percentage { unit_value, .. } => { + sanitize_number(*unit_value).map(GapValue::Percent).ok_or(()) + } + Token::Dimension { value, unit, .. } => { + if let Some((amount, unit)) = viewport_length(*value, unit) { + return sanitize_number(amount) + .map(|amount| GapValue::Viewport(amount, unit)) + .ok_or(()); + } + length_to_px(*value, unit).map(GapValue::Length).ok_or(()) + } + _ => Err(()), + } +} + +/// `grid-auto-flow`:row | column | row dense | column dense。 +fn parse_grid_auto_flow(input: &mut Parser<'_>) -> Result<GridAutoFlowValue, ()> { + let first = match input.next().map_err(|_| ())? { + Token::Ident(name) if name.eq_ignore_ascii_case("row") => GridAutoFlowValue::Row, + Token::Ident(name) if name.eq_ignore_ascii_case("column") => GridAutoFlowValue::Column, + _ => return Err(()), + }; + // 可选 `dense` 后缀 + if input + .try_parse(|i| i.expect_ident_matching("dense").map(|_| ())) + .is_ok() + { + if input.expect_exhausted().is_err() { + return Err(()); + } + return Ok(match first { + GridAutoFlowValue::Row => GridAutoFlowValue::RowDense, + GridAutoFlowValue::Column => GridAutoFlowValue::ColumnDense, + _ => unreachable!(), + }); + } + if input.expect_exhausted().is_err() { + return Err(()); + } + Ok(first) +} + +/// `grid-template-columns` / `grid-template-rows` 的轨道列表解析 +/// (CSS Grid §7.2/§7.3;空白分隔轨道,支持 `minmax()`)。 +fn parse_grid_track_list(input: &mut Parser<'_>) -> Result<GridTrackList, ()> { + let mut tracks = Vec::new(); + let mut first = true; + while !input.is_exhausted() { + if !first && input.try_parse(|i| i.expect_whitespace()).is_err() { + return Err(()); + } + first = false; + tracks.push(parse_grid_track(input)?); + } + Ok(GridTrackList { tracks }) +} + +/// 单条 grid 轨道尺寸函数。 +fn parse_grid_track(input: &mut Parser<'_>) -> Result<GridTrack, ()> { + if input + .try_parse(|i| i.expect_function_matching("minmax").map(|_| ())) + .is_ok() + { + return input + .parse_nested_block(|i| { + let a = + parse_grid_track_size(i).map_err(|_| ParseError::<()>::unexpected_token())?; + i.expect_comma() + .map_err(|_| ParseError::<()>::unexpected_token())?; + let b = + parse_grid_track_size(i).map_err(|_| ParseError::<()>::unexpected_token())?; + i.expect_exhausted() + .map_err(|_| ParseError::<()>::unexpected_token())?; + Ok(GridTrack::MinMax(Box::new(a), Box::new(b))) + }) + .map_err(|_| ()); + } + parse_grid_track_size(input) +} + +/// 单段轨道尺寸(`minmax` 内的一段):<length> | <percentage> | <flex> | auto。 +fn parse_grid_track_size(input: &mut Parser<'_>) -> Result<GridTrack, ()> { + match input.next().map_err(|_| ())? { + Token::Ident(name) if name.eq_ignore_ascii_case("auto") => Ok(GridTrack::Auto), + Token::Number { value: 0.0, .. } => Ok(GridTrack::Length(0.0)), + Token::Percentage { unit_value, .. } => { + sanitize_number(*unit_value).map(GridTrack::Percent).ok_or(()) + } + Token::Dimension { value, unit, .. } => { + if unit.eq_ignore_ascii_case("fr") { + sanitize_number(*value).map(GridTrack::Fr).ok_or(()) + } else { + length_to_px(*value, unit).map(GridTrack::Length).ok_or(()) + } + } + _ => Err(()), + } +} + +/// `margin-*`:<length> | <percentage> | auto,长度可负。 +fn parse_margin(input: &mut Parser<'_>) -> Result<MarginValue, ()> { + match input.next().map_err(|_| ())? { + Token::Ident(name) if name.eq_ignore_ascii_case("auto") => Ok(MarginValue::Auto), + Token::Number { value: 0.0, .. } => Ok(MarginValue::Length(0.0)), + Token::Percentage { unit_value, .. } => { + sanitize_number(*unit_value).map(MarginValue::Percent).ok_or(()) + } + Token::Dimension { value, unit, .. } => { + if let Some((amount, unit)) = viewport_length(*value, unit) { + return sanitize_number(amount) + .map(|amount| MarginValue::Viewport(amount, unit)) + .ok_or(()); + } + length_to_px(*value, unit) + .map(MarginValue::Length) + .ok_or(()) + } + _ => Err(()), + } +} + +/// `padding-*`:<length> | <percentage>,不接受 auto、负值非法。 +fn parse_padding(input: &mut Parser<'_>) -> Result<PaddingValue, ()> { + match input.next().map_err(|_| ())? { + Token::Number { value: 0.0, .. } => Ok(PaddingValue::Length(0.0)), + Token::Percentage { unit_value, .. } => { + sanitize_number(*unit_value).map(PaddingValue::Percent).ok_or(()) + } + Token::Dimension { value, unit, .. } => { + if *value < 0.0 { + return Err(()); + } + if let Some((amount, unit)) = viewport_length(*value, unit) { + return sanitize_number(amount) + .map(|amount| PaddingValue::Viewport(amount, unit)) + .ok_or(()); + } + length_to_px(*value, unit) + .map(PaddingValue::Length) + .ok_or(()) + } + _ => Err(()), + } +} + +/// `border-*-width`:<line-width>(<length [0,∞]> | thin | medium | thick)。 +fn parse_border_width(input: &mut Parser<'_>) -> Result<BorderWidthValue, ()> { + match input.next().map_err(|_| ())? { + Token::Ident(name) if name.eq_ignore_ascii_case("thin") => Ok(BorderWidthValue::Thin), + Token::Ident(name) if name.eq_ignore_ascii_case("medium") => Ok(BorderWidthValue::Medium), + Token::Ident(name) if name.eq_ignore_ascii_case("thick") => Ok(BorderWidthValue::Thick), + Token::Number { value: 0.0, .. } => Ok(BorderWidthValue::Length(0.0)), + Token::Dimension { value, unit, .. } => { + if *value < 0.0 { + return Err(()); + } + length_to_px(*value, unit) + .map(BorderWidthValue::Length) + .ok_or(()) + } + _ => Err(()), + } +} + +/// `border-*-style`:<line-style>(10 个关键字)。 +fn parse_border_style(input: &mut Parser<'_>) -> Result<BorderStyle, ()> { + let Token::Ident(name) = input.next().map_err(|_| ())? else { + return Err(()); + }; + const STYLES: [(&str, BorderStyle); 10] = [ + ("none", BorderStyle::None), + ("hidden", BorderStyle::Hidden), + ("solid", BorderStyle::Solid), + ("dashed", BorderStyle::Dashed), + ("dotted", BorderStyle::Dotted), + ("double", BorderStyle::Double), + ("groove", BorderStyle::Groove), + ("ridge", BorderStyle::Ridge), + ("inset", BorderStyle::Inset), + ("outset", BorderStyle::Outset), + ]; + STYLES + .into_iter() + .find(|(keyword, _)| keyword.eq_ignore_ascii_case(name)) + .map(|(_, style)| style) + .ok_or(()) +} + +/// `border-*-color`:<color> | currentcolor。 +fn parse_border_color(input: &mut Parser<'_>) -> Result<BorderColorValue, ()> { + if let Ok(rgba) = input.try_parse(parse_color) { + return Ok(BorderColorValue::Rgba(rgba)); + } + match input.next().map_err(|_| ())? { + Token::Ident(name) if name.eq_ignore_ascii_case("currentcolor") => { + Ok(BorderColorValue::CurrentColor) + } + _ => Err(()), + } +} + +/// 以下为简写展开(parser 模块)复用的单值解析入口。 +pub(crate) fn parse_margin_value(input: &mut Parser<'_>) -> Result<MarginValue, ()> { + parse_margin(input) +} + +pub(crate) fn parse_padding_value(input: &mut Parser<'_>) -> Result<PaddingValue, ()> { + parse_padding(input) +} + +pub(crate) fn parse_border_width_value(input: &mut Parser<'_>) -> Result<BorderWidthValue, ()> { + parse_border_width(input) +} + +pub(crate) fn parse_border_style_value(input: &mut Parser<'_>) -> Result<BorderStyle, ()> { + parse_border_style(input) +} + +pub(crate) fn parse_border_color_value(input: &mut Parser<'_>) -> Result<BorderColorValue, ()> { + parse_border_color(input) +} + +/// `inset` 简写复用单值解析入口。 +pub(crate) fn parse_inset_value(input: &mut Parser<'_>) -> Result<InsetValue, ()> { + parse_inset(input) +} + +/// `gap` 简写复用单值解析入口。 +pub(crate) fn parse_gap_value(input: &mut Parser<'_>) -> Result<GapValue, ()> { + parse_gap(input) +} + +fn parse_display(input: &mut Parser<'_>) -> Result<DisplayValue, ()> { + let Token::Ident(name) = input.next().map_err(|_| ())? else { + return Err(()); + }; + if name.eq_ignore_ascii_case("inline") { + return Ok(DisplayValue::Inline); + } + if name.eq_ignore_ascii_case("block") { + return Ok(DisplayValue::Block); + } + if name.eq_ignore_ascii_case("list-item") { + return Ok(DisplayValue::ListItem); + } + if name.eq_ignore_ascii_case("inline-block") { + return Ok(DisplayValue::InlineBlock); + } + if name.eq_ignore_ascii_case("flow-root") { + return Ok(DisplayValue::FlowRoot); + } + if name.eq_ignore_ascii_case("flex") { + return Ok(DisplayValue::Flex); + } + if name.eq_ignore_ascii_case("inline-flex") { + return Ok(DisplayValue::InlineFlex); + } + if name.eq_ignore_ascii_case("grid") { + return Ok(DisplayValue::Grid); + } + if name.eq_ignore_ascii_case("inline-grid") { + return Ok(DisplayValue::InlineGrid); + } + if name.eq_ignore_ascii_case("table") { + return Ok(DisplayValue::Table); + } + if name.eq_ignore_ascii_case("inline-table") { + return Ok(DisplayValue::InlineTable); + } + if name.eq_ignore_ascii_case("contents") { + return Ok(DisplayValue::Contents); + } + if name.eq_ignore_ascii_case("none") { + return Ok(DisplayValue::None); + } + const INTERNAL: [(&str, &str); 8] = [ + ("table-row-group", "table-row-group"), + ("table-header-group", "table-header-group"), + ("table-footer-group", "table-footer-group"), + ("table-row", "table-row"), + ("table-cell", "table-cell"), + ("table-column-group", "table-column-group"), + ("table-column", "table-column"), + ("table-caption", "table-caption"), + ]; + for (keyword, label) in INTERNAL { + if name.eq_ignore_ascii_case(keyword) { + return Ok(DisplayValue::TableInternal(label)); + } + } + Err(()) +} + +fn parse_text_align(input: &mut Parser<'_>) -> Result<TextAlignValue, ()> { + let Token::Ident(name) = input.next().map_err(|_| ())? else { + return Err(()); + }; + if name.eq_ignore_ascii_case("start") { + return Ok(TextAlignValue::Start); + } + if name.eq_ignore_ascii_case("end") { + return Ok(TextAlignValue::End); + } + if name.eq_ignore_ascii_case("left") { + return Ok(TextAlignValue::Left); + } + if name.eq_ignore_ascii_case("right") { + return Ok(TextAlignValue::Right); + } + if name.eq_ignore_ascii_case("center") { + return Ok(TextAlignValue::Center); + } + if name.eq_ignore_ascii_case("justify") { + return Ok(TextAlignValue::Justify); + } + if name.eq_ignore_ascii_case("match-parent") { + return Ok(TextAlignValue::MatchParent); + } + if name.eq_ignore_ascii_case("justify-all") { + return Ok(TextAlignValue::JustifyAll); + } + Err(()) +} + +fn parse_font_style(input: &mut Parser<'_>) -> Result<FontStyleValue, ()> { + let Token::Ident(name) = input.next().map_err(|_| ())? else { + return Err(()); + }; + if name.eq_ignore_ascii_case("normal") { + return Ok(FontStyleValue::Normal); + } + if name.eq_ignore_ascii_case("italic") { + return Ok(FontStyleValue::Italic); + } + if name.eq_ignore_ascii_case("oblique") { + // oblique [ <angle> | none ]? + let angle = input.try_parse(parse_angle).ok(); + if angle.is_none() + && (input.try_parse(|i| i.expect_ident_matching("none").map_err(|_| ()))).is_err() + && input.expect_exhausted().is_err() + { + return Err(()); + } + return Ok(FontStyleValue::Oblique(angle)); + } + Err(()) +} + +/// 解析角度并折算为角度制。 +fn parse_angle(input: &mut Parser<'_>) -> Result<f32, ()> { + match input.next().map_err(|_| ())? { + Token::Dimension { value, unit, .. } => { + if unit.eq_ignore_ascii_case("deg") { + Ok(*value) + } else if unit.eq_ignore_ascii_case("grad") { + Ok(*value * 360.0 / 400.0) + } else if unit.eq_ignore_ascii_case("rad") { + Ok(value.to_degrees()) + } else if unit.eq_ignore_ascii_case("turn") { + Ok(*value * 360.0) + } else { + Err(()) + } + } + _ => Err(()), + } +} + +/// 长度类数值的卫生上限(CSS px)。 +/// +/// 不可信输入里的巨数 token(`1e40px` 在 f32 中溢出为 `inf`)与相对单位 +/// 乘积在解析/计算出口被钳到该量级(与 Chromium 的传统长度上限同量级; +/// 超出按 UA clamp 记偏差),`inf`/`NaN` 直接拒绝——非有限值一旦进入 +/// 布局会沿几何扩散污染整页坐标。 +pub const MAX_CSS_LENGTH: f32 = 1.0e7; + +/// 解析出口的数值卫生:非有限值拒绝(整条声明按无效处理),有限值 clamp +/// 到 `[-MAX_CSS_LENGTH, MAX_CSS_LENGTH]`。 +pub(crate) fn sanitize_number(value: f32) -> Option<f32> { + value + .is_finite() + .then(|| value.clamp(-MAX_CSS_LENGTH, MAX_CSS_LENGTH)) +} + +/// `<length-percentage>` 折算为 px;返回 `None` 表示该单位不受支持或数值 +/// 非有限。 +fn length_to_px(value: f32, unit: &str) -> Option<f32> { + let px = if unit.eq_ignore_ascii_case("px") { + Some(value) + } else if unit.eq_ignore_ascii_case("pt") { + // 1pt = 1/72in,1in = 96px(CSS Values 4 绝对长度定义) + Some(value * 96.0 / 72.0) + } else if unit.eq_ignore_ascii_case("pc") { + Some(value * 16.0) + } else if unit.eq_ignore_ascii_case("in") { + Some(value * 96.0) + } else if unit.eq_ignore_ascii_case("cm") { + Some(value * 96.0 / 2.54) + } else if unit.eq_ignore_ascii_case("mm") { + Some(value * 96.0 / 25.4) + } else if unit.eq_ignore_ascii_case("q") { + Some(value * 96.0 / 101.6) + } else { + None + }?; + sanitize_number(px) +} + +/// 视口单位([CSS Values 4 §6.2](https://drafts.csswg.org/css-values-4/#viewport-relative-units)): +/// 相对初始包含块(视口)对应边的小数百分比基数。 +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +pub enum ViewportUnit { + /// `vw`:视口宽的 1%。 + Vw, + /// `vh`:视口高的 1%。 + Vh, + /// `vmin`:视口短边的 1%。 + Vmin, + /// `vmax`:视口长边的 1%。 + Vmax, +} + +/// 维度 token 的单位是否为视口单位;是则返回 `(数量, 单位)`。 +fn viewport_length(value: f32, unit: &str) -> Option<(f32, ViewportUnit)> { + let unit = if unit.eq_ignore_ascii_case("vw") { + ViewportUnit::Vw + } else if unit.eq_ignore_ascii_case("vh") { + ViewportUnit::Vh + } else if unit.eq_ignore_ascii_case("vmin") { + ViewportUnit::Vmin + } else if unit.eq_ignore_ascii_case("vmax") { + ViewportUnit::Vmax + } else { + return None; + }; + Some((value, unit)) +} + +fn parse_font_size(input: &mut Parser<'_>) -> Result<FontSizeValue, ()> { + match input.next().map_err(|_| ())? { + // <length> 为 0 时单位可省略(CSS Values 4) + Token::Number { value: 0.0, .. } => Ok(FontSizeValue::Px(0.0)), + Token::Number { .. } => Err(()), + Token::Percentage { unit_value, .. } => { + sanitize_number(*unit_value).map(FontSizeValue::Percent).ok_or(()) + } + Token::Dimension { value, unit, .. } => { + if unit.eq_ignore_ascii_case("em") { + sanitize_number(*value).map(FontSizeValue::Em).ok_or(()) + } else { + length_to_px(*value, unit).map(FontSizeValue::Px).ok_or(()) + } + } + Token::Ident(name) => { + if name.eq_ignore_ascii_case("xx-small") { + Ok(FontSizeValue::Absolute(AbsoluteSize::XxSmall)) + } else if name.eq_ignore_ascii_case("x-small") { + Ok(FontSizeValue::Absolute(AbsoluteSize::XSmall)) + } else if name.eq_ignore_ascii_case("small") { + Ok(FontSizeValue::Absolute(AbsoluteSize::Small)) + } else if name.eq_ignore_ascii_case("medium") { + Ok(FontSizeValue::Absolute(AbsoluteSize::Medium)) + } else if name.eq_ignore_ascii_case("large") { + Ok(FontSizeValue::Absolute(AbsoluteSize::Large)) + } else if name.eq_ignore_ascii_case("x-large") { + Ok(FontSizeValue::Absolute(AbsoluteSize::XLarge)) + } else if name.eq_ignore_ascii_case("xx-large") { + Ok(FontSizeValue::Absolute(AbsoluteSize::XxLarge)) + } else if name.eq_ignore_ascii_case("xxx-large") { + Ok(FontSizeValue::Absolute(AbsoluteSize::XxxLarge)) + } else if name.eq_ignore_ascii_case("larger") { + Ok(FontSizeValue::Larger) + } else if name.eq_ignore_ascii_case("smaller") { + Ok(FontSizeValue::Smaller) + } else { + Err(()) + } + } + _ => Err(()), + } +} + +fn parse_font_weight(input: &mut Parser<'_>) -> Result<FontWeightValue, ()> { + match input.next().map_err(|_| ())? { + Token::Number { value, .. } => { + // CSS Fonts 4:<number [1,1000]>,越界无效 + if (1.0..=1000.0).contains(value) { + Ok(FontWeightValue::Weight(*value)) + } else { + Err(()) + } + } + Token::Ident(name) => { + if name.eq_ignore_ascii_case("normal") { + Ok(FontWeightValue::Weight(400.0)) + } else if name.eq_ignore_ascii_case("bold") { + Ok(FontWeightValue::Weight(700.0)) + } else if name.eq_ignore_ascii_case("bolder") { + Ok(FontWeightValue::Bolder) + } else if name.eq_ignore_ascii_case("lighter") { + Ok(FontWeightValue::Lighter) + } else { + Err(()) + } + } + _ => Err(()), + } +} + +fn parse_font_family(input: &mut Parser<'_>) -> Result<Vec<FontFamilyValue>, ()> { + let mut families = Vec::new(); + loop { + families.push(parse_family_item(input)?); + // 逗号 → 还有下一项;`!`(!important 前缀)、其他终止符或 EOF → + // 族名列表结束,后续交给调用方(parse_important / 耗尽校验)。 + // 注意逗号是独立的 Token::Comma,不是 Delim。 + if input.try_parse(|i| i.expect_comma()).is_err() { + break; + } + } + Ok(families) +} + +/// 解析一个字体族名:`<string>` 或一串 `<custom-ident>`(以空白分隔)。 +/// +/// 遇到终止符(逗号、`!`、EOF)即停止且不消费,留给调用方——它们经 +/// `try_parse` 的 `Err` 返回,位置已还原;其他无法归入族名语法的 token +/// (数字、不匹配的括号等)照常消费并由 [`family_from_tokens`] 判为无效。 +fn parse_family_item(input: &mut Parser<'_>) -> Result<FontFamilyValue, ()> { + let mut tokens = Vec::new(); + loop { + let peeked = input.try_parse(|i| match i.next_including_whitespace() { + Ok(Token::Comma) | Ok(Token::Delim('!')) => Err(()), + Ok(token) => Ok(token.clone()), + Err(_) => Err(()), + }); + match peeked { + Ok(token) => tokens.push(token), + Err(()) => break, + } + } + family_from_tokens(&tokens) +} + +/// 把族名的 token 序列归一化为 [`FontFamilyValue`]:去首尾空白、中部空白 +/// 折叠为单个空格;无引号的单词族名映射 generic。 +fn family_from_tokens(tokens: &[Token<'_>]) -> Result<FontFamilyValue, ()> { + let mut parts: Vec<String> = Vec::new(); + let mut current: Option<String> = None; + let mut quoted = false; + for token in tokens { + match token { + Token::WhiteSpace(_) => { + if let Some(word) = current.take() { + parts.push(word); + } + } + Token::Ident(name) => { + current.get_or_insert_with(String::new).push_str(name); + } + Token::QuotedString(text) => { + if current.is_some() || !parts.is_empty() { + // 字符串只能单独成族名(CSS Fonts 4 §2.3 语法) + return Err(()); + } + quoted = true; + parts.push(text.to_string()); + } + _ => return Err(()), + } + } + if let Some(word) = current.take() { + parts.push(word); + } + + if parts.is_empty() { + return Err(()); + } + // 带引号的 "serif" 是名为 serif 的普通族名,不映射 generic + if parts.len() == 1 + && !quoted + && let Some(generic) = generic_family(&parts[0]) + { + return Ok(FontFamilyValue::Generic(generic)); + } + Ok(FontFamilyValue::Family(parts.join(" "))) +} + +/// `font` 简写值解析并展开为 longhand(CSS Fonts 4 §3.3)。 +/// +/// 语法:`[ <'font-style'> || <font-variant-css2> || <'font-weight'> || +/// <font-width-css3> ]? <'font-size'> [ / <'line-height'> ]? <'font-family'>#`—— +/// `||` 成分任意顺序、每项至多一次;缺省成分按简写语义重置为 initial。 +/// 偏差:`font-variant-css2`(`small-caps`)与 `<font-width-css3>`(宽度 +/// 关键字/百分比)无对应 longhand,按语法接受后丢弃;系统字体关键字 +/// (`caption` 等)整条无效。 +pub(crate) fn parse_font_shorthand( + input: &mut Parser<'_>, +) -> Result<Vec<(PropertyId, PropertyValue)>, ()> { + if is_system_family_name(input) { + return Err(()); + } + let mut style: Option<FontStyleValue> = None; + let mut weight: Option<FontWeightValue> = None; + let mut small_caps_seen = false; + let mut width_seen = false; + // `normal` 可出现在 style / variant / weight / width 四个槽位,统一计数 + // (各槽初值均为 normal,无需区分归属)。 + let mut normals = 0usize; + loop { + if normals < 4 && try_parse_ident(input, "normal") { + normals += 1; + continue; + } + if style.is_none() + && let Ok(value) = input.try_parse(parse_font_style_shorthand) + { + style = Some(value); + continue; + } + if weight.is_none() + && let Ok(value) = input.try_parse(parse_font_weight) + { + weight = Some(value); + continue; + } + if !small_caps_seen && try_parse_ident(input, "small-caps") { + small_caps_seen = true; + continue; + } + if !width_seen && try_parse_font_width(input) { + width_seen = true; + continue; + } + break; + } + + let size = parse_font_size(input)?; + let line_height = if input.try_parse(|i| i.expect_delim('/')).is_ok() { + Some(parse_line_height(input)?) + } else { + None + }; + let families = parse_font_family(input)?; + + Ok(vec![ + ( + PropertyId::FontStyle, + PropertyValue::FontStyle(style.unwrap_or(FontStyleValue::Normal)), + ), + ( + PropertyId::FontWeight, + PropertyValue::FontWeight(weight.unwrap_or(FontWeightValue::Weight(400.0))), + ), + (PropertyId::FontSize, PropertyValue::FontSize(size)), + ( + PropertyId::LineHeight, + PropertyValue::LineHeight(line_height.unwrap_or(LineHeightValue::Normal)), + ), + (PropertyId::FontFamily, PropertyValue::FontFamily(families)), + ]) +} + +/// 简写前缀里的 `<font-style>`:`italic | oblique [ <angle> | none ]?`。 +/// 与 longhand [`parse_font_style`] 的差别:裸 `oblique` 合法——简写中 +/// 其后还有 size 等成分,不能要求耗尽。 +fn parse_font_style_shorthand(input: &mut Parser<'_>) -> Result<FontStyleValue, ()> { + let Token::Ident(name) = input.next().map_err(|_| ())? else { + return Err(()); + }; + if name.eq_ignore_ascii_case("italic") { + return Ok(FontStyleValue::Italic); + } + if name.eq_ignore_ascii_case("oblique") { + let angle = input.try_parse(parse_angle).ok(); + if angle.is_none() + && input + .try_parse(|i| i.expect_ident_matching("none").map_err(|_| ())) + .is_ok() + { + return Ok(FontStyleValue::Oblique(None)); + } + return Ok(FontStyleValue::Oblique(angle)); + } + Err(()) +} + +/// `font` 简写的系统字体关键字(CSS Fonts 4 §3.3 `<system-family-name>`): +/// 依赖 UA 系统设置且要求重置全部子属性,本层不支持。 +fn is_system_family_name(input: &mut Parser<'_>) -> bool { + const SYSTEM: [&str; 6] = [ + "caption", + "icon", + "menu", + "message-box", + "small-caption", + "status-bar", + ]; + input + .try_parse(|i| match i.next() { + Ok(Token::Ident(name)) if SYSTEM.iter().any(|k| name.eq_ignore_ascii_case(k)) => Ok(()), + _ => Err(()), + }) + .is_ok() +} + +/// 尝试消费一个指定关键字(ASCII case-insensitive),命中则消费并返回真。 +fn try_parse_ident(input: &mut Parser<'_>, expected: &str) -> bool { + input + .try_parse(|i| match i.next() { + Ok(Token::Ident(name)) if name.eq_ignore_ascii_case(expected) => Ok(()), + _ => Err(()), + }) + .is_ok() +} + +/// `<font-width-css3>`:宽度关键字或非负百分比。本层无 font-stretch +/// longhand,按语法接受后丢弃(返回是否命中)。 +fn try_parse_font_width(input: &mut Parser<'_>) -> bool { + const KEYWORDS: [&str; 8] = [ + "ultra-condensed", + "extra-condensed", + "condensed", + "semi-condensed", + "semi-expanded", + "expanded", + "extra-expanded", + "ultra-expanded", + ]; + input + .try_parse(|i| match i.next() { + Ok(Token::Ident(name)) if KEYWORDS.iter().any(|k| name.eq_ignore_ascii_case(k)) => { + Ok(()) + } + Ok(Token::Percentage { unit_value, .. }) if *unit_value >= 0.0 => Ok(()), + _ => Err(()), + }) + .is_ok() +} + +/// 无引号的 generic 族关键字 +/// (CSS Fonts 4 §2.3:serif、sans-serif、cursive、fantasy、monospace、 +/// system-ui、math、emoji、fangsong、ui-serif、ui-sans-serif、ui-monospace、 +/// ui-rounded)。 +fn generic_family(name: &str) -> Option<&'static str> { + const GENERICS: [&str; 13] = [ + "serif", + "sans-serif", + "cursive", + "fantasy", + "monospace", + "system-ui", + "math", + "emoji", + "fangsong", + "ui-serif", + "ui-sans-serif", + "ui-monospace", + "ui-rounded", + ]; + GENERICS + .into_iter() + .find(|generic| generic.eq_ignore_ascii_case(name)) +} + +/// 解析 `<color>`([CSS Color 4 §5](https://drafts.csswg.org/css-color-4/#color-syntax)): +/// hex、`rgb()` / `rgba()`、`hsl()` / `hsla()`(现代与 legacy 逗号语法)、 +/// 命名色与 `transparent`。 +pub(crate) fn parse_color(input: &mut Parser<'_>) -> Result<Rgba, ()> { + let token = input.next().map_err(|_| ())?; + match token { + // `#fff` 这类合法标识符形式的 hash 会词法为 IDHash,与 Hash 同义 + Token::Hash(hash) | Token::IDHash(hash) => parse_hex(hash), + Token::Ident(name) => { + if name.eq_ignore_ascii_case("transparent") { + Ok(Rgba::transparent()) + } else if name.eq_ignore_ascii_case("currentcolor") { + // 依赖元素上下文,本轮不支持(见模块文档偏差) + Err(()) + } else { + named_color(name).ok_or(()) + } + } + Token::Function(name) => { + if name.eq_ignore_ascii_case("rgb") || name.eq_ignore_ascii_case("rgba") { + input + .parse_nested_block(|input| { + parse_rgb_arguments(input).map_err(|_| ParseError::<()>::unexpected_token()) + }) + .map_err(|_| ()) + } else if name.eq_ignore_ascii_case("hsl") || name.eq_ignore_ascii_case("hsla") { + input + .parse_nested_block(|input| { + parse_hsl_arguments(input).map_err(|_| ParseError::<()>::unexpected_token()) + }) + .map_err(|_| ()) + } else { + Err(()) + } + } + _ => Err(()), + } +} + +/// CSS Color 4 §6.1 命名色表(148 项,由规范表格生成)。 +const NAMED_COLORS: [(&str, u8, u8, u8); 148] = [ + ("aliceblue", 0xf0, 0xf8, 0xff), + ("antiquewhite", 0xfa, 0xeb, 0xd7), + ("aqua", 0x00, 0xff, 0xff), + ("aquamarine", 0x7f, 0xff, 0xd4), + ("azure", 0xf0, 0xff, 0xff), + ("beige", 0xf5, 0xf5, 0xdc), + ("bisque", 0xff, 0xe4, 0xc4), + ("black", 0x00, 0x00, 0x00), + ("blanchedalmond", 0xff, 0xeb, 0xcd), + ("blue", 0x00, 0x00, 0xff), + ("blueviolet", 0x8a, 0x2b, 0xe2), + ("brown", 0xa5, 0x2a, 0x2a), + ("burlywood", 0xde, 0xb8, 0x87), + ("cadetblue", 0x5f, 0x9e, 0xa0), + ("chartreuse", 0x7c, 0xfc, 0x00), + ("chocolate", 0xd2, 0x69, 0x1e), + ("coral", 0xff, 0x7f, 0x50), + ("cornflowerblue", 0x64, 0x95, 0xed), + ("cornsilk", 0xff, 0xf8, 0xdc), + ("crimson", 0xdc, 0x14, 0x3c), + ("cyan", 0x00, 0xff, 0xff), + ("darkblue", 0x00, 0x00, 0x8b), + ("darkcyan", 0x00, 0x8b, 0x8b), + ("darkgoldenrod", 0xb8, 0x86, 0x0b), + ("darkgray", 0xa9, 0xa9, 0xa9), + ("darkgreen", 0x00, 0x80, 0x00), + ("darkgrey", 0xa9, 0xa9, 0xa9), + ("darkkhaki", 0xbd, 0xb7, 0x6b), + ("darkmagenta", 0x8b, 0x00, 0x8b), + ("darkolivegreen", 0x55, 0x6b, 0x2f), + ("darkorange", 0xff, 0x8c, 0x00), + ("darkorchid", 0x99, 0x32, 0xcc), + ("darkred", 0x8b, 0x00, 0x00), + ("darksalmon", 0xe9, 0x96, 0x7a), + ("darkseagreen", 0x8f, 0xbc, 0x8f), + ("darkslateblue", 0x48, 0x3d, 0x8b), + ("darkslategray", 0x2f, 0x4f, 0x4f), + ("darkslategrey", 0x2f, 0x4f, 0x4f), + ("darkturquoise", 0x00, 0xce, 0xd1), + ("darkviolet", 0x94, 0x00, 0xd3), + ("deeppink", 0xff, 0x14, 0x93), + ("deepskyblue", 0x00, 0xbf, 0xff), + ("dimgray", 0x69, 0x69, 0x69), + ("dimgrey", 0x69, 0x69, 0x69), + ("dodgerblue", 0x1e, 0x90, 0xff), + ("firebrick", 0xb2, 0x22, 0x22), + ("floralwhite", 0xff, 0xfa, 0xf0), + ("forestgreen", 0x22, 0x8b, 0x22), + ("fuchsia", 0xff, 0x00, 0xff), + ("gainsboro", 0xdc, 0xdc, 0xdc), + ("ghostwhite", 0xf8, 0xf8, 0xff), + ("gold", 0xff, 0xd7, 0x00), + ("goldenrod", 0xda, 0xa5, 0x20), + ("gray", 0x80, 0x80, 0x80), + ("green", 0x00, 0x80, 0x00), + ("greenyellow", 0xad, 0xff, 0x2f), + ("grey", 0x80, 0x80, 0x80), + ("honeydew", 0xf0, 0xff, 0xf0), + ("hotpink", 0xff, 0x69, 0xb4), + ("indianred", 0xcd, 0x5c, 0x5c), + ("indigo", 0x4b, 0x00, 0x82), + ("ivory", 0xff, 0xff, 0xf0), + ("khaki", 0xf0, 0xe6, 0x8c), + ("lavender", 0xe6, 0xe6, 0xfa), + ("lavenderblush", 0xff, 0xf0, 0xf5), + ("lawngreen", 0x7c, 0xfc, 0x00), + ("lemonchiffon", 0xff, 0xfa, 0xcd), + ("lightblue", 0xad, 0xd8, 0xe6), + ("lightcoral", 0xf0, 0x80, 0x80), + ("lightcyan", 0xe0, 0xff, 0xff), + ("lightgoldenrodyellow", 0xfa, 0xfa, 0xd2), + ("lightgray", 0xd3, 0xd3, 0xd3), + ("lightgreen", 0x90, 0xee, 0x90), + ("lightgrey", 0xd3, 0xd3, 0xd3), + ("lightpink", 0xff, 0xb6, 0xc1), + ("lightsalmon", 0xff, 0xa0, 0x7a), + ("lightseagreen", 0x20, 0xb2, 0xaa), + ("lightskyblue", 0x87, 0xce, 0xfa), + ("lightslategray", 0x77, 0x88, 0x99), + ("lightslategrey", 0x77, 0x88, 0x99), + ("lightsteelblue", 0xb0, 0xc4, 0xde), + ("lightyellow", 0xff, 0xff, 0xe0), + ("lime", 0x00, 0xff, 0x00), + ("limegreen", 0x32, 0xcd, 0x32), + ("linen", 0xfa, 0xf0, 0xe6), + ("magenta", 0xff, 0x00, 0xff), + ("maroon", 0x80, 0x00, 0x00), + ("mediumaquamarine", 0x66, 0xcd, 0xaa), + ("mediumblue", 0x00, 0x00, 0xcd), + ("mediumorchid", 0xba, 0x55, 0xd3), + ("mediumpurple", 0x93, 0x70, 0xdb), + ("mediumseagreen", 0x3c, 0xb3, 0x71), + ("mediumslateblue", 0x7b, 0x68, 0xee), + ("mediumspringgreen", 0x00, 0xfa, 0x9a), + ("mediumturquoise", 0x48, 0xd1, 0xcc), + ("mediumvioletred", 0xc7, 0x15, 0x85), + ("midnightblue", 0x19, 0x19, 0x70), + ("mintcream", 0xf5, 0xff, 0xfa), + ("mistyrose", 0xff, 0xe4, 0xe1), + ("moccasin", 0xff, 0xe4, 0xb5), + ("navajowhite", 0xff, 0xde, 0xad), + ("navy", 0x00, 0x00, 0x80), + ("oldlace", 0xfd, 0xf5, 0xe6), + ("olive", 0x80, 0x80, 0x00), + ("olivedrab", 0x6b, 0x8e, 0x23), + ("orange", 0xff, 0xa5, 0x00), + ("orangered", 0xff, 0x45, 0x00), + ("orchid", 0xda, 0x70, 0xd6), + ("palegoldenrod", 0xee, 0xe8, 0xaa), + ("palegreen", 0x98, 0xfb, 0x98), + ("paleturquoise", 0xaf, 0xee, 0xee), + ("palevioletred", 0xdb, 0x70, 0x93), + ("papayawhip", 0xff, 0xef, 0xd5), + ("peachpuff", 0xff, 0xda, 0xb9), + ("peru", 0xcd, 0x85, 0x3f), + ("pink", 0xff, 0xc0, 0xcb), + ("plum", 0xdd, 0xa0, 0xdd), + ("powderblue", 0xb0, 0xe0, 0xe6), + ("purple", 0x80, 0x00, 0x80), + ("rebeccapurple", 0x66, 0x33, 0x99), + ("red", 0xff, 0x00, 0x00), + ("rosybrown", 0xbc, 0x8f, 0x8f), + ("royalblue", 0x41, 0x69, 0xe1), + ("saddlebrown", 0x8b, 0x45, 0x13), + ("salmon", 0xfa, 0x80, 0x72), + ("sandybrown", 0xf4, 0xa4, 0x60), + ("seagreen", 0x2e, 0x8b, 0x57), + ("seashell", 0xff, 0xf5, 0xee), + ("sienna", 0xa0, 0x52, 0x2d), + ("silver", 0xc0, 0xc0, 0xc0), + ("skyblue", 0x87, 0xce, 0xeb), + ("slateblue", 0x6a, 0x5a, 0xcd), + ("slategray", 0x70, 0x80, 0x90), + ("slategrey", 0x70, 0x80, 0x90), + ("snow", 0xff, 0xfa, 0xfa), + ("springgreen", 0x00, 0xff, 0x7f), + ("steelblue", 0x46, 0x82, 0xb4), + ("tan", 0xd2, 0xb4, 0x8c), + ("teal", 0x00, 0x80, 0x80), + ("thistle", 0xd8, 0xbf, 0xd8), + ("tomato", 0xff, 0x63, 0x47), + ("turquoise", 0x40, 0xe0, 0xd0), + ("violet", 0xee, 0x82, 0xee), + ("wheat", 0xf5, 0xde, 0xb3), + ("white", 0xff, 0xff, 0xff), + ("whitesmoke", 0xf5, 0xf5, 0xf5), + ("yellow", 0xff, 0xff, 0x00), + ("yellowgreen", 0x9a, 0xcd, 0x32), +]; + +fn named_color(name: &str) -> Option<Rgba> { + NAMED_COLORS + .iter() + .find(|(keyword, ..)| keyword.eq_ignore_ascii_case(name)) + .map(|&(_, r, g, b)| Rgba::opaque(r, g, b)) +} + +/// hex 记法:`#rgb` `#rgba` `#rrggbb` `#rrggbbaa`(CSS Color 4 §5.2)。 +fn parse_hex(hash: &str) -> Result<Rgba, ()> { + fn hex_digit(c: u8) -> Option<u8> { + match c { + b'0'..=b'9' => Some(c - b'0'), + b'a'..=b'f' => Some(c - b'a' + 10), + b'A'..=b'F' => Some(c - b'A' + 10), + _ => None, + } + } + let bytes = hash.as_bytes(); + let parse_pair = |slice: &[u8]| -> Option<u8> { + Some(hex_digit(*slice.first()?)? * 16 + hex_digit(*slice.get(1)?)?) + }; + match bytes.len() { + 3 => { + let digits: Option<Vec<u8>> = bytes.iter().map(|&c| hex_digit(c)).collect(); + let d = digits.ok_or(())?; + Ok(Rgba::opaque(d[0] * 17, d[1] * 17, d[2] * 17)) + } + 4 => { + let digits: Option<Vec<u8>> = bytes.iter().map(|&c| hex_digit(c)).collect(); + let d = digits.ok_or(())?; + Ok(Rgba { + r: d[0] * 17, + g: d[1] * 17, + b: d[2] * 17, + a: d[3] * 17, + }) + } + 6 => Ok(Rgba::opaque( + parse_pair(&bytes[0..2]).ok_or(())?, + parse_pair(&bytes[2..4]).ok_or(())?, + parse_pair(&bytes[4..6]).ok_or(())?, + )), + 8 => Ok(Rgba { + r: parse_pair(&bytes[0..2]).ok_or(())?, + g: parse_pair(&bytes[2..4]).ok_or(())?, + b: parse_pair(&bytes[4..6]).ok_or(())?, + a: parse_pair(&bytes[6..8]).ok_or(())?, + }), + _ => Err(()), + } +} + +/// 颜色分量:数字或百分比,可选 `none` 视为本轮不支持。 +enum Component { + Number(f32), + Percentage(f32), +} + +fn parse_component(input: &mut Parser<'_>) -> Result<Component, ()> { + match input.next().map_err(|_| ())? { + Token::Number { value, .. } => Ok(Component::Number(*value)), + Token::Percentage { unit_value, .. } => Ok(Component::Percentage(*unit_value * 100.0)), + _ => Err(()), + } +} + +/// alpha 分量:数字(0–1)或百分比(0–100%)。 +fn parse_alpha(input: &mut Parser<'_>) -> Result<f32, ()> { + let component = parse_component(input)?; + Ok(match component { + Component::Number(value) => value, + Component::Percentage(value) => value / 100.0, + }) +} + +/// 分量 → 8bit 通道:数字按 0–255、百分比按 0–100% 折算后 clamp 并四舍五入 +/// (CSS Color 4:rgb() 分量超出范围时 clamp 到设备无关 0–255)。 +fn component_to_byte(component: Component) -> u8 { + let raw = match component { + Component::Number(value) => value, + Component::Percentage(value) => value * 255.0 / 100.0, + }; + raw.clamp(0.0, 255.0).round() as u8 +} + +/// rgb() / rgba() 的参数:现代空白语法(可带 `/ alpha`)与 legacy 逗号语法 +/// (CSS Color 4 §5.3)。 +fn parse_rgb_arguments(input: &mut Parser<'_>) -> Result<Rgba, ()> { + let first = parse_component(input)?; + let comma = input.try_parse(Parser::expect_comma).is_ok(); + + let (red, green, blue, alpha) = if comma { + let green = parse_component(input)?; + input.expect_comma().map_err(|_| ())?; + let blue = parse_component(input)?; + let alpha = if input.try_parse(Parser::expect_comma).is_ok() { + parse_alpha(input)? + } else { + 1.0 + }; + (first, green, blue, alpha) + } else { + let green = parse_component(input)?; + let blue = parse_component(input)?; + let alpha = if input.try_parse(|i| i.expect_delim('/')).is_ok() { + parse_alpha(input)? + } else { + 1.0 + }; + (first, green, blue, alpha) + }; + + if input.expect_exhausted().is_err() { + return Err(()); + } + Ok(Rgba { + r: component_to_byte(red), + g: component_to_byte(green), + b: component_to_byte(blue), + a: (alpha.clamp(0.0, 1.0) * 255.0).round() as u8, + }) +} + +/// hsl() / hsla() 的参数(CSS Color 4 §7)。 +fn parse_hsl_arguments(input: &mut Parser<'_>) -> Result<Rgba, ()> { + let hue = parse_hue(input)?; + let comma = input.try_parse(Parser::expect_comma).is_ok(); + let (saturation, lightness, alpha) = if comma { + let saturation = parse_percentage(input)?; + input.expect_comma().map_err(|_| ())?; + let lightness = parse_percentage(input)?; + let alpha = if input.try_parse(Parser::expect_comma).is_ok() { + parse_alpha(input)? + } else { + 1.0 + }; + (saturation, lightness, alpha) + } else { + let saturation = parse_percentage(input)?; + let lightness = parse_percentage(input)?; + let alpha = if input.try_parse(|i| i.expect_delim('/')).is_ok() { + parse_alpha(input)? + } else { + 1.0 + }; + (saturation, lightness, alpha) + }; + if input.expect_exhausted().is_err() { + return Err(()); + } + Ok(hsl_to_rgb( + hue, + saturation / 100.0, + lightness / 100.0, + alpha, + )) +} + +/// `<hue>`:裸数字(度)或角度 dimension。 +fn parse_hue(input: &mut Parser<'_>) -> Result<f32, ()> { + match input.next().map_err(|_| ())? { + Token::Number { value, .. } => Ok(*value), + Token::Dimension { value, unit, .. } => { + if unit.eq_ignore_ascii_case("deg") { + Ok(*value) + } else if unit.eq_ignore_ascii_case("grad") { + Ok(*value * 360.0 / 400.0) + } else if unit.eq_ignore_ascii_case("rad") { + Ok(value.to_degrees()) + } else if unit.eq_ignore_ascii_case("turn") { + Ok(*value * 360.0) + } else { + Err(()) + } + } + _ => Err(()), + } +} + +/// 百分比的数值(`50%` → `50.0`),与 [`Component::Percentage`] 一致。 +fn parse_percentage(input: &mut Parser<'_>) -> Result<f32, ()> { + match input.next().map_err(|_| ())? { + Token::Percentage { unit_value, .. } => Ok(*unit_value * 100.0), + _ => Err(()), + } +} + +/// HSL → sRGB(CSS Color 4 §7.1 的转换算法)。 +fn hsl_to_rgb(hue: f32, saturation: f32, lightness: f32, alpha: f32) -> Rgba { + let t2 = if lightness <= 0.5 { + lightness * (1.0 + saturation) + } else { + lightness + saturation - lightness * saturation + }; + let t1 = 2.0 * lightness - t2; + let channel = |offset: f32| -> u8 { + let h = (hue.rem_euclid(360.0) + offset).rem_euclid(360.0); + let value = if h < 60.0 { + t1 + (t2 - t1) * h / 60.0 + } else if h < 180.0 { + t2 + } else if h < 240.0 { + t1 + (t2 - t1) * (240.0 - h) / 60.0 + } else { + t1 + }; + (value.clamp(0.0, 1.0) * 255.0).round() as u8 + }; + Rgba { + r: channel(120.0), + g: channel(0.0), + b: channel(-120.0), + a: (alpha.clamp(0.0, 1.0) * 255.0).round() as u8, + } +} + +#[allow(clippy::too_many_lines)] +#[cfg(test)] +mod tests { + use super::*; + + /// 单值解析入口:解析整段文本后要求耗尽。 + fn parse_typed(property: PropertyId, text: &str) -> Result<PropertyValue, ()> { + let mut parser = Parser::new(text); + let value = parse_property_value(property, &mut parser)?; + parser.expect_exhausted().map_err(|_| ())?; + Ok(value) + } + + fn parse_one(property: PropertyId, text: &str) -> PropertyValue { + parse_typed(property, text).expect("value should parse") + } + + fn parse_err(property: PropertyId, text: &str) { + assert!( + parse_typed(property, text).is_err(), + "{text} should not parse" + ); + } + + #[test] + fn position_inset_flex_grid_properties_parse() { + use PropertyValue::{ + AlignItems, AlignSelf, FlexDirection, FlexShrink, FlexWrap, Gap, GridAutoFlow, + GridTrack as GridTrackValue, Inset, JustifyContent, Position, + }; + // position + assert_eq!( + parse_one(PropertyId::Position, "absolute"), + Position(PositionValue::Absolute) + ); + assert_eq!( + parse_one(PropertyId::Position, "FIXED"), + Position(PositionValue::Fixed) + ); + parse_err(PropertyId::Position, "sticky"); + + // inset(四边 longhand 共用 InsetValue) + assert_eq!( + parse_one(PropertyId::Top, "10px"), + Inset(InsetValue::Length(10.0)) + ); + assert_eq!( + parse_one(PropertyId::Left, "50%"), + Inset(InsetValue::Percent(0.5)) + ); + assert_eq!( + parse_one(PropertyId::Bottom, "auto"), + Inset(InsetValue::Auto) + ); + + // flex-direction / flex-wrap / flex-shrink + assert_eq!( + parse_one(PropertyId::FlexDirection, "column"), + FlexDirection(FlexDirectionValue::Column) + ); + assert_eq!( + parse_one(PropertyId::FlexWrap, "wrap-reverse"), + FlexWrap(FlexWrapValue::WrapReverse) + ); + assert_eq!(parse_one(PropertyId::FlexShrink, "2"), FlexShrink(2.0)); + parse_err(PropertyId::FlexShrink, "-1"); + + // align-items / justify-content / align-self(兼容 start/end) + assert_eq!( + parse_one(PropertyId::AlignItems, "center"), + AlignItems(AlignItemsValue::Center) + ); + assert_eq!( + parse_one(PropertyId::AlignItems, "start"), + AlignItems(AlignItemsValue::FlexStart) + ); + assert_eq!( + parse_one(PropertyId::JustifyContent, "space-between"), + JustifyContent(JustifyContentValue::SpaceBetween) + ); + assert_eq!( + parse_one(PropertyId::AlignSelf, "auto"), + AlignSelf(AlignSelfValue::Auto) + ); + + // gap(auto 非法) + assert_eq!( + parse_one(PropertyId::RowGap, "8px"), + Gap(GapValue::Length(8.0)) + ); + assert_eq!( + parse_one(PropertyId::ColumnGap, "normal"), + Gap(GapValue::Normal) + ); + parse_err(PropertyId::RowGap, "auto"); + + // grid-auto-flow(可选 dense 后缀) + assert_eq!( + parse_one(PropertyId::GridAutoFlow, "row dense"), + GridAutoFlow(GridAutoFlowValue::RowDense) + ); + assert_eq!( + parse_one(PropertyId::GridAutoFlow, "column"), + GridAutoFlow(GridAutoFlowValue::Column) + ); + + // grid 轨道列表(含 minmax 与 fr) + assert_eq!( + parse_one(PropertyId::GridTemplateColumns, "100px 1fr auto"), + GridTrackValue(GridTrackList { + tracks: vec![ + GridTrack::Length(100.0), + GridTrack::Fr(1.0), + GridTrack::Auto, + ] + }) + ); + assert_eq!( + parse_one(PropertyId::GridTemplateRows, "minmax(50px, 1fr)"), + GridTrackValue(GridTrackList { + tracks: vec![GridTrack::MinMax( + Box::new(GridTrack::Length(50.0)), + Box::new(GridTrack::Fr(1.0)), + )] + }) + ); + // 无空白分隔 / 未知轨道关键字 → 整条声明无效 + parse_err(PropertyId::GridTemplateColumns, "100px2px"); + parse_err(PropertyId::GridTemplateColumns, "auto bogus"); + // gridshorthand:gap 两值、inset 四值 + } + + #[test] + fn gap_and_inset_shorthands_expand() { + let sheet = + crate::parser::Stylesheet::parse("div { gap: 10px 20px; inset: 1px 2px 3px 4px; }"); + let declarations = &sheet.rules()[0].declarations(); + assert_eq!(declarations.len(), 6); + let get = |property: PropertyId| { + declarations + .iter() + .find(|d| d.property == property) + .map(|d| &d.value) + }; + assert_eq!( + get(PropertyId::RowGap), + Some(&DeclaredValue::Typed(PropertyValue::Gap(GapValue::Length( + 10.0 + )))) + ); + assert_eq!( + get(PropertyId::ColumnGap), + Some(&DeclaredValue::Typed(PropertyValue::Gap(GapValue::Length( + 20.0 + )))) + ); + assert_eq!( + get(PropertyId::Top), + Some(&DeclaredValue::Typed(PropertyValue::Inset( + InsetValue::Length(1.0) + ))) + ); + assert_eq!( + get(PropertyId::Left), + Some(&DeclaredValue::Typed(PropertyValue::Inset( + InsetValue::Length(4.0) + ))) + ); + } + + #[test] + fn property_id_lookup_is_ascii_case_insensitive() { + assert_eq!( + PropertyId::from_name("FONT-SIZE"), + Some(PropertyId::FontSize) + ); + assert_eq!(PropertyId::from_name("color"), Some(PropertyId::Color)); + assert_eq!(PropertyId::from_name("grid-area"), None); + assert_eq!(PropertyId::FontSize.as_str(), "font-size"); + } + + #[test] + fn box_sizing_overflow_and_min_max_parse() { + assert_eq!( + parse_one(PropertyId::BoxSizing, "border-box"), + PropertyValue::BoxSizing(BoxSizingValue::BorderBox) + ); + assert_eq!( + parse_one(PropertyId::BoxSizing, "CONTENT-BOX"), + PropertyValue::BoxSizing(BoxSizingValue::ContentBox) + ); + parse_err(PropertyId::BoxSizing, "padding-box"); + + assert_eq!( + parse_one(PropertyId::Overflow, "hidden"), + PropertyValue::Overflow(OverflowValue::Hidden) + ); + assert_eq!( + parse_one(PropertyId::Overflow, "visible"), + PropertyValue::Overflow(OverflowValue::Visible) + ); + // 偏差:auto/scroll/clip 暂不建模,按无效声明丢弃 + parse_err(PropertyId::Overflow, "auto"); + parse_err(PropertyId::Overflow, "scroll"); + parse_err(PropertyId::Overflow, "clip"); + + assert_eq!( + parse_one(PropertyId::MinWidth, "40px"), + PropertyValue::Size(SizeValue::Length(40.0)) + ); + assert_eq!( + parse_one(PropertyId::MaxWidth, "50%"), + PropertyValue::Size(SizeValue::Percent(0.5)) + ); + assert_eq!( + parse_one(PropertyId::MinHeight, "auto"), + PropertyValue::Size(SizeValue::Auto) + ); + assert_eq!( + parse_one(PropertyId::MaxHeight, "0"), + PropertyValue::Size(SizeValue::Length(0.0)) + ); + // 负尺寸非法 + parse_err(PropertyId::MaxWidth, "-10px"); + } + + #[test] + fn color_hex_forms() { + assert_eq!( + parse_one(PropertyId::Color, "#fff"), + PropertyValue::Color(Rgba::opaque(255, 255, 255)) + ); + assert_eq!( + parse_one(PropertyId::Color, "#0000"), + PropertyValue::Color(Rgba { + r: 0, + g: 0, + b: 0, + a: 0 + }) + ); + assert_eq!( + parse_one(PropertyId::Color, "#336699"), + PropertyValue::Color(Rgba::opaque(0x33, 0x66, 0x99)) + ); + assert_eq!( + parse_one(PropertyId::Color, "#33669980"), + PropertyValue::Color(Rgba { + r: 0x33, + g: 0x66, + b: 0x99, + a: 0x80 + }) + ); + parse_err(PropertyId::Color, "#ff"); + parse_err(PropertyId::Color, "#ffggzz"); + } + + #[test] + fn color_named_and_transparent() { + assert_eq!( + parse_one(PropertyId::Color, "rebeccapurple"), + PropertyValue::Color(Rgba::opaque(0x66, 0x33, 0x99)) + ); + assert_eq!( + parse_one(PropertyId::Color, "BLACK"), + PropertyValue::Color(Rgba::opaque(0, 0, 0)) + ); + assert_eq!( + parse_one(PropertyId::Color, "transparent"), + PropertyValue::Color(Rgba::transparent()) + ); + parse_err(PropertyId::Color, "notacolor"); + parse_err(PropertyId::Color, "currentcolor"); + } + + #[test] + fn color_rgb_legacy_and_modern() { + assert_eq!( + parse_one(PropertyId::Color, "rgb(255, 0, 128)"), + PropertyValue::Color(Rgba::opaque(255, 0, 128)) + ); + assert_eq!( + parse_one(PropertyId::Color, "rgba(255, 0, 128, 0.5)"), + PropertyValue::Color(Rgba { + r: 255, + g: 0, + b: 128, + a: 128 + }) + ); + assert_eq!( + parse_one(PropertyId::Color, "rgb(255 0 128)"), + PropertyValue::Color(Rgba::opaque(255, 0, 128)) + ); + assert_eq!( + parse_one(PropertyId::Color, "rgb(255 0 128 / 50%)"), + PropertyValue::Color(Rgba { + r: 255, + g: 0, + b: 128, + a: 128 + }) + ); + assert_eq!( + parse_one(PropertyId::Color, "rgb(50% 0% 100%)"), + PropertyValue::Color(Rgba::opaque(128, 0, 255)) + ); + // 超范围 clamp(CSS Color 4) + assert_eq!( + parse_one(PropertyId::Color, "rgb(-20 300 128)"), + PropertyValue::Color(Rgba::opaque(0, 255, 128)) + ); + parse_err(PropertyId::Color, "rgb(255 0)"); + parse_err(PropertyId::Color, "rgb(255, 0, 128 0.5)"); + } + + #[test] + fn color_hsl() { + assert_eq!( + parse_one(PropertyId::Color, "hsl(120, 100%, 50%)"), + PropertyValue::Color(Rgba::opaque(0, 255, 0)) + ); + assert_eq!( + parse_one(PropertyId::Color, "hsl(120 100% 50%)"), + PropertyValue::Color(Rgba::opaque(0, 255, 0)) + ); + assert_eq!( + parse_one(PropertyId::Color, "hsla(0, 0%, 0%, 0.5)"), + PropertyValue::Color(Rgba { + r: 0, + g: 0, + b: 0, + a: 128 + }) + ); + // 色相取模 + assert_eq!( + parse_one(PropertyId::Color, "hsl(480 100% 50%)"), + PropertyValue::Color(Rgba::opaque(0, 255, 0)) + ); + parse_err(PropertyId::Color, "hsl(120 50 50%)"); + } + + #[test] + fn font_size_forms() { + assert_eq!( + parse_one(PropertyId::FontSize, "16px"), + PropertyValue::FontSize(FontSizeValue::Px(16.0)) + ); + assert_eq!( + parse_one(PropertyId::FontSize, "12pt"), + PropertyValue::FontSize(FontSizeValue::Px(16.0)) + ); + assert_eq!( + parse_one(PropertyId::FontSize, "1.5em"), + PropertyValue::FontSize(FontSizeValue::Em(1.5)) + ); + assert_eq!( + parse_one(PropertyId::FontSize, "120%"), + PropertyValue::FontSize(FontSizeValue::Percent(1.2)) + ); + assert_eq!( + parse_one(PropertyId::FontSize, "0"), + PropertyValue::FontSize(FontSizeValue::Px(0.0)) + ); + assert_eq!( + parse_one(PropertyId::FontSize, "x-large"), + PropertyValue::FontSize(FontSizeValue::Absolute(AbsoluteSize::XLarge)) + ); + assert_eq!( + parse_one(PropertyId::FontSize, "larger"), + PropertyValue::FontSize(FontSizeValue::Larger) + ); + parse_err(PropertyId::FontSize, "16"); + parse_err(PropertyId::FontSize, "2rem"); + parse_err(PropertyId::FontSize, "medium small"); + } + + #[test] + fn absolute_size_table_matches_spec_factors() { + // CSS Fonts 4 §2.5.1 scaling factors + assert_eq!(AbsoluteSize::XxSmall.factor(), 0.6); + assert_eq!(AbsoluteSize::XSmall.factor(), 0.75); + assert_eq!(AbsoluteSize::Small.factor(), 8.0 / 9.0); + assert_eq!(AbsoluteSize::Medium.factor(), 1.0); + assert_eq!(AbsoluteSize::Large.factor(), 1.2); + assert_eq!(AbsoluteSize::XLarge.factor(), 1.5); + assert_eq!(AbsoluteSize::XxLarge.factor(), 2.0); + assert_eq!(AbsoluteSize::XxxLarge.factor(), 3.0); + } + + #[test] + fn font_weight_forms() { + assert_eq!( + parse_one(PropertyId::FontWeight, "400"), + PropertyValue::FontWeight(FontWeightValue::Weight(400.0)) + ); + assert_eq!( + parse_one(PropertyId::FontWeight, "normal"), + PropertyValue::FontWeight(FontWeightValue::Weight(400.0)) + ); + assert_eq!( + parse_one(PropertyId::FontWeight, "bold"), + PropertyValue::FontWeight(FontWeightValue::Weight(700.0)) + ); + assert_eq!( + parse_one(PropertyId::FontWeight, "bolder"), + PropertyValue::FontWeight(FontWeightValue::Bolder) + ); + parse_err(PropertyId::FontWeight, "0"); + parse_err(PropertyId::FontWeight, "1001"); + parse_err(PropertyId::FontWeight, "bold 700"); + } + + #[test] + fn font_family_forms() { + assert_eq!( + parse_one(PropertyId::FontFamily, "serif"), + PropertyValue::FontFamily(vec![FontFamilyValue::Generic("serif")]) + ); + assert_eq!( + parse_one(PropertyId::FontFamily, "SANS-SERIF"), + PropertyValue::FontFamily(vec![FontFamilyValue::Generic("sans-serif")]) + ); + // 带引号的 serif 是普通族名,不是 generic + assert_eq!( + parse_one(PropertyId::FontFamily, "\"serif\""), + PropertyValue::FontFamily(vec![FontFamilyValue::Family("serif".into())]) + ); + assert_eq!( + parse_one(PropertyId::FontFamily, "Times New Roman, Arial, sans-serif"), + PropertyValue::FontFamily(vec![ + FontFamilyValue::Family("Times New Roman".into()), + FontFamilyValue::Family("Arial".into()), + FontFamilyValue::Generic("sans-serif"), + ]) + ); + parse_err(PropertyId::FontFamily, ""); + parse_err(PropertyId::FontFamily, "Times \"New\" Roman"); + parse_err(PropertyId::FontFamily, "12px"); + } + + #[test] + fn keyword_properties() { + assert_eq!( + parse_one(PropertyId::Display, "none"), + PropertyValue::Display(DisplayValue::None) + ); + assert_eq!( + parse_one(PropertyId::Display, "FLEX"), + PropertyValue::Display(DisplayValue::Flex) + ); + assert_eq!( + parse_one(PropertyId::Display, "table-cell"), + PropertyValue::Display(DisplayValue::TableInternal("table-cell")) + ); + parse_err(PropertyId::Display, "ruby"); + parse_err(PropertyId::Display, "block flex"); + + assert_eq!( + parse_one(PropertyId::TextAlign, "center"), + PropertyValue::TextAlign(TextAlignValue::Center) + ); + assert_eq!( + parse_one(PropertyId::TextAlign, "match-parent"), + PropertyValue::TextAlign(TextAlignValue::MatchParent) + ); + parse_err(PropertyId::TextAlign, "middle"); + + assert_eq!( + parse_one(PropertyId::FontStyle, "italic"), + PropertyValue::FontStyle(FontStyleValue::Italic) + ); + assert_eq!( + parse_one(PropertyId::FontStyle, "oblique"), + PropertyValue::FontStyle(FontStyleValue::Oblique(None)) + ); + assert_eq!( + parse_one(PropertyId::FontStyle, "oblique 30deg"), + PropertyValue::FontStyle(FontStyleValue::Oblique(Some(30.0))) + ); + parse_err(PropertyId::FontStyle, "oblique 30px"); + } + + #[test] + fn flex_property_forms() { + // flex-grow:<number [0,∞]>(CSS Flexbox §7.1) + assert_eq!( + parse_one(PropertyId::FlexGrow, "2.5"), + PropertyValue::FlexGrow(2.5) + ); + assert_eq!( + parse_one(PropertyId::FlexGrow, "0"), + PropertyValue::FlexGrow(0.0) + ); + parse_err(PropertyId::FlexGrow, "-1"); + parse_err(PropertyId::FlexGrow, "auto"); + parse_err(PropertyId::FlexGrow, "1 2"); + + // flex-basis:auto | <length-percentage>(CSS Flexbox §7.2) + assert_eq!( + parse_one(PropertyId::FlexBasis, "auto"), + PropertyValue::FlexBasis(SizeValue::Auto) + ); + assert_eq!( + parse_one(PropertyId::FlexBasis, "0"), + PropertyValue::FlexBasis(SizeValue::Length(0.0)) + ); + assert_eq!( + parse_one(PropertyId::FlexBasis, "100px"), + PropertyValue::FlexBasis(SizeValue::Length(100.0)) + ); + assert_eq!( + parse_one(PropertyId::FlexBasis, "50%"), + PropertyValue::FlexBasis(SizeValue::Percent(0.5)) + ); + parse_err(PropertyId::FlexBasis, "-5px"); + parse_err(PropertyId::FlexBasis, "content"); + } + + #[test] + fn white_space_overflow_wrap_word_break_forms() { + // white-space:六个关键字(CSS Text 3 §3.1),大小写不敏感 + for (text, expected) in [ + ("normal", WhiteSpaceValue::Normal), + ("nowrap", WhiteSpaceValue::Nowrap), + ("pre", WhiteSpaceValue::Pre), + ("pre-wrap", WhiteSpaceValue::PreWrap), + ("PRE-LINE", WhiteSpaceValue::PreLine), + ("break-spaces", WhiteSpaceValue::BreakSpaces), + ] { + assert_eq!( + parse_one(PropertyId::WhiteSpace, text), + PropertyValue::WhiteSpace(expected) + ); + } + parse_err(PropertyId::WhiteSpace, "pre nowrap"); + parse_err(PropertyId::WhiteSpace, "pre-wrap-x"); + parse_err(PropertyId::WhiteSpace, ""); + + // overflow-wrap:normal | break-word | anywhere + assert_eq!( + parse_one(PropertyId::OverflowWrap, "normal"), + PropertyValue::OverflowWrap(OverflowWrapValue::Normal) + ); + assert_eq!( + parse_one(PropertyId::OverflowWrap, "break-word"), + PropertyValue::OverflowWrap(OverflowWrapValue::BreakWord) + ); + assert_eq!( + parse_one(PropertyId::OverflowWrap, "anywhere"), + PropertyValue::OverflowWrap(OverflowWrapValue::Anywhere) + ); + parse_err(PropertyId::OverflowWrap, "break-all"); + parse_err(PropertyId::OverflowWrap, "word-wrap"); + + // word-break:normal | break-all | keep-all + assert_eq!( + parse_one(PropertyId::WordBreak, "normal"), + PropertyValue::WordBreak(WordBreakValue::Normal) + ); + assert_eq!( + parse_one(PropertyId::WordBreak, "break-all"), + PropertyValue::WordBreak(WordBreakValue::BreakAll) + ); + assert_eq!( + parse_one(PropertyId::WordBreak, "keep-all"), + PropertyValue::WordBreak(WordBreakValue::KeepAll) + ); + parse_err(PropertyId::WordBreak, "break-word"); + parse_err(PropertyId::WordBreak, "keep"); + } + + #[test] + fn declared_value_css_wide_keywords() { + fn parse_declared(text: &str) -> Result<(DeclaredValue, bool), ()> { + let mut parser = Parser::new(text); + parse_declared_value(PropertyId::Color, &mut parser) + } + assert_eq!( + parse_declared("inherit"), + Ok((DeclaredValue::CssWide(CssWideKeyword::Inherit), false)) + ); + assert_eq!( + parse_declared("INITIAL !important"), + Ok((DeclaredValue::CssWide(CssWideKeyword::Initial), true)) + ); + assert_eq!( + parse_declared("unset"), + Ok((DeclaredValue::CssWide(CssWideKeyword::Unset), false)) + ); + assert_eq!( + parse_declared("revert"), + Ok((DeclaredValue::CssWide(CssWideKeyword::Revert), false)) + ); + // CSS-wide 关键字后不允许拼接其他值 + assert!(parse_declared("inherit red").is_err()); + assert_eq!( + parse_declared("#fff"), + Ok(( + DeclaredValue::Typed(PropertyValue::Color(Rgba::opaque(255, 255, 255))), + false + )) + ); + assert_eq!( + parse_declared("#fff !important"), + Ok(( + DeclaredValue::Typed(PropertyValue::Color(Rgba::opaque(255, 255, 255))), + true + )) + ); + assert!(parse_declared("#fff important").is_err()); + assert!(parse_declared("#fff ! bogus").is_err()); + } +} diff --git a/crates/nexty-css/.mimosa/hook-status/sess_593b0e04-d177-44d2-b3cc-247d233520f7-3522fc697d.json b/crates/nexty-css/.mimosa/hook-status/sess_593b0e04-d177-44d2-b3cc-247d233520f7-3522fc697d.json new file mode 100644 index 0000000..8c2e050 --- /dev/null +++ b/crates/nexty-css/.mimosa/hook-status/sess_593b0e04-d177-44d2-b3cc-247d233520f7-3522fc697d.json @@ -0,0 +1,14 @@ +{ + "schemaVersion": "mimosa-hook-status/v1", + "recordedAt": "2026-10-31T07:13:39.241Z", + "sessionId": "sess_593b0e04-d177-44d2-b3cc-247d233520f7", + "event": "PostToolUse", + "toolName": "Edit", + "file": "src/cascade.rs", + "outcome": "clear", + "coverage": "complete", + "findingCount": 0, + "durationMs": 20, + "hostState": "hook_complete", + "reportHint": ".mimosa/reports/" +} diff --git a/crates/nexty-css/.mimosa/hook-status/sess_ca7e797f-14f7-4cd4-a65e-6a69d7418103-35569b193b.json b/crates/nexty-css/.mimosa/hook-status/sess_ca7e797f-14f7-4cd4-a65e-6a69d7418103-35569b193b.json new file mode 100644 index 0000000..2d739a9 --- /dev/null +++ b/crates/nexty-css/.mimosa/hook-status/sess_ca7e797f-14f7-4cd4-a65e-6a69d7418103-35569b193b.json @@ -0,0 +1,14 @@ +{ + "schemaVersion": "mimosa-hook-status/v1", + "recordedAt": "2026-10-11T03:14:59.648Z", + "sessionId": "sess_ca7e797f-14f7-4cd4-a65e-6a69d7418103", + "event": "PostToolUse", + "toolName": "Edit", + "file": "D:\\Nexty\\crates\\nexty-layout\\src\\block.rs", + "outcome": "inconclusive", + "coverage": "partial", + "findingCount": 0, + "durationMs": 24, + "hostState": "hook_complete", + "reportHint": ".mimosa/reports/" +} diff --git a/crates/nexty-css/.mimosa/hook-status/session_164476f9d97ffaabe4f6dc9715b6aad5-5e056c09de.json b/crates/nexty-css/.mimosa/hook-status/session_164476f9d97ffaabe4f6dc9715b6aad5-5e056c09de.json new file mode 100644 index 0000000..e61ffb0 --- /dev/null +++ b/crates/nexty-css/.mimosa/hook-status/session_164476f9d97ffaabe4f6dc9715b6aad5-5e056c09de.json @@ -0,0 +1,14 @@ +{ + "schemaVersion": "mimosa-hook-status/v1", + "recordedAt": "2026-10-24T14:07:27.999Z", + "sessionId": "session_164476f9d97ffaabe4f6dc9715b6aad5", + "event": "PostToolUse", + "toolName": "Edit", + "file": "D:\\Nexty\\crates\\nexty-layout\\tests\\layout.rs", + "outcome": "inconclusive", + "coverage": "partial", + "findingCount": 0, + "durationMs": 15, + "hostState": "hook_complete", + "reportHint": ".mimosa/reports/" +} diff --git a/crates/nexty-css/Cargo.toml b/crates/nexty-css/Cargo.toml index 469db93..32e59cd 100644 --- a/crates/nexty-css/Cargo.toml +++ b/crates/nexty-css/Cargo.toml @@ -1,7 +1,7 @@ [package] name = "nexty-css" description = "Nexty CSS 层:解析与选择器匹配复用 cssparser/selectors,cascade 自研" -version = "0.1.15" +version = "0.1.18" edition.workspace = true license.workspace = true repository.workspace = true diff --git a/crates/nexty-css/src/cascade.rs b/crates/nexty-css/src/cascade.rs index 483ba6e..f558476 100644 --- a/crates/nexty-css/src/cascade.rs +++ b/crates/nexty-css/src/cascade.rs @@ -17,13 +17,15 @@ use nexty_dom::{Document, NodeId, NodeKind}; use crate::parser::{Declaration, MediaViewport, StyleRule, Stylesheet, parse_inline_style}; use crate::selector::{NextySelector, atom_str, match_element_selectors}; use crate::value::{ - AbsoluteSize, AlignItemsValue, AlignSelfValue, BorderColorValue, BorderStyle, BorderWidthValue, - BoxSizingValue, ClearValue, CssWideKeyword, DeclaredValue, DisplayValue, FlexDirectionValue, - FlexWrapValue, FloatValue, FontFamilyValue, FontSizeValue, FontStyleValue, FontWeightValue, - GapValue, GridAutoFlowValue, GridTrackList, InsetValue, JustifyContentValue, LineHeightValue, - MAX_CSS_LENGTH, MarginValue, OverflowValue, OverflowWrapValue, PaddingValue, PositionValue, - PropertyId, PropertyValue, Rgba, SizeValue, SpacingValue, TabSizeValue, TextAlignValue, - TextIndentValue, ViewportUnit, WhiteSpaceValue, WordBreakValue, + AbsoluteSize, AlignItemsValue, AlignSelfValue, BackgroundImageValue, BorderColorValue, + BorderRadiusValue, BorderStyle, BorderWidthValue, BoxSizingValue, ClearValue, CssWideKeyword, + DeclaredValue, DisplayValue, FlexDirectionValue, FlexWrapValue, FloatValue, FontFamilyValue, + FontSizeValue, FontStyleValue, FontWeightValue, GapValue, GridAutoFlowValue, GridTrackList, + InsetValue, JustifyContentValue, LineHeightValue, MAX_CSS_LENGTH, MarginValue, OverflowValue, + OverflowWrapValue, PaddingValue, PositionValue, PropertyId, PropertyValue, Rgba, SizeValue, + SpacingValue, TabSizeValue, TextAlignValue, TextDecorationColorValue, TextDecorationLineValue, + TextDecorationStyleValue, TextIndentValue, ViewportUnit, WhiteSpaceValue, WordBreakValue, + ZIndexValue, }; /// 本层 UA 的 medium 字号基准(CSS Fonts 4 §2.5:initial 值由 UA 决定, @@ -39,6 +41,9 @@ pub struct ComputedStyle { pub color: Rgba, /// `background-color`。 pub background_color: Rgba, + /// `background-image`(CSS Backgrounds 3 §2;不继承;基础档仅 + /// none / linear-gradient,色标位置已归一为 0–1)。 + pub background_image: BackgroundImageValue, /// 计算字号(CSS px)。 pub font_size: f32, /// 计算字重(1–1000)。 @@ -66,6 +71,19 @@ pub struct ComputedStyle { pub text_indent: TextIndentValue, /// `tab-size`(CSS Text 3 §5;整数形态由 layout 按空格 advance 解析)。 pub tab_size: TabSizeValue, + /// `text-decoration-line`(CSS Text Decoration 3 §3;不继承——规范的 + /// 装饰线「传播」语义不实现,由消费方按元素自身 computed style 画, + /// 记偏差)。 + pub text_decoration_line: TextDecorationLineValue, + /// `text-decoration-style`(CSS Text Decoration 3 §5;解析存储, + /// 渲染仅 solid——偏差)。 + pub text_decoration_style: TextDecorationStyleValue, + /// `text-decoration-color`(CSS Text Decoration 3 §4;currentcolor 已按 + /// 本元素 color 解析)。 + pub text_decoration_color: Rgba, + /// `z-index`(CSS Position 3 §5;不继承;基础定序由 chrome pipeline + /// 消费,完整 stacking context 留 K7)。 + pub z_index: ZIndexValue, /// `width`(百分比由 layout 解析)。 pub width: SizeValue, /// `height`(百分比由 layout 解析)。 @@ -126,6 +144,9 @@ pub struct ComputedStyle { pub border_style: Edges<BorderStyle>, /// 四边 border 颜色(currentcolor 已按本元素 color 解析)。 pub border_color: Edges<Rgba>, + /// 四角 border-radius(top-left / top-right / bottom-right / bottom-left; + /// 百分比相对边框盒对应轴尺寸,由消费方解析)。 + pub border_radius: Corners<BorderRadiusValue>, } /// 四边值(top / right / bottom / left)。 @@ -154,6 +175,34 @@ impl<T: Copy> Edges<T> { } } +/// 四角值(top-left / top-right / bottom-right / bottom-left, +/// [CSS Backgrounds 3 §5.1](https://drafts.csswg.org/css-backgrounds-3/#border-radius) +/// 的角顺序)。 +#[derive(Debug, Clone, Copy, PartialEq)] +pub struct Corners<T> { + /// 左上角。 + pub top_left: T, + /// 右上角。 + pub top_right: T, + /// 右下角。 + pub bottom_right: T, + /// 左下角。 + pub bottom_left: T, +} + +impl<T: Copy> Corners<T> { + /// 用同一值填充四角。 + #[must_use] + pub const fn splat(value: T) -> Self { + Self { + top_left: value, + top_right: value, + bottom_right: value, + bottom_left: value, + } + } +} + impl ComputedStyle { /// 全部属性取 initial 值。 /// @@ -166,6 +215,7 @@ impl ComputedStyle { display: DisplayValue::Inline, color: Rgba::opaque(0, 0, 0), background_color: Rgba::transparent(), + background_image: BackgroundImageValue::None, font_size: MEDIUM_FONT_SIZE, font_weight: 400.0, font_style: FontStyleValue::Normal, @@ -179,6 +229,10 @@ impl ComputedStyle { word_spacing: SpacingValue::Normal, text_indent: TextIndentValue::Length(0.0), tab_size: TabSizeValue::Integer(8), + text_decoration_line: TextDecorationLineValue::None, + text_decoration_style: TextDecorationStyleValue::Solid, + text_decoration_color: Rgba::opaque(0, 0, 0), + z_index: ZIndexValue::Auto, width: SizeValue::Auto, height: SizeValue::Auto, min_width: SizeValue::Auto, @@ -209,6 +263,7 @@ impl ComputedStyle { border_width: Edges::splat(0.0), border_style: Edges::splat(BorderStyle::None), border_color: Edges::splat(Rgba::opaque(0, 0, 0)), + border_radius: Corners::splat(BorderRadiusValue::Length(0.0)), } } } @@ -240,12 +295,13 @@ impl PropertyId { /// 全部属性的固定枚举顺序。 /// /// 顺序承载计算依赖:`FontSize` 先于 `LineHeight`(百分比按自身字号折算)、 -/// `Color` 先于 border 颜色(currentcolor)、border style 先于 width -/// (none/hidden 时宽度归零)。 -const PROPERTY_ORDER: [PropertyId; 64] = [ +/// `Color` 先于 border / text-decoration 颜色(currentcolor)、border style +/// 先于 width(none/hidden 时宽度归零)。 +const PROPERTY_ORDER: [PropertyId; 73] = [ PropertyId::Display, PropertyId::Color, PropertyId::BackgroundColor, + PropertyId::BackgroundImage, PropertyId::FontSize, PropertyId::FontWeight, PropertyId::FontStyle, @@ -259,6 +315,9 @@ const PROPERTY_ORDER: [PropertyId; 64] = [ PropertyId::WordSpacing, PropertyId::TextIndent, PropertyId::TabSize, + PropertyId::TextDecorationLine, + PropertyId::TextDecorationStyle, + PropertyId::TextDecorationColor, PropertyId::Width, PropertyId::Height, PropertyId::MinWidth, @@ -276,6 +335,7 @@ const PROPERTY_ORDER: [PropertyId; 64] = [ PropertyId::Right, PropertyId::Bottom, PropertyId::Left, + PropertyId::ZIndex, PropertyId::FlexDirection, PropertyId::FlexWrap, PropertyId::FlexShrink, @@ -307,6 +367,10 @@ const PROPERTY_ORDER: [PropertyId; 64] = [ PropertyId::BorderRightColor, PropertyId::BorderBottomColor, PropertyId::BorderLeftColor, + PropertyId::BorderTopLeftRadius, + PropertyId::BorderTopRightRadius, + PropertyId::BorderBottomRightRadius, + PropertyId::BorderBottomLeftRadius, ]; /// 级联 origin 桶(CSS Cascade 5 §6.4,仅 UA 与 author 两个 origin; @@ -981,6 +1045,7 @@ resolve_viewport!(resolve_inset, InsetValue); resolve_viewport!(resolve_margin, MarginValue); resolve_viewport!(resolve_padding, PaddingValue); resolve_viewport!(resolve_gap, GapValue); +resolve_viewport!(resolve_border_radius, BorderRadiusValue); /// 逐属性解析出 computed style。 fn resolve_all( @@ -1011,6 +1076,9 @@ fn resolve_all( (PropertyId::BackgroundColor, Decision::Use(PropertyValue::Color(value))) => { style.background_color = *value; } + (PropertyId::BackgroundImage, Decision::Use(PropertyValue::BackgroundImage(value))) => { + style.background_image = value.clone(); + } (PropertyId::FontSize, Decision::Use(PropertyValue::FontSize(value))) => { style.font_size = compute_font_size(value, parent_font_size); } @@ -1077,6 +1145,28 @@ fn resolve_all( other => other, }; } + ( + PropertyId::TextDecorationLine, + Decision::Use(PropertyValue::TextDecorationLine(value)), + ) => { + style.text_decoration_line = *value; + } + ( + PropertyId::TextDecorationStyle, + Decision::Use(PropertyValue::TextDecorationStyle(value)), + ) => { + style.text_decoration_style = *value; + } + ( + PropertyId::TextDecorationColor, + Decision::Use(PropertyValue::TextDecorationColor(value)), + ) => { + // currentcolor 按本元素 color 解析(与 border 颜色同语义) + style.text_decoration_color = resolve_text_decoration_color(*value, style.color); + } + (PropertyId::ZIndex, Decision::Use(PropertyValue::ZIndex(value))) => { + style.z_index = *value; + } (PropertyId::Width, Decision::Use(PropertyValue::Size(value))) => { style.width = resolve_size(*value, viewport); } @@ -1221,6 +1311,30 @@ fn resolve_all( (PropertyId::BorderLeftColor, Decision::Use(PropertyValue::BorderColor(value))) => { style.border_color.left = resolve_border_color(*value, style.color); } + ( + PropertyId::BorderTopLeftRadius, + Decision::Use(PropertyValue::BorderRadius(value)), + ) => { + style.border_radius.top_left = resolve_border_radius(*value, viewport); + } + ( + PropertyId::BorderTopRightRadius, + Decision::Use(PropertyValue::BorderRadius(value)), + ) => { + style.border_radius.top_right = resolve_border_radius(*value, viewport); + } + ( + PropertyId::BorderBottomRightRadius, + Decision::Use(PropertyValue::BorderRadius(value)), + ) => { + style.border_radius.bottom_right = resolve_border_radius(*value, viewport); + } + ( + PropertyId::BorderBottomLeftRadius, + Decision::Use(PropertyValue::BorderRadius(value)), + ) => { + style.border_radius.bottom_left = resolve_border_radius(*value, viewport); + } // 关键字与继承:按属性回退 (property, decision @ (Decision::Parent | Decision::Initial)) => { let source = match decision { @@ -1231,6 +1345,9 @@ fn resolve_all( PropertyId::Display => style.display = source.display, PropertyId::Color => style.color = source.color, PropertyId::BackgroundColor => style.background_color = source.background_color, + PropertyId::BackgroundImage => { + style.background_image = source.background_image.clone(); + } PropertyId::FontSize => style.font_size = source.font_size, PropertyId::FontWeight => style.font_weight = source.font_weight, PropertyId::FontStyle => style.font_style = source.font_style, @@ -1244,6 +1361,16 @@ fn resolve_all( PropertyId::WordSpacing => style.word_spacing = source.word_spacing, PropertyId::TextIndent => style.text_indent = source.text_indent, PropertyId::TabSize => style.tab_size = source.tab_size, + PropertyId::TextDecorationLine => { + style.text_decoration_line = source.text_decoration_line; + } + PropertyId::TextDecorationStyle => { + style.text_decoration_style = source.text_decoration_style; + } + PropertyId::TextDecorationColor => { + style.text_decoration_color = source.text_decoration_color; + } + PropertyId::ZIndex => style.z_index = source.z_index, PropertyId::Width => style.width = source.width, PropertyId::Height => style.height = source.height, PropertyId::MinWidth => style.min_width = source.min_width, @@ -1314,6 +1441,18 @@ fn resolve_all( PropertyId::BorderLeftColor => { style.border_color.left = source.border_color.left; } + PropertyId::BorderTopLeftRadius => { + style.border_radius.top_left = source.border_radius.top_left; + } + PropertyId::BorderTopRightRadius => { + style.border_radius.top_right = source.border_radius.top_right; + } + PropertyId::BorderBottomRightRadius => { + style.border_radius.bottom_right = source.border_radius.bottom_right; + } + PropertyId::BorderBottomLeftRadius => { + style.border_radius.bottom_left = source.border_radius.bottom_left; + } } } // 声明值与属性不匹配只可能来自程序错误;保持 initial 值 @@ -1341,6 +1480,14 @@ fn resolve_border_color(value: BorderColorValue, color: Rgba) -> Rgba { } } +/// text-decoration-color 的 computed 值:currentcolor 按本元素 color 解析。 +fn resolve_text_decoration_color(value: TextDecorationColorValue, color: Rgba) -> Rgba { + match value { + TextDecorationColorValue::Rgba(rgba) => rgba, + TextDecorationColorValue::CurrentColor => color, + } +} + /// `font-size` 计算值(CSS Fonts 4 §2.5:长度/百分比相对父元素计算字号)。 /// /// 相对单位乘积过卫生钳:继承链上的巨数 em/百分比不得算出 `inf`。 @@ -2100,6 +2247,33 @@ mod tests { assert_eq!(styles[&pre].white_space, WhiteSpaceValue::PreWrap); } + /// UA 表给 `<a>` 链接 `text-decoration: underline`(WHATWG §15.3.4 + /// Phrasing content 中 `:link`/`:visited` 规则的无伪类近似),非 a + /// 元素不受影响,author 声明可覆盖。 + #[test] + fn ua_stylesheet_sets_link_underline() { + let document = build_document("<a href=\"https://example.com\">link</a><p>text</p>"); + let styles = compute_document_styles(&document, &[], Some(html_ua_stylesheet())); + let a = find_first_by_name(&document, "a").expect("a"); + assert_eq!( + styles[&a].text_decoration_line, + TextDecorationLineValue::Underline + ); + let p = find_first_by_name(&document, "p").expect("p"); + assert_eq!( + styles[&p].text_decoration_line, + TextDecorationLineValue::None + ); + + // author 普通声明压过 UA + let sheet = Stylesheet::parse("a { text-decoration: none }"); + let styles = compute_document_styles(&document, &[&sheet], Some(html_ua_stylesheet())); + assert_eq!( + styles[&a].text_decoration_line, + TextDecorationLineValue::None + ); + } + /// CSS Text 3 四属性:initial、em 按自身字号折算、percentage 保留原值、 /// 继承(四属性均 inherited)。 #[test] @@ -2380,4 +2554,147 @@ mod tests { .as_ptr(); assert!(std::ptr::eq(first_ptr, second_ptr), "原文未变应复用"); } + + // ---- K2 绘制扩展:新属性 computed 与继承性 ---- + + /// 四组新属性均不继承:父元素有值,子元素保持 initial。 + #[test] + fn drawing_extension_properties_are_not_inherited() { + let style = style_of( + "<div style=\"text-decoration: underline wavy; z-index: 5; \ + border-radius: 8px; background-image: linear-gradient(90deg, red, blue)\"> + <p>x</p></div>", + &[], + "p", + ); + assert_eq!( + style.text_decoration_line, + TextDecorationLineValue::None, + "text-decoration 不继承" + ); + assert_eq!(style.text_decoration_style, TextDecorationStyleValue::Solid); + assert_eq!(style.z_index, ZIndexValue::Auto, "z-index 不继承"); + assert_eq!( + style.border_radius.top_left, + BorderRadiusValue::Length(0.0), + "border-radius 不继承" + ); + assert_eq!( + style.background_image, + BackgroundImageValue::None, + "background-image 不继承" + ); + } + + /// text-decoration 简写展开进 cascade:line/style/color 三字段各自生效, + /// color 的 currentcolor 按本元素 color 解析。 + #[test] + fn text_decoration_computed_resolves_currentcolor() { + let style = style_of( + "<p style=\"color: blue; text-decoration: underline wavy\">x</p>", + &[], + "p", + ); + assert_eq!( + style.text_decoration_line, + TextDecorationLineValue::Underline + ); + assert_eq!(style.text_decoration_style, TextDecorationStyleValue::Wavy); + assert_eq!( + style.text_decoration_color, + Rgba::opaque(0, 0, 255), + "currentcolor 按本元素 color" + ); + // 显式 color 成分覆盖 currentcolor + let style = style_of( + "<p style=\"color: blue; text-decoration: red underline\">x</p>", + &[], + "p", + ); + assert_eq!(style.text_decoration_color, Rgba::opaque(255, 0, 0)); + } + + /// z-index:整数进 computed;`inherit` 取父 computed 值(fallback 分支)。 + #[test] + fn z_index_cascade_and_inherit() { + let document = + build_document("<div style=\"z-index: -3\"><p style=\"z-index: inherit\">x</p></div>"); + let refs: Vec<&Stylesheet> = vec![]; + let div = find_first_by_name(&document, "div").expect("div"); + let div_style = cascade(&document, div, &refs, None, None); + assert_eq!(div_style.z_index, ZIndexValue::Integer(-3)); + let p = find_first_by_name(&document, "p").expect("p"); + let p_style = cascade(&document, p, &refs, None, Some(&div_style)); + assert_eq!(p_style.z_index, ZIndexValue::Integer(-3), "inherit 取父值"); + } + + /// background-image:渐变带着归一后的色标位置进 computed style。 + #[test] + fn background_image_gradient_reaches_computed_style() { + let style = style_of( + "<p style=\"background-image: linear-gradient(to right, red, blue 50%, green)\">x</p>", + &[], + "p", + ); + let BackgroundImageValue::LinearGradient(gradient) = &style.background_image else { + panic!("gradient should reach computed style") + }; + assert_eq!(gradient.angle, 90.0); + assert_eq!(gradient.stops.len(), 3); + assert_eq!(gradient.stops[0].color, Rgba::opaque(255, 0, 0)); + assert_eq!(gradient.stops[1].position, 0.5); + assert_eq!(gradient.stops[2].position, 1.0); + } + + /// border-radius:1–4 值展开到四角;视口单位有视口时折算、无视口保留。 + #[test] + fn border_radius_computed_values() { + let style = style_of( + "<p style=\"border-radius: 10px 20px 30px 40px\">x</p>", + &[], + "p", + ); + assert_eq!( + style.border_radius.top_left, + BorderRadiusValue::Length(10.0) + ); + assert_eq!( + style.border_radius.top_right, + BorderRadiusValue::Length(20.0) + ); + assert_eq!( + style.border_radius.bottom_right, + BorderRadiusValue::Length(30.0) + ); + assert_eq!( + style.border_radius.bottom_left, + BorderRadiusValue::Length(40.0) + ); + + let document = build_document("<p></p>"); + let sheet = Stylesheet::parse("p { border-radius: 2vw 3vh }"); + let refs = vec![&sheet]; + let p = find_first_by_name(&document, "p").expect("p"); + let viewport = MediaViewport { + width: 800.0, + height: 600.0, + }; + let with_viewport = cascade_in(&document, p, &refs, None, None, Some(viewport)); + assert_eq!( + with_viewport.border_radius.top_left, + BorderRadiusValue::Length(16.0), + "2vw = 16px" + ); + assert_eq!( + with_viewport.border_radius.top_right, + BorderRadiusValue::Length(18.0), + "3vh = 18px" + ); + let without_viewport = cascade(&document, p, &refs, None, None); + assert_eq!( + without_viewport.border_radius.top_left, + BorderRadiusValue::Viewport(2.0, ViewportUnit::Vw), + "无视口保留原值" + ); + } } diff --git a/crates/nexty-css/src/lib.rs b/crates/nexty-css/src/lib.rs index 91412b1..0b9826a 100644 --- a/crates/nexty-css/src/lib.rs +++ b/crates/nexty-css/src/lib.rs @@ -7,8 +7,9 @@ //! 行为 ground truth:CSS Syntax、Selectors、CSS Cascade 规范。 //! //! 已落地:属性值模型与逐属性解析(`value`)、选择器解析与 arena DOM 匹配 -//! (`selector`)、样式表与声明块解析(`parser`)、自研 cascade 与 computed -//! style(`cascade`)、UA 默认样式表(`ua`)。 +//! (`selector`)、样式表与声明块解析(`parser`,含 `@media` 求值与 +//! `@font-face` 规则)、自研 cascade 与 computed style(`cascade`)、UA 默认 +//! 样式表(`ua`)。 //! //! **Feature**:按上表的五个模块一一对应,默认全开。依赖链为 //! `values` → `selectors` → `stylesheets` → {`cascade`, `ua-stylesheet`}, @@ -31,22 +32,28 @@ mod value; #[cfg(feature = "cascade")] pub use cascade::{ - ComputedStyle, Edges, InlineStyleCache, cascade, cascade_in, compute_document_styles, + ComputedStyle, Corners, Edges, InlineStyleCache, cascade, cascade_in, compute_document_styles, compute_document_styles_in, compute_document_styles_in_with_cache, }; #[cfg(feature = "stylesheets")] -pub use parser::{Declaration, MediaViewport, StyleRule, Stylesheet, parse_inline_style}; +pub use parser::{ + Declaration, FontFaceDisplay, FontFaceRule, FontFaceSource, FontFaceStyle, MediaViewport, + StyleRule, Stylesheet, parse_inline_style, +}; #[cfg(feature = "selectors")] pub use selector::{SelectorError, matches_selector}; #[cfg(feature = "ua-stylesheet")] pub use ua::html_ua_stylesheet; #[cfg(feature = "values")] pub use value::{ - AbsoluteSize, AlignItemsValue, AlignSelfValue, BorderColorValue, BorderStyle, BorderWidthValue, - BoxSizingValue, ClearValue, CssWideKeyword, DeclaredValue, DisplayValue, FlexDirectionValue, - FlexWrapValue, FloatValue, FontFamilyValue, FontSizeValue, FontStyleValue, FontWeightValue, - GapValue, GridAutoFlowValue, GridTrack, GridTrackList, InsetValue, JustifyContentValue, - LineHeightValue, MAX_CSS_LENGTH, MarginValue, OverflowValue, OverflowWrapValue, PaddingValue, - PositionValue, PropertyId, PropertyValue, Rgba, SizeValue, SpacingValue, TabSizeValue, - TextAlignValue, TextIndentValue, ViewportUnit, WhiteSpaceValue, WordBreakValue, + AbsoluteSize, AlignItemsValue, AlignSelfValue, BackgroundImageValue, BorderColorValue, + BorderRadiusValue, BorderStyle, BorderWidthValue, BoxSizingValue, ClearValue, CssWideKeyword, + DeclaredValue, DisplayValue, FlexDirectionValue, FlexWrapValue, FloatValue, FontFamilyValue, + FontSizeValue, FontStyleValue, FontWeightValue, GapValue, GradientColorStop, GridAutoFlowValue, + GridTrack, GridTrackList, InsetValue, JustifyContentValue, LineHeightValue, + LinearGradientValue, MAX_CSS_LENGTH, MarginValue, OverflowValue, OverflowWrapValue, + PaddingValue, PositionValue, PropertyId, PropertyValue, Rgba, SizeValue, SpacingValue, + TabSizeValue, TextAlignValue, TextDecorationColorValue, TextDecorationLineValue, + TextDecorationStyleValue, TextIndentValue, ViewportUnit, WhiteSpaceValue, WordBreakValue, + ZIndexValue, }; diff --git a/crates/nexty-css/src/parser.rs b/crates/nexty-css/src/parser.rs index 756433f..640647b 100644 --- a/crates/nexty-css/src/parser.rs +++ b/crates/nexty-css/src/parser.rs @@ -10,9 +10,25 @@ //! - 未知属性按无效声明处理;未知 at-rule(`@import` / `@supports` / …)整块跳过。 //! - `@media` 按视口条件求值([`Stylesheet::parse_with_viewport`]):命中的 //! 规则按源顺序就地展开参与级联,未命中或未提供视口的整块丢弃。 +//! - `@font-face` 按简化档解析为 [`FontFaceRule`](CSS Fonts 4 §4),由 +//! [`Stylesheet::font_faces`] 按源顺序携带;必需描述符 `font-family` +//! 缺失或非法 → 整条规则丢弃;`src` 单项非法 → 跳过该源,其余保留。 //! //! 已知偏差:`@supports` 等其余 at-rule 不求值(整体跳过);媒体特性只认 -//! `min/max-width/height`(px);嵌套 `@media` 不支持。 +//! `min/max-width/height`(px);嵌套 at-rule 不支持(含 `@media` 内的 +//! `@font-face`)。 +//! +//! `@font-face` 简化档偏差:描述符只认 `font-family`(必需) / `src` / +//! `font-weight`(单值) / `font-style` / `font-display`,其余 +//! (`unicode-range` / `font-stretch` / `font-variant` 等)按无效描述符丢弃; +//! `font-style` 只认 `normal` / `italic`(`oblique` 不识别);`font-weight` +//! 单值数字或 `normal` / `bold` 关键字,非整数字重四舍五入为整数存储 +//! (下游 face 权重类型为整数,实际字体 OS/2 权重亦为整数);`font-display` +//! 只解析存储,加载行为恒「就绪后重排一次」(swap 简化,五种取值行为相同); +//! `src` 的 `tech()` 提示与裸字符串形式不识别(含 `tech()` 的源按无效跳过), +//! `url()` 为空视为无效源,`format()` 提示只存不校验(woff/woff2 等格式 +//! 判断由字体加载层决策);未加引号的多词族名(`font-family: My Font`、 +//! `local(Helvetica Neue)`)不支持,引号形式可用。 //! //! **Feature**:本模块受 `stylesheets` feature 控制(由 lib.rs 装配)。`StyleRule` //! 的 `selectors` / `specificity` 字段由 `cascade` 模块读取,故关闭 cascade 时 @@ -22,10 +38,13 @@ use crate::selector::{NextySelector, parse_selector_list}; use crate::value::{ - BorderColorValue, BorderStyle, BorderWidthValue, DeclaredValue, PropertyId, PropertyValue, - parse_border_color_value, parse_border_style_value, parse_border_width_value, + BackgroundImageValue, BorderColorValue, BorderStyle, BorderWidthValue, DeclaredValue, + PropertyId, PropertyValue, Rgba, TextDecorationColorValue, TextDecorationLineValue, + TextDecorationStyleValue, parse_background_image_value, parse_border_color_value, + parse_border_radius_value, parse_border_style_value, parse_border_width_value, parse_color, parse_css_wide_keyword, parse_declared_value, parse_font_shorthand, parse_gap_value, - parse_inset_value, parse_margin_value, parse_padding_value, + parse_inset_value, parse_margin_value, parse_padding_value, parse_text_decoration_color_value, + parse_text_decoration_line_value, parse_text_decoration_style_value, }; use cssparser::{ AtRuleParser, DeclarationParser, ParseError, Parser, QualifiedRuleParser, RuleBodyItemParser, @@ -36,6 +55,8 @@ use cssparser::{ #[derive(Debug, Clone, Default)] pub struct Stylesheet { rules: Vec<StyleRule>, + /// `@font-face` 规则(源顺序;必需描述符非法的规则已丢弃)。 + font_faces: Vec<FontFaceRule>, } /// `@media` 求值的视口条件(CSS px)。 @@ -71,11 +92,16 @@ impl Stylesheet { let mut rule_parser = StylesheetRuleParser { viewport }; let mut input = Parser::new(css); let mut rules = Vec::new(); - // at-rule 产出的是规则组(@media 展开),普通规则是单元素组 + let mut font_faces = Vec::new(); + // at-rule 产出的是规则组(@media 展开 / 单条 @font-face), + // 普通规则是单元素组 for group in StyleSheetParser::new(&mut input, &mut rule_parser).flatten() { - rules.extend(group); + match group { + TopLevelRule::Style(style_rules) => rules.extend(style_rules), + TopLevelRule::FontFace(rule) => font_faces.push(rule), + } } - Stylesheet { rules } + Stylesheet { rules, font_faces } } /// 按源顺序返回全部样式规则。 @@ -83,6 +109,15 @@ impl Stylesheet { pub fn rules(&self) -> &[StyleRule] { &self.rules } + + /// 按源顺序返回全部 `@font-face` 规则。 + /// + /// 供下游编排字体子资源抓取与注册(K4):`family` 参与族名匹配, + /// `sources` 按序尝试。不参与级联。 + #[must_use] + pub fn font_faces(&self) -> &[FontFaceRule] { + &self.font_faces + } } /// 一条样式规则:选择器列表 + 声明块。 @@ -123,7 +158,90 @@ pub struct Declaration { pub important: bool, } -/// 顶层样式表规则解析:接受样式规则与 `@media`(带视口条件时求值)。 +/// 一条 `@font-face` 规则([CSS Fonts 4 §4](https://drafts.csswg.org/css-fonts-4/#font-face-rule) +/// 简化档,偏差见模块文档)。 +/// +/// 字段语义与下游字体描述符(`FontFaceDescriptor { family: String, +/// weight: u16, style: FontStyle::{Normal, Italic} }`)一一对应:可选描述符 +/// 未指定时为 `None`,按描述符 initial 值映射(weight → 400、style → normal)。 +#[derive(Debug, Clone, PartialEq)] +pub struct FontFaceRule { + /// `font-family` 描述符(必需;缺失或非法的规则已在解析期丢弃)。 + pub family: String, + /// `src` 描述符:按源顺序排列、按序尝试的源列表(非法项已跳过; + /// 描述符存在但全部源无效时为空列表——下游按「永远不可用 → 回退 + /// 系统字体」处理)。 + pub sources: Vec<FontFaceSource>, + /// `font-weight` 描述符([CSS Fonts 4](https://drafts.csswg.org/css-fonts-4/#descdef-font-face-font-weight), + /// 单值 1–1000;`None` = 未指定,语义默认 400)。 + pub weight: Option<u16>, + /// `font-style` 描述符(`None` = 未指定,语义默认 normal)。 + pub style: Option<FontFaceStyle>, + /// `font-display` 描述符(只解析存储;行为恒 swap 简化——偏差)。 + pub display: Option<FontFaceDisplay>, +} + +/// `src` 描述符的一个源([CSS Fonts 4](https://drafts.csswg.org/css-fonts-4/#descdef-font-face-src) +/// 简化档):按序尝试,前一个失败才轮到下一个。 +#[derive(Debug, Clone, PartialEq)] +pub enum FontFaceSource { + /// 外部资源:`url(…)` + 可选 `format(…)` 提示(提示只存不校验)。 + Url { + /// 资源地址(cssparser 已去转义;相对地址由抓取方按文档 base 解析)。 + url: String, + /// `format()` 提示字符串(无提示时为空列表)。 + format_hints: Vec<String>, + }, + /// 本地字体:`local(…)` 引用的已安装字体名。 + Local { + /// 本地字体名(`<string>` 或单个 `<custom-ident>`)。 + name: String, + }, +} + +/// `font-style` 描述符取值(`normal` / `italic`;`oblique` 不识别——偏差)。 +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +pub enum FontFaceStyle { + /// `normal`(描述符 initial)。 + Normal, + /// `italic`。 + Italic, +} + +/// `font-display` 描述符取值 +/// ([CSS Fonts 4](https://drafts.csswg.org/css-fonts-4/#descdef-font-face-font-display))。 +/// +/// 当前只解析存储:加载行为恒「就绪后重排一次」(swap 简化——偏差)。 +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +pub enum FontFaceDisplay { + /// `auto`(描述符 initial)。 + Auto, + /// `block`。 + Block, + /// `swap`。 + Swap, + /// `fallback`。 + Fallback, + /// `optional`。 + Optional, +} + +/// 顶层规则解析产物:样式规则组(qualified 规则单元素、`@media` 展开多 +/// 元素)或一条 `@font-face` 规则。cssparser 要求两个 trait 的产出同型, +/// 故用枚举承载后在 [`Stylesheet::parse_inner`] 分流。 +enum TopLevelRule { + Style(Vec<StyleRule>), + FontFace(FontFaceRule), +} + +/// 顶层 at-rule 的 prelude:`@media` 查询或无 prelude 的 `@font-face`。 +enum AtRulePrelude { + Media(MediaQuery), + FontFace, +} + +/// 顶层样式表规则解析:接受样式规则、`@media`(带视口条件时求值) +/// 与 `@font-face`。 struct StylesheetRuleParser { /// `@media` 求值条件;`None` 时 `@media` 不命中(整块丢弃)。 viewport: Option<MediaViewport>, @@ -131,7 +249,7 @@ struct StylesheetRuleParser { impl<'i> QualifiedRuleParser<'i> for StylesheetRuleParser { type Prelude = Vec<NextySelector>; - type QualifiedRule = Vec<StyleRule>; + type QualifiedRule = TopLevelRule; type Error = (); fn parse_prelude( @@ -152,19 +270,19 @@ impl<'i> QualifiedRuleParser<'i> for StylesheetRuleParser { .map(NextySelector::to_css_string) .collect::<Vec<_>>() .join(", "); - Ok(vec![StyleRule { + Ok(TopLevelRule::Style(vec![StyleRule { selectors: prelude, selector_text, declarations: parse_declaration_block(input), - }]) + }])) } } // 未知 at-rule(@import / @supports / …)走默认拒绝, // StyleSheetParser 按规范把整块消费掉。 impl<'i> AtRuleParser<'i> for StylesheetRuleParser { - type Prelude = MediaQuery; - type AtRule = Vec<StyleRule>; + type Prelude = AtRulePrelude; + type AtRule = TopLevelRule; type Error = (); fn parse_prelude( @@ -173,7 +291,15 @@ impl<'i> AtRuleParser<'i> for StylesheetRuleParser { input: &mut Parser<'i>, ) -> Result<Self::Prelude, ParseError<Self::Error>> { if name.eq_ignore_ascii_case("media") { - parse_media_query(input).ok_or_else(ParseError::<()>::unexpected_token) + parse_media_query(input) + .map(AtRulePrelude::Media) + .ok_or_else(ParseError::<()>::unexpected_token) + } else if name.eq_ignore_ascii_case("font-face") { + // @font-face 无 prelude(CSS Fonts 4 §4);带 prelude 的规则整条丢弃 + input + .expect_exhausted() + .map_err(|_| ParseError::<()>::unexpected_token())?; + Ok(AtRulePrelude::FontFace) } else { Err(ParseError::unexpected_token()) } @@ -185,18 +311,38 @@ impl<'i> AtRuleParser<'i> for StylesheetRuleParser { _start: &cssparser::ParserState, input: &mut Parser<'i>, ) -> Result<Self::AtRule, ParseError<Self::Error>> { - // 内层按 rule list 解析(块必须整体消费后再决定去留); - // 嵌套 at-rule 在内层解析器里按未知拒绝 - let mut inner = MediaQueryRuleParser; - let mut rules = Vec::new(); - for group in RuleBodyParser::new(input, &mut inner).flatten() { - rules.extend(group); + match prelude { + AtRulePrelude::Media(query) => { + // 内层按 rule list 解析(块必须整体消费后再决定去留); + // 嵌套 at-rule 在内层解析器里按未知拒绝 + let mut inner = MediaQueryRuleParser; + let mut rules = Vec::new(); + for group in RuleBodyParser::new(input, &mut inner).flatten() { + rules.extend(group); + } + let matched = match self.viewport { + Some(viewport) => query.matches(viewport), + None => false, + }; + Ok(TopLevelRule::Style(if matched { + rules + } else { + Vec::new() + })) + } + AtRulePrelude::FontFace => { + // 描述符块:逐条解析,非法描述符就地丢弃(CSS Fonts 4 §4) + let mut descriptors = FontFaceDescriptorsParser; + let mut items = Vec::new(); + for item in RuleBodyParser::new(input, &mut descriptors).flatten() { + items.push(item); + } + // 必需描述符 font-family 缺失 → 整条规则丢弃 + parse_font_face_rule(items) + .map(TopLevelRule::FontFace) + .ok_or_else(ParseError::<()>::unexpected_token) + } } - let matched = match self.viewport { - Some(viewport) => prelude.matches(viewport), - None => false, - }; - Ok(if matched { rules } else { Vec::new() }) } } @@ -380,6 +526,322 @@ fn parse_media_feature(input: &mut Parser<'_>) -> Result<MediaFeature, ()> { } } +// ---- @font-face 描述符解析(CSS Fonts 4 §4) ---- + +/// `@font-face` 块内单项解析结果(描述符产出;非法项由 cssparser 错误恢复丢弃)。 +enum FontFaceItem { + Family(String), + Sources(Vec<FontFaceSource>), + Weight(u16), + Style(FontFaceStyle), + Display(FontFaceDisplay), +} + +/// `@font-face` 块内描述符解析器:只接受描述符声明,拒绝嵌套规则与 at-rule。 +struct FontFaceDescriptorsParser; + +impl<'i> DeclarationParser<'i> for FontFaceDescriptorsParser { + type Declaration = FontFaceItem; + type Error = (); + + fn parse_value<'t>( + &mut self, + name: cssparser::CowRcStr<'i>, + input: &mut Parser<'i>, + _declaration_start: &cssparser::ParserState, + ) -> Result<FontFaceItem, ParseError<Self::Error>> { + let item = if name.eq_ignore_ascii_case("font-family") { + parse_font_face_family(input).map(FontFaceItem::Family) + } else if name.eq_ignore_ascii_case("src") { + Ok(FontFaceItem::Sources(parse_font_face_sources(input))) + } else if name.eq_ignore_ascii_case("font-weight") { + parse_font_face_weight(input).map(FontFaceItem::Weight) + } else if name.eq_ignore_ascii_case("font-style") { + parse_font_face_style(input).map(FontFaceItem::Style) + } else if name.eq_ignore_ascii_case("font-display") { + parse_font_face_display(input).map(FontFaceItem::Display) + } else { + // 未知 / 记偏差不解析的描述符(unicode-range、font-stretch、 + // font-variant、font-feature-settings…)按无效描述符丢弃 + Err(()) + }; + item.map_err(|_| ParseError::<()>::unexpected_token()) + } +} + +impl<'i> QualifiedRuleParser<'i> for FontFaceDescriptorsParser { + type Prelude = (); + type QualifiedRule = FontFaceItem; + type Error = (); +} + +impl<'i> AtRuleParser<'i> for FontFaceDescriptorsParser { + type Prelude = (); + type AtRule = FontFaceItem; + type Error = (); +} + +impl<'i> RuleBodyItemParser<'i, FontFaceItem, ()> for FontFaceDescriptorsParser { + // @font-face 块内只解析描述符声明(属性声明语法相同,但语义是描述符) + fn parse_declarations(&self) -> bool { + true + } + + fn parse_qualified(&self) -> bool { + false + } +} + +/// 组装 `@font-face` 规则:同一描述符多次出现取最后一条;必需的 +/// `font-family` 缺失(含描述符全部非法)→ 整条规则丢弃(返回 `None`)。 +fn parse_font_face_rule(items: Vec<FontFaceItem>) -> Option<FontFaceRule> { + let mut rule = FontFaceRule { + family: String::new(), + sources: Vec::new(), + weight: None, + style: None, + display: None, + }; + for item in items { + match item { + FontFaceItem::Family(family) => rule.family = family, + FontFaceItem::Sources(sources) => rule.sources = sources, + FontFaceItem::Weight(weight) => rule.weight = Some(weight), + FontFaceItem::Style(style) => rule.style = Some(style), + FontFaceItem::Display(display) => rule.display = Some(display), + } + } + if rule.family.is_empty() { + None + } else { + Some(rule) + } +} + +/// 族名不能取的关键字:CSS-wide 关键字(描述符禁用)与 `default`(CSS Fonts 4 +/// 将其与 CSS-wide 关键字一并排除在族名之外)。 +fn is_reserved_family_name(name: &str) -> bool { + ["initial", "inherit", "unset", "revert", "default"] + .iter() + .any(|keyword| name.eq_ignore_ascii_case(keyword)) +} + +/// `font-family` 描述符(必需;简化档):`<string>` 或单个 `<custom-ident>`, +/// 空族名非法;未加引号的多词族名不支持(偏差)。 +fn parse_font_face_family(input: &mut Parser<'_>) -> Result<String, ()> { + let family = match input.next().map_err(|_| ())? { + Token::QuotedString(family) => family.to_string(), + Token::Ident(family) if !is_reserved_family_name(family) => family.to_string(), + _ => return Err(()), + }; + if family.is_empty() { + return Err(()); + } + input.expect_exhausted().map_err(|_| ())?; + Ok(family) +} + +/// `font-weight` 描述符(单值简化档):`<number [1,1000]>` 或 `normal`(400) / +/// `bold`(700)关键字;相对关键字 `bolder` / `lighter` 描述符不适用,按无效 +/// 丢弃。非整数字重四舍五入为整数存储(偏差:下游 face 权重为整数)。 +fn parse_font_face_weight(input: &mut Parser<'_>) -> Result<u16, ()> { + let weight = match input.next().map_err(|_| ())? { + Token::Number { value, .. } if (1.0..=1000.0).contains(value) => value.round() as u16, + Token::Ident(name) if name.eq_ignore_ascii_case("normal") => 400, + Token::Ident(name) if name.eq_ignore_ascii_case("bold") => 700, + _ => return Err(()), + }; + input.expect_exhausted().map_err(|_| ())?; + Ok(weight) +} + +/// `font-style` 描述符(简化档):`normal` / `italic`;`oblique` 不识别(偏差)。 +fn parse_font_face_style(input: &mut Parser<'_>) -> Result<FontFaceStyle, ()> { + let style = match input.next().map_err(|_| ())? { + Token::Ident(name) if name.eq_ignore_ascii_case("normal") => FontFaceStyle::Normal, + Token::Ident(name) if name.eq_ignore_ascii_case("italic") => FontFaceStyle::Italic, + _ => return Err(()), + }; + input.expect_exhausted().map_err(|_| ())?; + Ok(style) +} + +/// `font-display` 描述符:五关键字只解析存储(行为恒 swap 简化——偏差)。 +fn parse_font_face_display(input: &mut Parser<'_>) -> Result<FontFaceDisplay, ()> { + let display = match input.next().map_err(|_| ())? { + Token::Ident(name) if name.eq_ignore_ascii_case("auto") => FontFaceDisplay::Auto, + Token::Ident(name) if name.eq_ignore_ascii_case("block") => FontFaceDisplay::Block, + Token::Ident(name) if name.eq_ignore_ascii_case("swap") => FontFaceDisplay::Swap, + Token::Ident(name) if name.eq_ignore_ascii_case("fallback") => FontFaceDisplay::Fallback, + Token::Ident(name) if name.eq_ignore_ascii_case("optional") => FontFaceDisplay::Optional, + _ => return Err(()), + }; + input.expect_exhausted().map_err(|_| ())?; + Ok(display) +} + +/// `src` 描述符:逗号分隔有序列表,逐项解析;单项非法 → 跳过该源,其余 +/// 保留(全部无效 → 空列表,规则保留)。项内只认 `url(…)`(含带引号的 +/// `url("…")`)可选尾随一个 `format(…)`,或 `local(…)`。 +fn parse_font_face_sources(input: &mut Parser<'_>) -> Vec<FontFaceSource> { + let mut sources = Vec::new(); + // 待定项:已解析出一个源,等逗号或结束才收录;项内出现其他 token 则整项作废 + let mut pending: Option<FontFaceSource> = None; + loop { + let token = match input.next() { + Ok(token) => token, + Err(_) => { + // src 描述符结束(parse_until_after 已限定到 `;` 前) + if let Some(source) = pending.take() { + sources.push(source); + } + break; + } + }; + match token { + Token::Comma => { + if let Some(source) = pending.take() { + sources.push(source); + } + } + Token::Function(name) if name.eq_ignore_ascii_case("format") => { + // format() 只能尾随同项的 url():挂到待定项,或整项作废 + let attachable = matches!( + &pending, + Some(FontFaceSource::Url { format_hints, .. }) if format_hints.is_empty() + ); + let hints = if attachable { + input + .parse_nested_block(|input| parse_format_hints(input)) + .ok() + } else { + // 位置非法的 format():仍需消费其块再跳到逗号 + let _ = input.parse_nested_block(|_input| { + Err::<(), _>(ParseError::<()>::unexpected_token()) + }); + None + }; + match (hints, &mut pending) { + (Some(hints), Some(FontFaceSource::Url { format_hints, .. })) => { + *format_hints = hints; + } + _ => { + pending = None; + skip_to_comma(input); + } + } + } + token => match parse_font_face_source(token.clone(), input) { + Ok(source) if pending.is_none() => pending = Some(source), + _ => { + // 无效项,或同项出现第二个源:整项作废,跳到下一项 + pending = None; + skip_to_comma(input); + } + }, + } + } + sources +} + +/// 解析一个源项的首个 token(`token` 为已消费项的克隆,与 parser 解引用): +/// `url(…)` / `url("…")` / `local(…)`。空 `url()` 与裸字符串等其余形式按无效处理。 +fn parse_font_face_source(token: Token<'_>, input: &mut Parser<'_>) -> Result<FontFaceSource, ()> { + match token { + Token::UnquotedUrl(url) if !url.is_empty() => Ok(FontFaceSource::Url { + url: url.to_string(), + format_hints: Vec::new(), + }), + Token::Function(name) if name.eq_ignore_ascii_case("url") => { + let url = input + .parse_nested_block(|input| parse_quoted_url(input)) + .map_err(|_| ())?; + if url.is_empty() { + return Err(()); + } + Ok(FontFaceSource::Url { + url, + format_hints: Vec::new(), + }) + } + Token::Function(name) if name.eq_ignore_ascii_case("local") => { + let name = input + .parse_nested_block(|input| parse_local_name(input)) + .map_err(|_| ())?; + Ok(FontFaceSource::Local { name }) + } + _ => Err(()), + } +} + +/// `url("…")` 带引号形式:函数块内恰好一个非空 `<string>`。 +fn parse_quoted_url(input: &mut Parser<'_>) -> Result<String, ParseError<()>> { + let url = match input.next() { + Ok(Token::QuotedString(url)) => url.to_string(), + _ => return Err(ParseError::unexpected_token()), + }; + input + .expect_exhausted() + .map_err(|_| ParseError::unexpected_token())?; + Ok(url) +} + +/// `local(…)` 内容:非空 `<string>` 或单个 `<custom-ident>` +/// (未加引号的多词族名不支持——偏差)。 +fn parse_local_name(input: &mut Parser<'_>) -> Result<String, ParseError<()>> { + let name = match input.next() { + Ok(Token::QuotedString(name)) => name.to_string(), + Ok(Token::Ident(name)) if !is_reserved_family_name(name) => name.to_string(), + _ => return Err(ParseError::unexpected_token()), + }; + if name.is_empty() { + return Err(ParseError::unexpected_token()); + } + input + .expect_exhausted() + .map_err(|_| ParseError::unexpected_token())?; + Ok(name) +} + +/// `format(<string>#)` 提示:只接受带引号字符串(规范语法),逗号分隔; +/// 至少一项,含其他 token 则整个源项无效。 +fn parse_format_hints(input: &mut Parser<'_>) -> Result<Vec<String>, ParseError<()>> { + let mut hints = Vec::new(); + loop { + match input.next() { + Ok(Token::QuotedString(hint)) => hints.push(hint.to_string()), + Ok(Token::Comma) => continue, + Err(_) => break, + Ok(_) => return Err(ParseError::unexpected_token()), + } + } + if hints.is_empty() { + return Err(ParseError::unexpected_token()); + } + Ok(hints) +} + +/// 跳过一个源项的剩余 token(到逗号或 src 描述符结束);嵌套块整体消费, +/// 避免块内逗号提前截断。 +fn skip_to_comma(input: &mut Parser<'_>) { + loop { + match input.next() { + Err(_) | Ok(Token::Comma) => break, + Ok( + Token::Function(_) + | Token::ParenthesisBlock + | Token::SquareBracketBlock + | Token::CurlyBracketBlock, + ) => { + let _ = input.parse_nested_block(|_input| { + Err::<(), _>(ParseError::<()>::unexpected_token()) + }); + } + _ => {} + } + } +} + /// 解析一个声明块(`{ ... }` 内容或内联 style 属性值)。 /// /// 无效声明(含未知属性)就地跳过,其余保留(CSS Syntax §5.5)。 @@ -524,6 +986,181 @@ fn expand_shorthand(name: &str, input: &mut Parser<'_>) -> Option<Result<Shortha return Some(parse_gap_shorthand(input)); } + // text-decoration 简写:<'text-decoration-line'> || <'text-decoration-style'> + // || <'text-decoration-color'>(CSS Text Decoration 3 §3.3 基础档;缺省成分 + // 重置为 initial——line none / style solid / color currentcolor。thickness + // 成分与 `blink` 不识别,整条无效——偏差)。 + if name.eq_ignore_ascii_case("text-decoration") { + if let Ok(keyword) = input.try_parse(parse_css_wide_keyword) { + let important = input.try_parse(cssparser::parse_important).is_ok(); + if input.expect_exhausted().is_err() { + return Some(Err(())); + } + let longhands = [ + PropertyId::TextDecorationLine, + PropertyId::TextDecorationStyle, + PropertyId::TextDecorationColor, + ]; + return Some(Ok(( + longhands + .into_iter() + .map(|property| (property, DeclaredValue::CssWide(keyword))) + .collect(), + important, + ))); + } + let mut line = None; + let mut style = None; + let mut color = None; + loop { + if line.is_none() + && let Ok(value) = input.try_parse(parse_text_decoration_line_value) + { + line = Some(value); + continue; + } + if style.is_none() + && let Ok(value) = input.try_parse(parse_text_decoration_style_value) + { + style = Some(value); + continue; + } + if color.is_none() + && let Ok(value) = input.try_parse(parse_text_decoration_color_value) + { + color = Some(value); + continue; + } + break; + } + if line.is_none() && style.is_none() && color.is_none() { + return Some(Err(())); + } + let important = input.try_parse(cssparser::parse_important).is_ok(); + if input.expect_exhausted().is_err() { + return Some(Err(())); + } + return Some(Ok(( + vec![ + ( + PropertyId::TextDecorationLine, + DeclaredValue::Typed(PropertyValue::TextDecorationLine( + line.unwrap_or(TextDecorationLineValue::None), + )), + ), + ( + PropertyId::TextDecorationStyle, + DeclaredValue::Typed(PropertyValue::TextDecorationStyle( + style.unwrap_or(TextDecorationStyleValue::Solid), + )), + ), + ( + PropertyId::TextDecorationColor, + DeclaredValue::Typed(PropertyValue::TextDecorationColor( + color.unwrap_or(TextDecorationColorValue::CurrentColor), + )), + ), + ], + important, + ))); + } + + // background 简写:[ <bg-image> || <bg-color> ](CSS Backgrounds 3 §2 的 + // 两 longhand 基础子集;position / size / repeat / attachment / origin / + // clip 成分与多层背景不识别,整条无效——偏差)。缺省成分重置为 initial + // (image none / color transparent)。 + if name.eq_ignore_ascii_case("background") { + if let Ok(keyword) = input.try_parse(parse_css_wide_keyword) { + let important = input.try_parse(cssparser::parse_important).is_ok(); + if input.expect_exhausted().is_err() { + return Some(Err(())); + } + let longhands = [PropertyId::BackgroundImage, PropertyId::BackgroundColor]; + return Some(Ok(( + longhands + .into_iter() + .map(|property| (property, DeclaredValue::CssWide(keyword))) + .collect(), + important, + ))); + } + let mut image = None; + let mut color = None; + loop { + if image.is_none() + && let Ok(value) = input.try_parse(parse_background_image_value) + { + image = Some(value); + continue; + } + if color.is_none() + && let Ok(value) = input.try_parse(parse_color) + { + color = Some(value); + continue; + } + break; + } + if image.is_none() && color.is_none() { + return Some(Err(())); + } + let important = input.try_parse(cssparser::parse_important).is_ok(); + if input.expect_exhausted().is_err() { + return Some(Err(())); + } + return Some(Ok(( + vec![ + ( + PropertyId::BackgroundImage, + DeclaredValue::Typed(PropertyValue::BackgroundImage( + image.unwrap_or(BackgroundImageValue::None), + )), + ), + ( + PropertyId::BackgroundColor, + DeclaredValue::Typed(PropertyValue::Color( + color.unwrap_or_else(Rgba::transparent), + )), + ), + ], + important, + ))); + } + + // border-radius 简写:<length-percentage [0,∞]>{1,4}(CSS Backgrounds 3 + // §5.1 基础档;`/` 椭圆语法不识别,整条无效——偏差)。 + if name.eq_ignore_ascii_case("border-radius") { + if let Ok(keyword) = input.try_parse(parse_css_wide_keyword) { + let important = input.try_parse(cssparser::parse_important).is_ok(); + if input.expect_exhausted().is_err() { + return Some(Err(())); + } + return Some(Ok(( + border_radius_longhands() + .into_iter() + .map(|property| (property, DeclaredValue::CssWide(keyword))) + .collect(), + important, + ))); + } + let corners = match expand_box_values(input, parse_border_radius_value) { + Ok(values) => values, + Err(()) => return Some(Err(())), + }; + let important = input.try_parse(cssparser::parse_important).is_ok(); + if input.expect_exhausted().is_err() { + return Some(Err(())); + } + return Some(Ok(( + zip_edges( + corners, + border_radius_longhands(), + PropertyValue::BorderRadius, + ), + important, + ))); + } + // 先确认是简写名,再试 CSS-wide 关键字(否则关键字会被误吞且不复位) let is_border = name.eq_ignore_ascii_case("border"); let edges = box_shorthand_edges(name); @@ -765,6 +1402,16 @@ fn inset_longhands() -> Vec<PropertyId> { ] } +/// `border-radius` 简写的四角 longhand(顺时针:TL / TR / BR / BL)。 +fn border_radius_longhands() -> Vec<PropertyId> { + vec![ + PropertyId::BorderTopLeftRadius, + PropertyId::BorderTopRightRadius, + PropertyId::BorderBottomRightRadius, + PropertyId::BorderBottomLeftRadius, + ] +} + /// `gap` 简写:`<row-gap> <column-gap>?`(CSS Box Alignment §6)。 /// /// 单值同时作用于行与列;双值行领先、列取第二项。`normal` 不是合法 gap 值, @@ -1431,4 +2078,504 @@ mod tests { ])) ); } + + // ---- K2 绘制扩展:text-decoration / background / border-radius 简写 ---- + + use crate::value::BorderRadiusValue; + + #[test] + fn text_decoration_shorthand_expands_with_resets() { + // 单成分:缺省成分重置为 initial(line none / style solid / color currentcolor) + let sheet = Stylesheet::parse("p { text-decoration: underline }"); + assert_eq!( + declaration_of(&sheet, 0, PropertyId::TextDecorationLine).value, + DeclaredValue::Typed(PropertyValue::TextDecorationLine( + TextDecorationLineValue::Underline + )) + ); + assert_eq!( + declaration_of(&sheet, 0, PropertyId::TextDecorationStyle).value, + DeclaredValue::Typed(PropertyValue::TextDecorationStyle( + TextDecorationStyleValue::Solid + )) + ); + assert_eq!( + declaration_of(&sheet, 0, PropertyId::TextDecorationColor).value, + DeclaredValue::Typed(PropertyValue::TextDecorationColor( + TextDecorationColorValue::CurrentColor + )) + ); + + // 三成分任意顺序(|| 语义) + let sheet = Stylesheet::parse("p { text-decoration: wavy red underline }"); + assert_eq!( + declaration_of(&sheet, 0, PropertyId::TextDecorationLine).value, + DeclaredValue::Typed(PropertyValue::TextDecorationLine( + TextDecorationLineValue::Underline + )) + ); + assert_eq!( + declaration_of(&sheet, 0, PropertyId::TextDecorationStyle).value, + DeclaredValue::Typed(PropertyValue::TextDecorationStyle( + TextDecorationStyleValue::Wavy + )) + ); + assert_eq!( + declaration_of(&sheet, 0, PropertyId::TextDecorationColor).value, + DeclaredValue::Typed(PropertyValue::TextDecorationColor( + TextDecorationColorValue::Rgba(Rgba::opaque(255, 0, 0)) + )) + ); + + // 仅 color 成分合法(line 重置为 none) + let sheet = Stylesheet::parse("p { text-decoration: red }"); + assert_eq!( + declaration_of(&sheet, 0, PropertyId::TextDecorationLine).value, + DeclaredValue::Typed(PropertyValue::TextDecorationLine( + TextDecorationLineValue::None + )) + ); + + // CSS-wide 关键字作用于全部 longhand + let sheet = Stylesheet::parse("p { text-decoration: inherit !important }"); + let declarations = sheet.rules()[0].declarations(); + assert_eq!(declarations.len(), 3); + assert!(declarations.iter().all(|declaration| declaration.important + && declaration.value == DeclaredValue::CssWide(CssWideKeyword::Inherit))); + + // thickness 成分与 blink 不识别 → 整条声明丢弃(偏差) + assert!( + Stylesheet::parse("p { text-decoration: underline 2px }").rules()[0] + .declarations() + .is_empty() + ); + assert!( + Stylesheet::parse("p { text-decoration: blink }").rules()[0] + .declarations() + .is_empty() + ); + } + + #[test] + fn background_shorthand_expands_with_resets() { + // 纯色:image 重置为 none + let sheet = Stylesheet::parse("p { background: red }"); + assert_eq!( + declaration_of(&sheet, 0, PropertyId::BackgroundColor).value, + DeclaredValue::Typed(PropertyValue::Color(Rgba::opaque(255, 0, 0))) + ); + assert_eq!( + declaration_of(&sheet, 0, PropertyId::BackgroundImage).value, + DeclaredValue::Typed(PropertyValue::BackgroundImage(BackgroundImageValue::None)) + ); + + // 渐变 + 颜色任意顺序;缺省 color 重置为 transparent + for css in [ + "p { background: linear-gradient(90deg, red, blue) #0f0 }", + "p { background: #0f0 linear-gradient(90deg, red, blue) }", + ] { + let sheet = Stylesheet::parse(css); + assert_eq!( + declaration_of(&sheet, 0, PropertyId::BackgroundColor).value, + DeclaredValue::Typed(PropertyValue::Color(Rgba::opaque(0, 255, 0))), + "{css}" + ); + let image = declaration_of(&sheet, 0, PropertyId::BackgroundImage) + .value + .clone(); + let DeclaredValue::Typed(PropertyValue::BackgroundImage( + BackgroundImageValue::LinearGradient(gradient), + )) = image + else { + panic!("{css} should carry a linear-gradient") + }; + assert_eq!(gradient.angle, 90.0); + assert_eq!(gradient.stops.len(), 2); + } + + // 纯渐变:color 重置为 transparent + let sheet = Stylesheet::parse("p { background: linear-gradient(red, blue) }"); + assert_eq!( + declaration_of(&sheet, 0, PropertyId::BackgroundColor).value, + DeclaredValue::Typed(PropertyValue::Color(Rgba::transparent())) + ); + + // CSS-wide 关键字 + let sheet = Stylesheet::parse("p { background: initial }"); + let declarations = sheet.rules()[0].declarations(); + assert_eq!(declarations.len(), 2); + assert!(declarations.iter().all( + |declaration| declaration.value == DeclaredValue::CssWide(CssWideKeyword::Initial) + )); + + // position / repeat 等成分不识别 → 整条声明丢弃(偏差);空值非法 + assert!( + Stylesheet::parse("p { background: url(x.png) no-repeat }").rules()[0] + .declarations() + .is_empty() + ); + assert!( + Stylesheet::parse("p { background: no-repeat red }").rules()[0] + .declarations() + .is_empty() + ); + assert!( + Stylesheet::parse("p { background: }").rules()[0] + .declarations() + .is_empty() + ); + } + + #[test] + fn border_radius_shorthand_expands_clockwise() { + // 单值:四角同值 + let sheet = Stylesheet::parse("p { border-radius: 10px }"); + assert_eq!(sheet.rules()[0].declarations().len(), 4); + for property in [ + PropertyId::BorderTopLeftRadius, + PropertyId::BorderTopRightRadius, + PropertyId::BorderBottomRightRadius, + PropertyId::BorderBottomLeftRadius, + ] { + assert_eq!( + declaration_of(&sheet, 0, property).value, + DeclaredValue::Typed(PropertyValue::BorderRadius(BorderRadiusValue::Length(10.0))) + ); + } + + // 双值:TL/BR 取第一,TR/BL 取第二 + let sheet = Stylesheet::parse("p { border-radius: 10px 20px }"); + assert_eq!( + declaration_of(&sheet, 0, PropertyId::BorderTopLeftRadius).value, + DeclaredValue::Typed(PropertyValue::BorderRadius(BorderRadiusValue::Length(10.0))) + ); + assert_eq!( + declaration_of(&sheet, 0, PropertyId::BorderTopRightRadius).value, + DeclaredValue::Typed(PropertyValue::BorderRadius(BorderRadiusValue::Length(20.0))) + ); + assert_eq!( + declaration_of(&sheet, 0, PropertyId::BorderBottomRightRadius).value, + DeclaredValue::Typed(PropertyValue::BorderRadius(BorderRadiusValue::Length(10.0))) + ); + assert_eq!( + declaration_of(&sheet, 0, PropertyId::BorderBottomLeftRadius).value, + DeclaredValue::Typed(PropertyValue::BorderRadius(BorderRadiusValue::Length(20.0))) + ); + + // 三值:TR/BL 取第二;四值顺时针 + let sheet = Stylesheet::parse("p { border-radius: 10px 20px 30px }"); + assert_eq!( + declaration_of(&sheet, 0, PropertyId::BorderBottomLeftRadius).value, + DeclaredValue::Typed(PropertyValue::BorderRadius(BorderRadiusValue::Length(20.0))) + ); + let sheet = Stylesheet::parse("p { border-radius: 10% 20px 30% 40px }"); + assert_eq!( + declaration_of(&sheet, 0, PropertyId::BorderTopLeftRadius).value, + DeclaredValue::Typed(PropertyValue::BorderRadius(BorderRadiusValue::Percent(0.1))) + ); + assert_eq!( + declaration_of(&sheet, 0, PropertyId::BorderBottomLeftRadius).value, + DeclaredValue::Typed(PropertyValue::BorderRadius(BorderRadiusValue::Length(40.0))) + ); + + // CSS-wide 关键字 + let sheet = Stylesheet::parse("p { border-radius: unset }"); + let declarations = sheet.rules()[0].declarations(); + assert_eq!(declarations.len(), 4); + assert!( + declarations + .iter() + .all(|declaration| declaration.value + == DeclaredValue::CssWide(CssWideKeyword::Unset)) + ); + + // `/` 椭圆语法不识别 → 整条声明丢弃(偏差) + assert!( + Stylesheet::parse("p { border-radius: 10px / 20px }").rules()[0] + .declarations() + .is_empty() + ); + assert!( + Stylesheet::parse("p { border-radius: 10px 20px / 5px }").rules()[0] + .declarations() + .is_empty() + ); + } + + // ---- K4 T1:@font-face 解析(CSS Fonts 4 §4) ---- + + fn url_source(url: &str, hints: &[&str]) -> FontFaceSource { + FontFaceSource::Url { + url: url.to_string(), + format_hints: hints.iter().map(|hint| hint.to_string()).collect(), + } + } + + fn local_source(name: &str) -> FontFaceSource { + FontFaceSource::Local { + name: name.to_string(), + } + } + + #[test] + fn font_face_parses_descriptors_with_defaults() { + let sheet = + Stylesheet::parse("@font-face { font-family: \"My Font\"; src: url(fonts/a.ttf); }"); + // @font-face 不进样式规则列表 + assert!(sheet.rules().is_empty()); + let faces = sheet.font_faces(); + assert_eq!(faces.len(), 1); + assert_eq!(faces[0].family, "My Font"); + assert_eq!(faces[0].sources, vec![url_source("fonts/a.ttf", &[])]); + // 可选描述符未指定 → None(下游按 initial 值映射:400 / normal / auto) + assert_eq!(faces[0].weight, None); + assert_eq!(faces[0].style, None); + assert_eq!(faces[0].display, None); + } + + #[test] + fn font_face_keeps_source_order_across_url_and_local() { + // 多 src:逗号分隔有序列表,按序尝试语义由顺序承载 + let sheet = Stylesheet::parse( + "@font-face { font-family: Fallback; src: local(Arial), \ + url(a.woff2) format(\"woff2\"), url(b.ttf) format(\"truetype\"), \ + url(\"quoted.otf\"), local(\"My Font\"); }", + ); + let sources = &sheet.font_faces()[0].sources; + assert_eq!( + sources, + &[ + local_source("Arial"), + url_source("a.woff2", &["woff2"]), + url_source("b.ttf", &["truetype"]), + url_source("quoted.otf", &[]), + local_source("My Font"), + ] + ); + } + + #[test] + fn font_face_without_required_family_is_dropped() { + // 缺 font-family → 整条规则丢弃,后续规则不受影响 + let sheet = Stylesheet::parse("@font-face { src: url(a.ttf) } p { color: red }"); + assert!(sheet.font_faces().is_empty()); + assert_eq!(sheet.rules().len(), 1); + // font-family 非法:CSS-wide 关键字 + assert!( + Stylesheet::parse("@font-face { font-family: inherit; src: url(a.ttf) }") + .font_faces() + .is_empty() + ); + // font-family 非法:未加引号的多词族名(偏差:不支持) + assert!( + Stylesheet::parse("@font-face { font-family: My Font; src: url(a.ttf) }") + .font_faces() + .is_empty() + ); + // font-family 非法:空字符串 / 非标识符 + assert!( + Stylesheet::parse("@font-face { font-family: \"\" }") + .font_faces() + .is_empty() + ); + assert!( + Stylesheet::parse("@font-face { font-family: 42 }") + .font_faces() + .is_empty() + ); + // 无块的 @font-face 与带 prelude 的 @font-face 整条丢弃 + assert!(Stylesheet::parse("@font-face;").font_faces().is_empty()); + assert!( + Stylesheet::parse("@font-face bogus { font-family: X }") + .font_faces() + .is_empty() + ); + } + + #[test] + fn font_face_invalid_sources_are_skipped_individually() { + let sheet = Stylesheet::parse( + "@font-face { font-family: X; src: url(good.ttf), bogus, \ + url(\"quoted.woff\") format(\"woff\"), local(), format(\"woff2\"), \ + \"bare-string.ttf\", url(last.ttf); }", + ); + let sources = &sheet.font_faces()[0].sources; + // bogus(非源 token)、local()(空内容)、位置非法的 format()、 + // 裸字符串四项被跳过,其余按源顺序保留 + assert_eq!( + sources, + &[ + url_source("good.ttf", &[]), + url_source("quoted.woff", &["woff"]), + url_source("last.ttf", &[]), + ] + ); + } + + #[test] + fn font_face_with_all_invalid_sources_keeps_rule_with_empty_list() { + let sheet = Stylesheet::parse("@font-face { font-family: X; src: bogus, local() }"); + let faces = sheet.font_faces(); + assert_eq!(faces.len(), 1); + assert!(faces[0].sources.is_empty()); + } + + #[test] + fn font_face_weight_number_and_keyword_forms() { + let sheet = Stylesheet::parse( + "@font-face { font-family: A; font-weight: 700 } \ + @font-face { font-family: B; font-weight: bold } \ + @font-face { font-family: C; font-weight: normal } \ + @font-face { font-family: D; font-weight: 550.5 } \ + @font-face { font-family: E; font-weight: bolder } \ + @font-face { font-family: G; font-weight: 1001 } \ + @font-face { font-family: H; font-weight: 0 }", + ); + let faces = sheet.font_faces(); + // weight 是可选描述符:非法值只丢描述符,规则保留 + assert_eq!(faces.len(), 7); + assert_eq!(faces[0].weight, Some(700)); + assert_eq!(faces[1].weight, Some(700), "bold = 700"); + assert_eq!(faces[2].weight, Some(400), "normal = 400"); + assert_eq!(faces[3].weight, Some(551), "非整数四舍五入(偏差)"); + assert_eq!(faces[4].weight, None, "bolder 描述符不适用"); + assert_eq!(faces[5].weight, None, "1001 越界"); + assert_eq!(faces[6].weight, None, "0 越界"); + } + + #[test] + fn font_face_format_hints_are_parsed_and_stored() { + // format() 多提示:CSS Fonts 4 允许逗号分隔多个 <string> + let sheet = Stylesheet::parse( + "@font-face { font-family: X; src: url(a.woff2) format(\"woff2\"), \ + url(b.otf) format(\"opentype\", \"otf\"), url(c.ttf) format(), \ + url(d.ttf) format(\"truetype\") }", + ); + let sources = &sheet.font_faces()[0].sources; + assert_eq!(sources[0], url_source("a.woff2", &["woff2"])); + assert_eq!( + sources[1], + url_source("b.otf", &["opentype", "otf"]), + "多提示按序存储" + ); + assert_eq!(sources[2], url_source("d.ttf", &["truetype"])); + // 空 format() 与未加引号的提示(规范语法是 <string>#)使该源无效 + let sheet = Stylesheet::parse( + "@font-face { font-family: X; src: url(c.ttf) format(), url(d.ttf) format(truetype) }", + ); + assert!(sheet.font_faces()[0].sources.is_empty()); + } + + #[test] + fn font_face_style_and_display_forms() { + let sheet = Stylesheet::parse( + "@font-face { font-family: A; font-style: italic; font-display: swap } \ + @font-face { font-family: B; font-style: normal; font-display: optional } \ + @font-face { font-family: C; font-style: oblique; font-display: block } \ + @font-face { font-family: D; font-style: oblique 30deg; font-display: fallback } \ + @font-face { font-family: E; font-display: auto }", + ); + let faces = sheet.font_faces(); + assert_eq!(faces.len(), 5, "可选描述符非法只丢描述符"); + assert_eq!(faces[0].style, Some(FontFaceStyle::Italic)); + assert_eq!(faces[0].display, Some(FontFaceDisplay::Swap)); + assert_eq!(faces[1].style, Some(FontFaceStyle::Normal)); + assert_eq!(faces[1].display, Some(FontFaceDisplay::Optional)); + assert_eq!(faces[2].style, None, "oblique 不识别(偏差)"); + assert_eq!(faces[2].display, Some(FontFaceDisplay::Block)); + assert_eq!(faces[3].style, None, "oblique 带角度同样不识别"); + assert_eq!(faces[3].display, Some(FontFaceDisplay::Fallback)); + assert_eq!(faces[4].display, Some(FontFaceDisplay::Auto)); + } + + #[test] + fn font_face_family_string_and_ident_forms() { + let sheet = Stylesheet::parse( + "@font-face { font-family: Custom; src: url(a.ttf) } \ + @font-face { font-family: \"With Space\"; src: url(b.ttf) } \ + @font-face { font-family: initial; src: url(c.ttf) } \ + @font-face { font-family: default; src: url(d.ttf) }", + ); + let faces = sheet.font_faces(); + assert_eq!(faces.len(), 2, "CSS-wide 关键字与 default 不能作族名"); + assert_eq!(faces[0].family, "Custom"); + assert_eq!(faces[1].family, "With Space"); + } + + #[test] + fn font_face_duplicate_descriptors_last_wins() { + let sheet = Stylesheet::parse( + "@font-face { font-family: A; font-family: B; font-weight: 300; \ + font-weight: 700; src: url(one.ttf); src: url(two.ttf) format(\"t2\"); }", + ); + let face = &sheet.font_faces()[0]; + assert_eq!(face.family, "B"); + assert_eq!(face.weight, Some(700)); + assert_eq!(face.sources, vec![url_source("two.ttf", &["t2"])]); + } + + #[test] + fn font_face_descriptor_with_important_is_dropped() { + // 描述符不接受 !important:带该标志的描述符按无效丢弃 + let sheet = Stylesheet::parse("@font-face { font-family: X !important } p { color: red }"); + assert!( + sheet.font_faces().is_empty(), + "必需描述符带 !important → 丢整条" + ); + assert_eq!(sheet.rules().len(), 1); + let sheet = Stylesheet::parse("@font-face { font-family: X; font-weight: 700 !important }"); + assert_eq!( + sheet.font_faces()[0].weight, + None, + "可选描述符带 !important 丢弃" + ); + let sheet = Stylesheet::parse("@font-face { font-family: X; src: url(a.ttf) !important }"); + assert!( + sheet.font_faces()[0].sources.is_empty(), + "src 带 !important 整个描述符无效" + ); + } + + #[test] + fn font_face_unknown_descriptors_are_dropped() { + // unicode-range / font-stretch / font-variant 等记偏差不解析: + // 按无效描述符丢弃,规则保留 + let sheet = Stylesheet::parse( + "@font-face { font-family: X; unicode-range: U+0-7F; font-stretch: condensed; \ + font-variant: small-caps; src: url(a.ttf) }", + ); + let faces = sheet.font_faces(); + assert_eq!(faces.len(), 1); + assert_eq!(faces[0].sources, vec![url_source("a.ttf", &[])]); + } + + #[test] + fn font_faces_keep_source_order_and_do_not_disturb_style_rules() { + let sheet = Stylesheet::parse( + "@font-face { font-family: A; src: url(a.ttf) } \ + p { color: red } \ + @font-face { font-family: B; font-family: C; src: url(b.ttf) } \ + q { color: blue } \ + @font-face { src: url(c.ttf) }", + ); + assert_eq!(rule_texts(&sheet), vec!["p", "q"]); + let faces = sheet.font_faces(); + assert_eq!(faces.len(), 2, "缺 family 的第三条丢弃"); + assert_eq!(faces[0].family, "A"); + assert_eq!(faces[1].family, "C", "重复描述符最后生效"); + } + + #[test] + fn font_face_inside_media_is_not_supported() { + // 嵌套 at-rule 不支持(既有偏差):@media 内的 @font-face 整块跳过 + let sheet = Stylesheet::parse_with_viewport( + "@media screen { @font-face { font-family: X; src: url(a.ttf) } }", + MediaViewport { + width: 800.0, + height: 600.0, + }, + ); + assert!(sheet.font_faces().is_empty()); + assert!(sheet.rules().is_empty()); + } } diff --git a/crates/nexty-css/src/ua.rs b/crates/nexty-css/src/ua.rs index 8cf64c7..2dde1e8 100644 --- a/crates/nexty-css/src/ua.rs +++ b/crates/nexty-css/src/ua.rs @@ -2,7 +2,9 @@ //! //! 内容取自 [HTML Standard §15 Rendering](https://html.spec.whatwg.org/multipage/rendering.html) //! 的期望渲染意图:块级元素的 `display: block`、头部的 `display: none`、 -//! 标题字号/字重、强调样式与常见默认 margin。本样式表由样式层持有, +//! 标题字号/字重、强调样式、链接下划线与常见默认 margin。链接下划线按 +//! `a` 元素选择器近似规范的 `:link`/`:visited`(本层无伪类支持),无 href +//! 的 `<a>` 也会命中,记偏差。本样式表由样式层持有, //! 经 [`crate::cascade`] 的 UA origin 参与级联(优先级低于 author 声明, //! UA `!important` 最高)。 @@ -42,6 +44,8 @@ h6 { font-size: 0.67em; margin: 1.33em 0; font-weight: bold } b, strong { font-weight: bold } i, em, cite, dfn, var { font-style: italic } +a { text-decoration: underline } + pre, code, kbd, samp, tt { font-family: monospace } pre, textarea, listing, xmp { white-space: pre } diff --git a/crates/nexty-css/src/value.rs b/crates/nexty-css/src/value.rs index 31c4767..31e751e 100644 --- a/crates/nexty-css/src/value.rs +++ b/crates/nexty-css/src/value.rs @@ -14,8 +14,19 @@ //! 相对单位、`currentcolor`、`color-mix()` 等函数色、`display` 的多关键字 //! 语法与 ruby 内部盒、`var()` 均视为无效声明(浏览器会接受其中的合法值)。 //! 视口单位(`vw`/`vh`/`vmin`/`vmax`)只在盒级长度属性(width/height/min/max、 -//! inset、margin、padding、gap)上接受;`font-size` / `border-width` / -//! `line-height` 上的视口单位视为无效声明。 +//! inset、margin、padding、gap、border-radius)上接受;`font-size` / +//! `border-width` / `line-height` 上的视口单位视为无效声明。 +//! +//! K2 绘制扩展基础档(记偏差):`text-decoration-line` 只认单关键字 +//! (多关键字空格列表与 `blink` 不识别);`text-decoration-style` 解析存储、 +//! 渲染只画 solid;`text-decoration` 简写不识别 thickness 成分; +//! `border-radius` 的 `/` 椭圆语法不识别;`linear-gradient` 只认角度 +//! (deg/grad/rad/turn)与 `to left/right/top/bottom`(对角 corner 不识别), +//! 色标位置仅百分比(长度位置、双位置不识别),位置按简化档解析——显式 +//! 位置 clamp 到 [0,1] 且保证非递减、未指定位置在两侧已定值间均匀分布 +//! (完整 gradient-line fixup 记偏差);`background-image` 不认 url() 与 +//! 多重背景;`background` 简写只认 image + color 成分(position/size/ +//! repeat/attachment/origin/clip 成分整条无效)。 //! `font` 简写里无对应 longhand 的成分——`<font-variant-css2>`(`small-caps`) //! 与 `<font-width-css3>`(宽度关键字/百分比)——按语法接受后丢弃(无渲染 //! 效果但声明不整体失效);系统字体关键字(`caption` / `menu` 等)整条无效。 @@ -198,6 +209,24 @@ pub enum PropertyId { BorderBottomColor, /// `border-left-color`。 BorderLeftColor, + /// `text-decoration-line`。 + TextDecorationLine, + /// `text-decoration-style`。 + TextDecorationStyle, + /// `text-decoration-color`。 + TextDecorationColor, + /// `z-index`。 + ZIndex, + /// `background-image`。 + BackgroundImage, + /// `border-top-left-radius`。 + BorderTopLeftRadius, + /// `border-top-right-radius`。 + BorderTopRightRadius, + /// `border-bottom-right-radius`。 + BorderBottomRightRadius, + /// `border-bottom-left-radius`。 + BorderBottomLeftRadius, } impl PropertyId { @@ -269,6 +298,15 @@ impl PropertyId { PropertyId::BorderRightColor => "border-right-color", PropertyId::BorderBottomColor => "border-bottom-color", PropertyId::BorderLeftColor => "border-left-color", + PropertyId::TextDecorationLine => "text-decoration-line", + PropertyId::TextDecorationStyle => "text-decoration-style", + PropertyId::TextDecorationColor => "text-decoration-color", + PropertyId::ZIndex => "z-index", + PropertyId::BackgroundImage => "background-image", + PropertyId::BorderTopLeftRadius => "border-top-left-radius", + PropertyId::BorderTopRightRadius => "border-top-right-radius", + PropertyId::BorderBottomRightRadius => "border-bottom-right-radius", + PropertyId::BorderBottomLeftRadius => "border-bottom-left-radius", } } @@ -276,7 +314,7 @@ impl PropertyId { /// (CSS Syntax:声明名匹配大小写不敏感)。 #[must_use] pub fn from_name(name: &str) -> Option<Self> { - const ALL: [PropertyId; 64] = [ + const ALL: [PropertyId; 73] = [ PropertyId::Display, PropertyId::Color, PropertyId::BackgroundColor, @@ -341,6 +379,15 @@ impl PropertyId { PropertyId::BorderRightColor, PropertyId::BorderBottomColor, PropertyId::BorderLeftColor, + PropertyId::TextDecorationLine, + PropertyId::TextDecorationStyle, + PropertyId::TextDecorationColor, + PropertyId::ZIndex, + PropertyId::BackgroundImage, + PropertyId::BorderTopLeftRadius, + PropertyId::BorderTopRightRadius, + PropertyId::BorderBottomRightRadius, + PropertyId::BorderBottomLeftRadius, ]; ALL.into_iter() .find(|id| id.as_str().eq_ignore_ascii_case(name)) @@ -455,6 +502,18 @@ pub enum PropertyValue { BorderStyle(BorderStyle), /// border-*-color 值。 BorderColor(BorderColorValue), + /// `text-decoration-line` 关键字。 + TextDecorationLine(TextDecorationLineValue), + /// `text-decoration-style` 关键字。 + TextDecorationStyle(TextDecorationStyleValue), + /// `text-decoration-color` 值。 + TextDecorationColor(TextDecorationColorValue), + /// `z-index` 值。 + ZIndex(ZIndexValue), + /// `background-image` 值。 + BackgroundImage(BackgroundImageValue), + /// border-*-radius 值(四角共用)。 + BorderRadius(BorderRadiusValue), } /// `display` 的单关键字值 @@ -1104,6 +1163,112 @@ pub enum BorderColorValue { CurrentColor, } +/// `text-decoration-line` 值 +/// ([CSS Text Decoration 3 §3](https://drafts.csswg.org/css-text-decor-3/#text-decoration-line-property))。 +/// +/// 基础档:单关键字(规范的多关键字空格列表与 `blink` 不识别,记偏差)。 +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +pub enum TextDecorationLineValue { + /// `none`(initial)。 + None, + /// `underline`。 + Underline, + /// `overline`。 + Overline, + /// `line-through`。 + LineThrough, +} + +/// `text-decoration-style` 值 +/// ([CSS Text Decoration 3 §5](https://drafts.csswg.org/css-text-decor-3/#text-decoration-style-property))。 +/// +/// 解析存储;本渲染管线只画 solid——其余取值记偏差。 +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +pub enum TextDecorationStyleValue { + /// `solid`(initial)。 + Solid, + /// `double`。 + Double, + /// `dotted`。 + Dotted, + /// `dashed`。 + Dashed, + /// `wavy`。 + Wavy, +} + +/// `text-decoration-color` 值 +/// ([CSS Text Decoration 3 §4](https://drafts.csswg.org/css-text-decor-3/#text-decoration-color-property))。 +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +pub enum TextDecorationColorValue { + /// 具体颜色。 + Rgba(Rgba), + /// `currentcolor`(computed 阶段按本元素 color 解析)。 + CurrentColor, +} + +/// `z-index` 值 +/// ([CSS Position 3 §5](https://drafts.csswg.org/css-position-3/#z-index))。 +/// +/// 完整 stacking context 留 K7;基础定序(定位元素绘制在普通流之上、 +/// 定位兄弟按整数排序)由 chrome pipeline 消费。 +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +pub enum ZIndexValue { + /// `auto`(initial)。 + Auto, + /// 整数(可为负)。 + Integer(i32), +} + +/// `border-radius` 单角值 +/// ([CSS Backgrounds 3 §5.1](https://drafts.csswg.org/css-backgrounds-3/#border-radius))。 +/// +/// 非负;百分比相对边框盒对应轴尺寸(水平半径相对宽、垂直半径相对高), +/// 由消费方(paint / pipeline)解析;视口单位 computed 阶段折算。 +#[derive(Debug, Clone, Copy, PartialEq)] +pub enum BorderRadiusValue { + /// 绝对长度(CSS px)。 + Length(f32), + /// 百分比(以小数存储)。 + Percent(f32), + /// 视口单位;cascade 在 computed 阶段折算(同 [`SizeValue::Viewport`])。 + Viewport(f32, ViewportUnit), +} + +/// linear-gradient 的一个色标 +/// ([CSS Images 4 §3.1.1](https://drafts.csswg.org/css-images-4/#linear-gradients), +/// 基础档:位置仅百分比)。 +#[derive(Debug, Clone, Copy, PartialEq)] +pub struct GradientColorStop { + /// 色标颜色。 + pub color: Rgba, + /// 渐变线上的位置(0..=1)。解析期已归一:显式位置 clamp 到 [0,1] + /// 且保证非递减,未指定位置在两侧已定值间均匀分布(简化档 fixup)。 + pub position: f32, +} + +/// `background-image` 的 linear-gradient 值(基础档)。 +#[derive(Debug, Clone, PartialEq)] +pub struct LinearGradientValue { + /// 渐变线角度(度;0 = to top,顺时针增加;缺省 180 = to bottom)。 + /// 负值与超过 360 的原值保留,由消费方归一。 + pub angle: f32, + /// 色标列表(≥2,源顺序,位置非递减)。 + pub stops: Vec<GradientColorStop>, +} + +/// `background-image` 值 +/// ([CSS Backgrounds 3 §2](https://drafts.csswg.org/css-backgrounds-3/#background-image))。 +/// +/// 基础档:`none` | 单个 linear-gradient;url() 与多重背景记偏差。 +#[derive(Debug, Clone, PartialEq)] +pub enum BackgroundImageValue { + /// `none`(initial)。 + None, + /// 线性渐变。 + LinearGradient(LinearGradientValue), +} + /// 把声明值解析为 [`DeclaredValue`]:先识别 CSS-wide 关键字,再按属性语法解析。 /// /// `input` 已由调用方限定在本条声明的值范围内(分号 / 块尾之前)。 @@ -1216,6 +1381,25 @@ fn parse_property_value(property: PropertyId, input: &mut Parser<'_>) -> Result< | PropertyId::BorderRightColor | PropertyId::BorderBottomColor | PropertyId::BorderLeftColor => parse_border_color(input).map(PropertyValue::BorderColor), + PropertyId::TextDecorationLine => { + parse_text_decoration_line(input).map(PropertyValue::TextDecorationLine) + } + PropertyId::TextDecorationStyle => { + parse_text_decoration_style(input).map(PropertyValue::TextDecorationStyle) + } + PropertyId::TextDecorationColor => { + parse_text_decoration_color(input).map(PropertyValue::TextDecorationColor) + } + PropertyId::ZIndex => parse_z_index(input).map(PropertyValue::ZIndex), + PropertyId::BackgroundImage => { + parse_background_image(input).map(PropertyValue::BackgroundImage) + } + PropertyId::BorderTopLeftRadius + | PropertyId::BorderTopRightRadius + | PropertyId::BorderBottomRightRadius + | PropertyId::BorderBottomLeftRadius => { + parse_border_radius(input).map(PropertyValue::BorderRadius) + } } } @@ -1805,6 +1989,212 @@ fn parse_border_color(input: &mut Parser<'_>) -> Result<BorderColorValue, ()> { } } +/// `text-decoration-line`:none | underline | overline | line-through +/// (CSS Text Decoration 3 §3;基础档单关键字,多关键字列表记偏差)。 +fn parse_text_decoration_line(input: &mut Parser<'_>) -> Result<TextDecorationLineValue, ()> { + let Token::Ident(name) = input.next().map_err(|_| ())? else { + return Err(()); + }; + if name.eq_ignore_ascii_case("none") { + Ok(TextDecorationLineValue::None) + } else if name.eq_ignore_ascii_case("underline") { + Ok(TextDecorationLineValue::Underline) + } else if name.eq_ignore_ascii_case("overline") { + Ok(TextDecorationLineValue::Overline) + } else if name.eq_ignore_ascii_case("line-through") { + Ok(TextDecorationLineValue::LineThrough) + } else { + Err(()) + } +} + +/// `text-decoration-style`:solid | double | dotted | dashed | wavy +/// (CSS Text Decoration 3 §5;解析存储,渲染仅 solid——偏差)。 +fn parse_text_decoration_style(input: &mut Parser<'_>) -> Result<TextDecorationStyleValue, ()> { + let Token::Ident(name) = input.next().map_err(|_| ())? else { + return Err(()); + }; + const STYLES: [(&str, TextDecorationStyleValue); 5] = [ + ("solid", TextDecorationStyleValue::Solid), + ("double", TextDecorationStyleValue::Double), + ("dotted", TextDecorationStyleValue::Dotted), + ("dashed", TextDecorationStyleValue::Dashed), + ("wavy", TextDecorationStyleValue::Wavy), + ]; + STYLES + .into_iter() + .find(|(keyword, _)| keyword.eq_ignore_ascii_case(name)) + .map(|(_, style)| style) + .ok_or(()) +} + +/// `text-decoration-color`:<color> | currentcolor。 +fn parse_text_decoration_color(input: &mut Parser<'_>) -> Result<TextDecorationColorValue, ()> { + if let Ok(rgba) = input.try_parse(parse_color) { + return Ok(TextDecorationColorValue::Rgba(rgba)); + } + match input.next().map_err(|_| ())? { + Token::Ident(name) if name.eq_ignore_ascii_case("currentcolor") => { + Ok(TextDecorationColorValue::CurrentColor) + } + _ => Err(()), + } +} + +/// `z-index`:auto | <integer>(CSS Position 3 §5;整数 token 之外的 Number +/// (小数)按无效处理,与 `tab-size` 同一口径)。超出 i32 的整数 token 被 +/// tokenizer 饱和到 i32::MAX/MIN,与浏览器 z-index 钳制行为一致。 +fn parse_z_index(input: &mut Parser<'_>) -> Result<ZIndexValue, ()> { + match input.next().map_err(|_| ())? { + Token::Ident(name) if name.eq_ignore_ascii_case("auto") => Ok(ZIndexValue::Auto), + Token::Number { + int_value: Some(int), + .. + } => Ok(ZIndexValue::Integer(*int)), + _ => Err(()), + } +} + +/// border-*-radius:<length-percentage [0,∞]>;视口单位按盒级长度属性接受, +/// computed 阶段折算。 +fn parse_border_radius(input: &mut Parser<'_>) -> Result<BorderRadiusValue, ()> { + match input.next().map_err(|_| ())? { + Token::Number { value: 0.0, .. } => Ok(BorderRadiusValue::Length(0.0)), + Token::Percentage { unit_value, .. } => sanitize_number(*unit_value) + .filter(|value| *value >= 0.0) + .map(BorderRadiusValue::Percent) + .ok_or(()), + Token::Dimension { value, unit, .. } => { + if *value < 0.0 { + return Err(()); + } + if let Some((amount, unit)) = viewport_length(*value, unit) { + return sanitize_number(amount) + .map(|amount| BorderRadiusValue::Viewport(amount, unit)) + .ok_or(()); + } + length_to_px(*value, unit) + .map(BorderRadiusValue::Length) + .ok_or(()) + } + _ => Err(()), + } +} + +/// `background-image`:none | linear-gradient(...)(基础档;url() 与多重 +/// 背景记偏差,整条声明无效)。 +fn parse_background_image(input: &mut Parser<'_>) -> Result<BackgroundImageValue, ()> { + match input.next().map_err(|_| ())? { + Token::Ident(name) if name.eq_ignore_ascii_case("none") => Ok(BackgroundImageValue::None), + Token::Function(name) if name.eq_ignore_ascii_case("linear-gradient") => input + .parse_nested_block(|input| { + parse_linear_gradient_arguments(input) + .map_err(|_| ParseError::<()>::unexpected_token()) + }) + .map(BackgroundImageValue::LinearGradient) + .map_err(|_| ()), + _ => Err(()), + } +} + +/// `linear-gradient(...)` 实参: +/// `[ <angle> | to left | to right | to top | to bottom ]? , <color-stop>#{2,}`。 +/// 角度缺省 180deg(to bottom,CSS Images 4 §3.1.1);对角 corner 与长度/ +/// 双位置色标不识别。 +fn parse_linear_gradient_arguments(input: &mut Parser<'_>) -> Result<LinearGradientValue, ()> { + let mut angle = 180.0; + let mut has_direction = false; + if let Ok(value) = input.try_parse(parse_angle) { + angle = value; + has_direction = true; + } else if try_parse_ident(input, "to") { + let Token::Ident(side) = input.next().map_err(|_| ())? else { + return Err(()); + }; + angle = if side.eq_ignore_ascii_case("left") { + 270.0 + } else if side.eq_ignore_ascii_case("right") { + 90.0 + } else if side.eq_ignore_ascii_case("top") { + 0.0 + } else if side.eq_ignore_ascii_case("bottom") { + 180.0 + } else { + return Err(()); + }; + has_direction = true; + } + // 角度成分可省略;省略时首个色标直接开始(无前导逗号) + if has_direction { + input.expect_comma().map_err(|_| ())?; + } + + let mut raw: Vec<(Rgba, Option<f32>)> = Vec::new(); + loop { + let color = parse_color(input)?; + let position = input + .try_parse(|i| match i.next().map_err(|_| ())? { + Token::Percentage { unit_value, .. } => sanitize_number(*unit_value).ok_or(()), + _ => Err(()), + }) + .ok(); + raw.push((color, position)); + if input.try_parse(|i| i.expect_comma()).is_err() { + break; + } + } + if raw.len() < 2 { + return Err(()); + } + let positions = resolve_stop_positions(&raw); + let stops = raw + .into_iter() + .zip(positions) + .map(|((color, _), position)| GradientColorStop { color, position }) + .collect(); + Ok(LinearGradientValue { angle, stops }) +} + +/// 色标位置的基础档解析(CSS Images 4 §3.1.1 color-stop fixup 简化档): +/// 显式位置 clamp 到 [0,1] 且保证非递减(后标不超前标);首尾未指定补 +/// 0 / 1;其余未指定色标在两侧已定位置间均匀分布。 +fn resolve_stop_positions(raw: &[(Rgba, Option<f32>)]) -> Vec<f32> { + let count = raw.len(); + let mut resolved: Vec<Option<f32>> = raw.iter().map(|(_, position)| *position).collect(); + if resolved[0].is_none() { + resolved[0] = Some(0.0); + } + if resolved[count - 1].is_none() { + resolved[count - 1] = Some(1.0); + } + let mut running = 0.0; + for position in resolved.iter_mut().flatten() { + *position = (*position).clamp(0.0, 1.0).max(running); + running = *position; + } + // 未指定色标:两侧端点必有已定值(首尾已补),按序均匀插入 + let mut positions = vec![0.0; count]; + let mut index = 0; + while index < count { + if let Some(position) = resolved[index] { + positions[index] = position; + index += 1; + continue; + } + let start = index; + while index < count && resolved[index].is_none() { + index += 1; + } + let lo = positions[start - 1]; + let hi = resolved[index].unwrap_or(1.0); + let steps = (index - start + 1) as f32; + for (step, slot) in positions[start..index].iter_mut().enumerate() { + *slot = lo + (hi - lo) * (step + 1) as f32 / steps; + } + } + positions +} + /// 以下为简写展开(parser 模块)复用的单值解析入口。 pub(crate) fn parse_margin_value(input: &mut Parser<'_>) -> Result<MarginValue, ()> { parse_margin(input) @@ -1836,6 +2226,37 @@ pub(crate) fn parse_gap_value(input: &mut Parser<'_>) -> Result<GapValue, ()> { parse_gap(input) } +/// `text-decoration` 简写复用的三个 longhand 入口。 +pub(crate) fn parse_text_decoration_line_value( + input: &mut Parser<'_>, +) -> Result<TextDecorationLineValue, ()> { + parse_text_decoration_line(input) +} + +pub(crate) fn parse_text_decoration_style_value( + input: &mut Parser<'_>, +) -> Result<TextDecorationStyleValue, ()> { + parse_text_decoration_style(input) +} + +pub(crate) fn parse_text_decoration_color_value( + input: &mut Parser<'_>, +) -> Result<TextDecorationColorValue, ()> { + parse_text_decoration_color(input) +} + +/// `background` 简写复用的 image 成分入口(color 成分直接用 [`parse_color`])。 +pub(crate) fn parse_background_image_value( + input: &mut Parser<'_>, +) -> Result<BackgroundImageValue, ()> { + parse_background_image(input) +} + +/// `border-radius` 简写复用的单角入口。 +pub(crate) fn parse_border_radius_value(input: &mut Parser<'_>) -> Result<BorderRadiusValue, ()> { + parse_border_radius(input) +} + fn parse_display(input: &mut Parser<'_>) -> Result<DisplayValue, ()> { let Token::Ident(name) = input.next().map_err(|_| ())? else { return Err(()); @@ -3555,4 +3976,243 @@ mod tests { PropertyValue::LineHeight(LineHeightValue::Number(MAX_CSS_LENGTH)) ); } + + // ---- K2 绘制扩展:text-decoration / z-index / border-radius / background-image ---- + + #[test] + fn text_decoration_longhands_parse() { + use PropertyValue::{TextDecorationColor, TextDecorationLine, TextDecorationStyle}; + // line:四关键字 + 大小写不敏感;多关键字列表与 blink 非法(基础档) + for (text, expected) in [ + ("none", TextDecorationLineValue::None), + ("underline", TextDecorationLineValue::Underline), + ("OVERLINE", TextDecorationLineValue::Overline), + ("line-through", TextDecorationLineValue::LineThrough), + ] { + assert_eq!( + parse_one(PropertyId::TextDecorationLine, text), + TextDecorationLine(expected) + ); + } + parse_err(PropertyId::TextDecorationLine, "underline overline"); + parse_err(PropertyId::TextDecorationLine, "blink"); + + // style:五关键字(解析存储;渲染仅 solid——偏差) + for (text, expected) in [ + ("solid", TextDecorationStyleValue::Solid), + ("double", TextDecorationStyleValue::Double), + ("dotted", TextDecorationStyleValue::Dotted), + ("DASHED", TextDecorationStyleValue::Dashed), + ("wavy", TextDecorationStyleValue::Wavy), + ] { + assert_eq!( + parse_one(PropertyId::TextDecorationStyle, text), + TextDecorationStyle(expected) + ); + } + parse_err(PropertyId::TextDecorationStyle, "none"); + parse_err(PropertyId::TextDecorationStyle, "wave"); + + // color:<color> | currentcolor + assert_eq!( + parse_one(PropertyId::TextDecorationColor, "red"), + TextDecorationColor(TextDecorationColorValue::Rgba(Rgba::opaque(255, 0, 0))) + ); + assert_eq!( + parse_one(PropertyId::TextDecorationColor, "#0f0"), + TextDecorationColor(TextDecorationColorValue::Rgba(Rgba::opaque(0, 255, 0))) + ); + assert_eq!( + parse_one(PropertyId::TextDecorationColor, "CURRENTCOLOR"), + TextDecorationColor(TextDecorationColorValue::CurrentColor) + ); + parse_err(PropertyId::TextDecorationColor, "1px"); + } + + #[test] + fn z_index_parses_integer_and_auto() { + use PropertyValue::ZIndex; + assert_eq!( + parse_one(PropertyId::ZIndex, "auto"), + ZIndex(ZIndexValue::Auto) + ); + assert_eq!( + parse_one(PropertyId::ZIndex, "0"), + ZIndex(ZIndexValue::Integer(0)) + ); + assert_eq!( + parse_one(PropertyId::ZIndex, "-3"), + ZIndex(ZIndexValue::Integer(-3)) + ); + assert_eq!( + parse_one(PropertyId::ZIndex, "+7"), + ZIndex(ZIndexValue::Integer(7)) + ); + // 小数、单位、非关键字非法;超出 i32 的整数 token 被 cssparser 饱和到 + // i32::MAX(与浏览器 z-index 钳制行为一致,非拒绝) + parse_err(PropertyId::ZIndex, "3.5"); + parse_err(PropertyId::ZIndex, "3px"); + parse_err(PropertyId::ZIndex, "none"); + assert_eq!( + parse_one(PropertyId::ZIndex, "2147483648"), + ZIndex(ZIndexValue::Integer(i32::MAX)) + ); + } + + #[test] + fn border_radius_corner_parses() { + use PropertyValue::BorderRadius; + assert_eq!( + parse_one(PropertyId::BorderTopLeftRadius, "10px"), + BorderRadius(BorderRadiusValue::Length(10.0)) + ); + assert_eq!( + parse_one(PropertyId::BorderBottomRightRadius, "50%"), + BorderRadius(BorderRadiusValue::Percent(0.5)) + ); + assert_eq!( + parse_one(PropertyId::BorderTopLeftRadius, "2vw"), + BorderRadius(BorderRadiusValue::Viewport(2.0, ViewportUnit::Vw)) + ); + assert_eq!( + parse_one(PropertyId::BorderTopLeftRadius, "0"), + BorderRadius(BorderRadiusValue::Length(0.0)) + ); + parse_err(PropertyId::BorderTopLeftRadius, "-5px"); + parse_err(PropertyId::BorderTopLeftRadius, "-5%"); + parse_err(PropertyId::BorderTopLeftRadius, "auto"); + parse_err(PropertyId::BorderTopLeftRadius, "5"); + } + + /// 渐变解析辅助:取 LinearGradient 值。 + fn gradient_of(text: &str) -> LinearGradientValue { + match parse_one(PropertyId::BackgroundImage, text) { + PropertyValue::BackgroundImage(BackgroundImageValue::LinearGradient(gradient)) => { + gradient + } + other => panic!("expected linear gradient, got {other:?}"), + } + } + + #[test] + fn background_image_parses_none_and_rejects_unsupported() { + assert_eq!( + parse_one(PropertyId::BackgroundImage, "none"), + PropertyValue::BackgroundImage(BackgroundImageValue::None) + ); + assert_eq!( + parse_one(PropertyId::BackgroundImage, "NONE"), + PropertyValue::BackgroundImage(BackgroundImageValue::None) + ); + // url()、多重背景、径向渐变不识别(基础档偏差) + parse_err(PropertyId::BackgroundImage, "url(x.png)"); + parse_err( + PropertyId::BackgroundImage, + "linear-gradient(red, blue), linear-gradient(blue, green)", + ); + parse_err(PropertyId::BackgroundImage, "radial-gradient(red, blue)"); + } + + #[test] + fn linear_gradient_angle_forms() { + // 缺省角度 = 180deg(to bottom,CSS Images 4 §3.1.1) + assert_eq!(gradient_of("linear-gradient(red, blue)").angle, 180.0); + assert_eq!(gradient_of("linear-gradient(0deg, red, blue)").angle, 0.0); + assert_eq!(gradient_of("linear-gradient(90deg, red, blue)").angle, 90.0); + assert_eq!( + gradient_of("linear-gradient(-45deg, red, blue)").angle, + -45.0 + ); + assert_eq!( + gradient_of("linear-gradient(0.5turn, red, blue)").angle, + 180.0 + ); + assert_eq!(gradient_of("linear-gradient(to top, red, blue)").angle, 0.0); + assert_eq!( + gradient_of("linear-gradient(to right, red, blue)").angle, + 90.0 + ); + assert_eq!( + gradient_of("linear-gradient(TO LEFT, red, blue)").angle, + 270.0 + ); + assert_eq!( + gradient_of("linear-gradient(to bottom, red, blue)").angle, + 180.0 + ); + // 函数名大小写不敏感 + assert_eq!(gradient_of("LINEAR-GRADIENT(to top, red, blue)").angle, 0.0); + // 对角 corner、多余逗号、无逗号非法 + parse_err( + PropertyId::BackgroundImage, + "linear-gradient(to top right, red, blue)", + ); + parse_err(PropertyId::BackgroundImage, "linear-gradient(red blue)"); + parse_err(PropertyId::BackgroundImage, "linear-gradient(, red, blue)"); + } + + #[test] + fn linear_gradient_stops_and_positions() { + // 无位置色标:首尾 0/1,中间均匀 + let gradient = gradient_of("linear-gradient(90deg, red, yellow, blue)"); + assert_eq!( + gradient.stops, + vec![ + GradientColorStop { + color: Rgba::opaque(255, 0, 0), + position: 0.0, + }, + GradientColorStop { + color: Rgba::opaque(255, 255, 0), + position: 0.5, + }, + GradientColorStop { + color: Rgba::opaque(0, 0, 255), + position: 1.0, + }, + ] + ); + // 显式位置 + 中间未指定:在两侧已定位置间均匀分布 + let gradient = gradient_of("linear-gradient(90deg, red, blue 50%, green)"); + assert_eq!(gradient.stops[0].position, 0.0); + assert_eq!(gradient.stops[1].position, 0.5); + assert_eq!(gradient.stops[2].position, 1.0); + assert_eq!(gradient.stops[1].color, Rgba::opaque(0, 0, 255)); + // 显式位置保留(20% → 0.2) + let gradient = gradient_of("linear-gradient(90deg, red 20%, blue)"); + assert_eq!(gradient.stops[0].position, 0.2); + assert_eq!(gradient.stops[1].position, 1.0); + // 超出 [0,1] clamp(简化档 fixup) + let gradient = gradient_of("linear-gradient(90deg, red 120%, blue)"); + assert_eq!(gradient.stops[0].position, 1.0); + assert_eq!(gradient.stops[1].position, 1.0); + // 非递减(后标不超前标,CSS Images 4 §3.1.1) + let gradient = gradient_of("linear-gradient(90deg, red 80%, blue 20%)"); + assert_eq!(gradient.stops[0].position, 0.8); + assert_eq!(gradient.stops[1].position, 0.8); + // rgb() 函数色标与连续位置逗号 + let gradient = gradient_of("linear-gradient(90deg, rgb(255, 0, 0), rgba(0, 0, 255, 0.5))"); + assert_eq!(gradient.stops[1].color.a, 128); + } + + #[test] + fn linear_gradient_requires_two_stops_and_percent_positions_only() { + // 单色标非法(CSS Images 4 §3.1.1:至少两个色标) + parse_err(PropertyId::BackgroundImage, "linear-gradient(red)"); + parse_err(PropertyId::BackgroundImage, "linear-gradient(red,)"); + // 长度位置、双位置色标不识别(基础档偏差) + parse_err( + PropertyId::BackgroundImage, + "linear-gradient(red 10px, blue)", + ); + parse_err( + PropertyId::BackgroundImage, + "linear-gradient(red 20% 40%, blue)", + ); + // 未知颜色非法 + parse_err( + PropertyId::BackgroundImage, + "linear-gradient(red, notacolor)", + ); + } } From 80d4e86538d6563a80841a5e0447f706986857ba Mon Sep 17 00:00:00 2001 From: zwork <zwork@local> Date: Sat, 31 Oct 2026 18:30:03 +0800 Subject: [PATCH 08/14] [network] url crate direct dep, four-tier encoding detection, explicit redirects + final_url, HTTP cache feature (0.1.6) --- crates/nexty-network/Cargo.toml | 17 +- crates/nexty-network/src/cache.rs | 693 ++++++++++++++++++++++++++ crates/nexty-network/src/decode.rs | 538 ++++++++++++++++++++ crates/nexty-network/src/lib.rs | 603 ++++++++++++++++++---- docs/decisions/2026-10-31-encoding.md | 61 +++ docs/decisions/2026-10-31-url.md | 47 ++ 6 files changed, 1846 insertions(+), 113 deletions(-) create mode 100644 crates/nexty-network/src/cache.rs create mode 100644 crates/nexty-network/src/decode.rs create mode 100644 docs/decisions/2026-10-31-encoding.md create mode 100644 docs/decisions/2026-10-31-url.md diff --git a/crates/nexty-network/Cargo.toml b/crates/nexty-network/Cargo.toml index 0cbdb70..842ce91 100644 --- a/crates/nexty-network/Cargo.toml +++ b/crates/nexty-network/Cargo.toml @@ -1,7 +1,7 @@ [package] name = "nexty-network" description = "Nexty 网络 facade" -version = "0.1.5" +version = "0.1.6" edition.workspace = true license.workspace = true repository.workspace = true @@ -9,11 +9,20 @@ rust-version.workspace = true [features] # 默认开启全部已实现能力;下游(nexty-chrome)依赖默认即可获得完整网络栈。 -default = ["fetch", "resolve"] +default = ["fetch", "resolve", "decode", "cache"] # 抓取后端(reqwest)与 NetworkFetcher trait / Request / Response 类型。 fetch = ["dep:reqwest"] -# 相对 URL 解析(WHATWG basic URL parsing),不依赖 reqwest,仅用其 Url 类型。 -resolve = ["dep:reqwest"] +# 相对 URL 解析(WHATWG basic URL parsing),直依赖 `url` crate,不拉 reqwest。 +# 选型见 docs/decisions/2026-10-31-url.md。 +resolve = ["dep:url"] +# 主文档字符编码探测与解码:HTTP charset > BOM > meta 预扫 > UTF-8。 +# 选型见 docs/decisions/2026-10-31-encoding.md。 +decode = ["dep:encoding_rs"] +# 内存级 HTTP 缓存(Cache-Control / ETag / Last-Modified / LRU), +# 以装饰器实现 NetworkFetcher,故隐含 fetch。 +cache = ["fetch"] [dependencies] reqwest = { version = "0.13.5", features = ["blocking"], optional = true } +url = { version = "2.5.8", optional = true } +encoding_rs = { version = "0.8.42", optional = true } diff --git a/crates/nexty-network/src/cache.rs b/crates/nexty-network/src/cache.rs new file mode 100644 index 0000000..c33d9c6 --- /dev/null +++ b/crates/nexty-network/src/cache.rs @@ -0,0 +1,693 @@ +//! 内存级 HTTP 缓存(feature `cache`,隐含 `fetch`)。 +//! +//! [`CachedFetcher`] 装饰任意 [`NetworkFetcher`],对 GET / HEAD 的 200 响应做 +//! 内存缓存: +//! - `Cache-Control: max-age=N`——新鲜度内直接复用;`no-store`——不存; +//! `no-cache`——强制再验证(即便仍新鲜); +//! - `ETag` → 条件请求 `If-None-Match`,`Last-Modified` → `If-Modified-Since` +//! (两者都在则都发);服务器 304 时复用缓存体、刷新新鲜度与 validator; +//! - `Vary` 含 `User-Agent` 以外字段(或 `*`)→ 整条不缓存;仅 `User-Agent` +//! 时记录填充请求的 UA,复用要求 UA 一致; +//! - 无新鲜度且无 validator(且非 no-cache)的 200 不缓存(简化档不认 +//! `Expires`); +//! - 单条响应体超过 [`MAX_CACHE_ENTRY_BODY_BYTES`] 不缓存;条目数达 +//! [`MAX_CACHE_ENTRIES`] 时按 LRU(最近使用时间戳)逐出。 +//! +//! 与 RFC 9111 的偏差(简化档):只认 `max-age`,不认 `Expires` / `Age` / +//! `s-maxage` / `must-revalidate`;字段限定的 `no-cache="field"` 指令不识别; +//! 再验证请求失败(网络错误)直接上抛,不回退过期响应;并发未命中不做请求 +//! 合并(后写覆盖先写);缓存体按值克隆返回,无共享引用计数。 + +use std::collections::HashMap; +use std::sync::Mutex; +use std::time::{Duration, Instant}; + +use crate::{Method, NetworkError, NetworkFetcher, Request, Response}; + +/// 缓存条目数上限;超出时逐出最久未使用的条目(LRU)。 +pub const MAX_CACHE_ENTRIES: usize = 64; + +/// 单条响应体缓存上限:超过此大小的响应不缓存(巨响应不进内存; +/// 与抓取层的字节预算语义一致,分配失败是 abort,panic 兜底兜不住)。 +pub const MAX_CACHE_ENTRY_BODY_BYTES: usize = 20 * 1024 * 1024; + +/// 内存级 HTTP 缓存装饰器:包住任意 [`NetworkFetcher`],自身也是 +/// [`NetworkFetcher`](`Send + Sync`,可直接 `Arc` 后给并发抓取共享)。 +/// +/// 缓存键为(method, url);语义清单见模块文档。 +/// +/// ``` +/// use nexty_network::{CachedFetcher, NetworkError, NetworkFetcher, Request, Response}; +/// +/// struct NullFetcher; +/// impl NetworkFetcher for NullFetcher { +/// fn fetch(&self, _request: &Request) -> Result<Response, NetworkError> { +/// Ok(Response { +/// status: 200, +/// headers: Vec::new(), +/// body: Vec::new(), +/// final_url: String::new(), +/// }) +/// } +/// } +/// +/// let fetcher = CachedFetcher::new(NullFetcher); +/// ``` +pub struct CachedFetcher<F: NetworkFetcher> { + inner: F, + state: Mutex<CacheState>, +} + +struct CacheState { + entries: HashMap<(Method, String), CacheEntry>, + /// 逻辑时钟:每次访问 / 写入递增,用作 LRU 时间戳。 + clock: u64, +} + +struct CacheEntry { + /// 缓存的完整表示(status 200 的响应,含头、体与 final_url)。 + response: Response, + /// 新鲜度起点(写入或最近一次 304 刷新时刻)。 + stored_at: Instant, + /// `Cache-Control: max-age` 的新鲜度寿命。 + max_age: Option<Duration>, + /// `Cache-Control: no-cache`:复用前强制再验证。 + must_revalidate: bool, + etag: Option<String>, + last_modified: Option<String>, + /// `Vary: User-Agent` 时的 UA 约束:外层 `Some` 表示设了约束,内层 + /// `None` 表示填充请求本就无 UA 头;复用要求 UA 一致。 + vary_ua: Option<Option<String>>, + /// 最近一次被使用(命中 / 再验证 / 写入)的逻辑时钟值。 + last_used: u64, +} + +impl<F: NetworkFetcher> CachedFetcher<F> { + /// 创建缓存装饰器。 + pub fn new(inner: F) -> Self { + Self { + inner, + state: Mutex::new(CacheState { + entries: HashMap::new(), + clock: 0, + }), + } + } + + /// 锁住缓存状态;锁中毒(他线程持锁时 panic)归入传输错误,不让缓存 + /// 层 panic 上抛。 + fn lock(&self) -> Result<std::sync::MutexGuard<'_, CacheState>, NetworkError> { + self.state.lock().map_err(|_| NetworkError::Transport) + } + + /// 按缓存策略决定是否存下一次响应;可存则写入并做 LRU 逐出。 + fn store(&self, key: &(Method, String), request: &Request, response: &Response) { + let Some(mut entry) = build_entry(request, response) else { + return; + }; + let Ok(mut state) = self.state.lock() else { + return; + }; + state.clock += 1; + entry.last_used = state.clock; + while state.entries.len() >= MAX_CACHE_ENTRIES { + let Some(victim) = state + .entries + .iter() + .min_by_key(|(_, entry)| entry.last_used) + .map(|(key, _)| key.clone()) + else { + break; + }; + state.entries.remove(&victim); + } + state.entries.insert(key.clone(), entry); + } +} + +/// 一次查询的处置:直接命中 / 带条件头再验证 / 未命中重抓。 +enum Action { + Serve(Response), + Revalidate { + if_none_match: Option<String>, + if_modified_since: Option<String>, + }, + Miss, +} + +impl<F: NetworkFetcher> NetworkFetcher for CachedFetcher<F> { + fn fetch(&self, request: &Request) -> Result<Response, NetworkError> { + let key = (request.method, request.url.clone()); + // 决策阶段持锁、网络阶段不持锁:抓取可能阻塞整请求时长, + // 持锁跨网络会串行化所有并发抓取。 + let action = { + let mut state = self.lock()?; + state.clock += 1; + let stamp = state.clock; + match state.entries.get_mut(&key) { + Some(entry) => { + if !vary_matches(entry, request) { + Action::Miss + } else if !entry.must_revalidate + && entry + .max_age + .is_some_and(|age| entry.stored_at.elapsed() < age) + { + entry.last_used = stamp; + Action::Serve(entry.response.clone()) + } else if entry.etag.is_some() || entry.last_modified.is_some() { + // 过期(或 no-cache)且可再验证 + entry.last_used = stamp; + Action::Revalidate { + if_none_match: entry.etag.clone(), + if_modified_since: entry.last_modified.clone(), + } + } else { + // 过期且无 validator 可发:无法再验证,重新抓取 + Action::Miss + } + } + None => Action::Miss, + } + }; + match action { + Action::Serve(response) => Ok(response), + Action::Miss => { + let response = self.inner.fetch(request)?; + self.store(&key, request, &response); + Ok(response) + } + Action::Revalidate { + if_none_match, + if_modified_since, + } => { + let mut conditional = request.clone(); + if let Some(tag) = if_none_match { + conditional.headers.push(("If-None-Match".to_owned(), tag)); + } + if let Some(since) = if_modified_since { + conditional + .headers + .push(("If-Modified-Since".to_owned(), since)); + } + let response = self.inner.fetch(&conditional)?; + if response.status == 304 { + let mut state = self.lock()?; + state.clock += 1; + let stamp = state.clock; + match state.entries.get_mut(&key) { + Some(entry) => { + refresh_entry(entry, &response, stamp); + Ok(entry.response.clone()) + } + // 条目在再验证期间被并发逐出:304 无体可用,重新整抓 + None => { + drop(state); + let response = self.inner.fetch(request)?; + self.store(&key, request, &response); + Ok(response) + } + } + } else { + self.store(&key, request, &response); + Ok(response) + } + } + } + } +} + +/// 304 刷新:重置新鲜度起点;304 头里出现的新 `Cache-Control` / `ETag` / +/// `Last-Modified` 覆盖旧值(RFC 9111 §4.3.4 更新存储头的简化档)。 +fn refresh_entry(entry: &mut CacheEntry, response_304: &Response, stamp: u64) { + entry.stored_at = Instant::now(); + entry.last_used = stamp; + let has_cache_control = response_304 + .headers + .iter() + .any(|(name, _)| name.eq_ignore_ascii_case("cache-control")); + if has_cache_control { + let cache_control = parse_cache_control(response_304); + entry.max_age = cache_control.max_age; + entry.must_revalidate = cache_control.no_cache; + } + for (name, value) in &response_304.headers { + if name.eq_ignore_ascii_case("etag") { + entry.etag = Some(value.clone()); + } else if name.eq_ignore_ascii_case("last-modified") { + entry.last_modified = Some(value.clone()); + } + } +} + +/// 按缓存策略判定一次响应是否可存;可存则构造条目。 +fn build_entry(request: &Request, response: &Response) -> Option<CacheEntry> { + if response.status != 200 { + // 只缓存 200(错误页与重定向终态不进缓存) + return None; + } + if response.body.len() > MAX_CACHE_ENTRY_BODY_BYTES { + return None; + } + let cache_control = parse_cache_control(response); + if cache_control.no_store { + return None; + } + let etag = header(response, "etag"); + let last_modified = header(response, "last-modified"); + if cache_control.no_cache && etag.is_none() && last_modified.is_none() { + // 强制再验证但无 validator 可发,缓存无意义 + return None; + } + if cache_control.max_age.is_none() && etag.is_none() && last_modified.is_none() { + // 无新鲜度且无 validator:不缓存(简化档不认 Expires) + return None; + } + let vary_ua = match vary_policy(response, request) { + VaryPolicy::NotCacheable => return None, + VaryPolicy::Unconstrained => None, + VaryPolicy::UserAgent(ua) => Some(ua), + }; + Some(CacheEntry { + response: response.clone(), + stored_at: Instant::now(), + max_age: cache_control.max_age, + must_revalidate: cache_control.no_cache, + etag, + last_modified, + vary_ua, + last_used: 0, + }) +} + +/// `Vary` 处置:`Unconstrained`——无 Vary(或空值)→ 自由缓存;`UserAgent`—— +/// 仅 `User-Agent` → 携带填充请求的 UA(可能为无 UA 头);`NotCacheable`—— +/// 含 `User-Agent` 以外字段(或 `*`)→ 整条不缓存。 +enum VaryPolicy { + Unconstrained, + UserAgent(Option<String>), + NotCacheable, +} + +fn vary_policy(response: &Response, request: &Request) -> VaryPolicy { + let Some(vary) = header(response, "vary") else { + return VaryPolicy::Unconstrained; + }; + let mut saw_user_agent = false; + for field in vary.split(',') { + let field = field.trim(); + if field.is_empty() { + continue; + } + if field.eq_ignore_ascii_case("user-agent") { + saw_user_agent = true; + } else { + return VaryPolicy::NotCacheable; + } + } + if saw_user_agent { + VaryPolicy::UserAgent( + request + .headers + .iter() + .find(|(name, _)| name.eq_ignore_ascii_case("user-agent")) + .map(|(_, value)| value.clone()), + ) + } else { + VaryPolicy::Unconstrained + } +} + +/// `Vary: User-Agent` 一致性:条目设了 UA 约束时,请求 UA 必须与填充时一致。 +fn vary_matches(entry: &CacheEntry, request: &Request) -> bool { + let Some(fill_ua) = &entry.vary_ua else { + return true; + }; + let request_ua = request + .headers + .iter() + .find(|(name, _)| name.eq_ignore_ascii_case("user-agent")) + .map(|(_, value)| value.as_str()); + request_ua == fill_ua.as_deref() +} + +struct CacheControl { + no_store: bool, + no_cache: bool, + max_age: Option<Duration>, +} + +/// 解析 `Cache-Control`(可多条,指令逗号分隔;非法值忽略)。 +fn parse_cache_control(response: &Response) -> CacheControl { + let mut parsed = CacheControl { + no_store: false, + no_cache: false, + max_age: None, + }; + for (name, value) in &response.headers { + if !name.eq_ignore_ascii_case("cache-control") { + continue; + } + for directive in value.split(',') { + let directive = directive.trim(); + if directive.eq_ignore_ascii_case("no-store") { + parsed.no_store = true; + } else if directive.eq_ignore_ascii_case("no-cache") { + parsed.no_cache = true; + } else if let Some(seconds) = directive + .split_once('=') + .filter(|(name, _)| name.trim().eq_ignore_ascii_case("max-age")) + .and_then(|(_, value)| value.trim().parse::<u64>().ok()) + { + parsed.max_age = Some(Duration::from_secs(seconds)); + } + } + } + parsed +} + +/// 取第一个同名响应头(名字大小写不敏感)。 +fn header(response: &Response, name: &str) -> Option<String> { + response + .headers + .iter() + .find(|(key, _)| key.eq_ignore_ascii_case(name)) + .map(|(_, value)| value.clone()) +} + +#[cfg(test)] +mod tests { + use super::*; + use crate::ReqwestFetcher; + use crate::test_loopback::{Server, request_path, respond}; + + fn fetcher() -> CachedFetcher<ReqwestFetcher> { + CachedFetcher::new(ReqwestFetcher::new().expect("fetcher")) + } + + fn get(fetcher: &CachedFetcher<ReqwestFetcher>, url: &str) -> Response { + fetcher + .fetch(&Request { + url: url.to_owned(), + method: Method::Get, + headers: Vec::new(), + }) + .expect("fetch") + } + + fn get_with_ua(fetcher: &CachedFetcher<ReqwestFetcher>, url: &str, ua: &str) -> Response { + fetcher + .fetch(&Request { + url: url.to_owned(), + method: Method::Get, + headers: vec![("User-Agent".to_owned(), ua.to_owned())], + }) + .expect("fetch") + } + + /// 首次未命中走网络;新鲜度内二次请求命中缓存(服务器只收到一次请求)。 + #[test] + fn fresh_entry_is_served_from_cache_after_first_miss() { + let server = Server::start(1, |_, _| { + respond(200, "OK", &[("Cache-Control", "max-age=60")], b"v1") + }); + let url = format!("{}/doc", server.base()); + let fetcher = fetcher(); + + let first = get(&fetcher, &url); + assert_eq!(first.body, b"v1"); + assert_eq!(server.requests().len(), 1); // 首次未命中:走网络 + + let second = get(&fetcher, &url); + assert_eq!(second.status, 200); + assert_eq!(second.body, b"v1"); // 命中:内容一致 + assert_eq!(second.final_url, first.final_url); + assert_eq!(server.requests().len(), 1); // 服务器未再收到请求 + server.join(); + } + + /// 过期条目经 If-None-Match 再验证:304 后复用缓存体,对外仍是 200。 + #[test] + fn stale_entry_revalidates_with_304_and_reuses_body() { + let server = Server::start(2, |index, _| { + if index == 0 { + respond( + 200, + "OK", + &[("Cache-Control", "max-age=0"), ("ETag", "\"v1\"")], + b"stale-body", + ) + } else { + respond(304, "Not Modified", &[("ETag", "\"v1\"")], b"") + } + }); + let url = format!("{}/doc", server.base()); + let fetcher = fetcher(); + + let first = get(&fetcher, &url); + assert_eq!(first.body, b"stale-body"); + + // max-age=0:立即过期 → 必须再验证 + let second = get(&fetcher, &url); + assert_eq!(second.status, 200); + assert_eq!(second.body, b"stale-body"); // 304 → 缓存体复用 + + let requests = server.requests(); + assert_eq!(requests.len(), 2); + assert!( + requests[1] + .to_ascii_lowercase() + .contains("if-none-match: \"v1\""), + "二次请求应带条件头: {}", + requests[1] + ); + server.join(); + } + + /// 同时有 ETag 与 Last-Modified:再验证请求两个条件头都带。 + #[test] + fn revalidation_sends_both_validators() { + let server = Server::start(2, |index, _| { + if index == 0 { + respond( + 200, + "OK", + &[ + ("Cache-Control", "max-age=0"), + ("ETag", "\"v1\""), + ("Last-Modified", "Wed, 21 Oct 2026 07:28:00 GMT"), + ], + b"body", + ) + } else { + respond(304, "Not Modified", &[("ETag", "\"v1\"")], b"") + } + }); + let url = format!("{}/doc", server.base()); + let fetcher = fetcher(); + + get(&fetcher, &url); + let second = get(&fetcher, &url); + assert_eq!(second.body, b"body"); + + let requests = server.requests(); + assert_eq!(requests.len(), 2); + let head = requests[1].to_ascii_lowercase(); + assert!(head.contains("if-none-match"), "应带 If-None-Match: {head}"); + assert!( + head.contains("if-modified-since"), + "应带 If-Modified-Since: {head}" + ); + server.join(); + } + + /// no-cache 强制再验证:即使 max-age 未过也要发条件请求。 + #[test] + fn no_cache_forces_revalidation_even_when_fresh() { + let server = Server::start(2, |index, _| { + if index == 0 { + respond( + 200, + "OK", + &[ + ("Cache-Control", "no-cache, max-age=9999"), + ("ETag", "\"v1\""), + ], + b"A", + ) + } else { + respond(304, "Not Modified", &[("ETag", "\"v1\"")], b"") + } + }); + let url = format!("{}/doc", server.base()); + let fetcher = fetcher(); + + let first = get(&fetcher, &url); + assert_eq!(first.body, b"A"); + let second = get(&fetcher, &url); + assert_eq!(second.status, 200); + assert_eq!(second.body, b"A"); // 304 复用缓存体 + + assert_eq!(server.requests().len(), 2); // 尽管仍新鲜,仍发起了再验证 + server.join(); + } + + /// no-store 不缓存:两次请求都落到服务器。 + #[test] + fn no_store_is_never_cached() { + let server = Server::start(2, |_, _| { + respond(200, "OK", &[("Cache-Control", "no-store")], b"n") + }); + let url = format!("{}/doc", server.base()); + let fetcher = fetcher(); + + assert_eq!(get(&fetcher, &url).body, b"n"); + assert_eq!(get(&fetcher, &url).body, b"n"); + assert_eq!(server.requests().len(), 2); + server.join(); + } + + /// Vary 含 User-Agent 以外字段:不缓存。 + #[test] + fn vary_other_than_user_agent_is_not_cached() { + let server = Server::start(2, |_, _| { + respond( + 200, + "OK", + &[("Cache-Control", "max-age=60"), ("Vary", "Accept-Language")], + b"v", + ) + }); + let url = format!("{}/doc", server.base()); + let fetcher = fetcher(); + + assert_eq!(get(&fetcher, &url).body, b"v"); + assert_eq!(get(&fetcher, &url).body, b"v"); + assert_eq!(server.requests().len(), 2); + server.join(); + } + + /// Vary: User-Agent 可缓存;UA 一致命中,不同 UA 未命中。 + #[test] + fn vary_user_agent_matches_on_ua_equality() { + let server = Server::start(2, |_, _| { + respond( + 200, + "OK", + &[("Cache-Control", "max-age=60"), ("Vary", "User-Agent")], + b"ua-body", + ) + }); + let url = format!("{}/doc", server.base()); + let fetcher = fetcher(); + + get_with_ua(&fetcher, &url, "agent-a"); + let hit = get_with_ua(&fetcher, &url, "agent-a"); + assert_eq!(hit.body, b"ua-body"); + assert_eq!(server.requests().len(), 1); // 同 UA:命中 + + let miss = get_with_ua(&fetcher, &url, "agent-b"); + assert_eq!(miss.body, b"ua-body"); + assert_eq!(server.requests().len(), 2); // 不同 UA:未命中 + server.join(); + } + + /// 缓存键含 method:GET 已缓存不影响 HEAD 的独立键。 + #[test] + fn cache_key_includes_method() { + let server = Server::start(2, |index, head| { + if index == 0 { + assert!(head.starts_with("GET "), "首请求应为 GET: {head}"); + respond(200, "OK", &[("Cache-Control", "max-age=60")], b"get-body") + } else { + assert!(head.starts_with("HEAD "), "次请求应为 HEAD: {head}"); + respond(200, "OK", &[("Cache-Control", "max-age=60")], b"") + } + }); + let url = format!("{}/k", server.base()); + let fetcher = fetcher(); + + let got = get(&fetcher, &url); + assert_eq!(got.body, b"get-body"); + let headed = fetcher + .fetch(&Request { + url: url.clone(), + method: Method::Head, + headers: Vec::new(), + }) + .expect("head"); + assert_eq!(headed.body, b""); // HEAD 独立键:走到服务器(体空是 HEAD 语义) + assert_eq!(server.requests().len(), 2); + server.join(); + } + + /// 超容量 LRU 逐出:最久未使用的条目被逐出后再次抓取重新走网络, + /// 新条目仍命中。 + #[test] + fn lru_evicts_least_recently_used_beyond_capacity() { + let server = Server::start(MAX_CACHE_ENTRIES + 2, |_, head| { + respond( + 200, + "OK", + &[("Cache-Control", "max-age=60")], + request_path(head).as_bytes(), + ) + }); + let url = |name: &str| format!("{}/e{name}", server.base()); + let fetcher = fetcher(); + + // 填满容量再多放一个:最早的 /e00 被逐出 + get(&fetcher, &url("00")); + for i in 1..=MAX_CACHE_ENTRIES { + get(&fetcher, &url(&format!("{i:02}"))); + } + assert_eq!(server.requests().len(), MAX_CACHE_ENTRIES + 1); + + // 新条目仍命中:不产生请求 + let recent_name = format!("{MAX_CACHE_ENTRIES:02}"); + let recent = get(&fetcher, &url(&recent_name)); + assert_eq!(recent.body, format!("/e{recent_name}").into_bytes()); + assert_eq!(server.requests().len(), MAX_CACHE_ENTRIES + 1); + + // 被逐出的最旧条目:重新走网络 + let evicted = get(&fetcher, &url("00")); + assert_eq!(evicted.body, b"/e00"); + assert_eq!(server.requests().len(), MAX_CACHE_ENTRIES + 2); + server.join(); + } + + /// 非 200 不缓存:404 两次都走网络。 + #[test] + fn non_200_is_not_cached() { + let server = Server::start(2, |_, _| respond(404, "Not Found", &[], b"missing")); + let url = format!("{}/missing", server.base()); + let fetcher = fetcher(); + + assert_eq!(get(&fetcher, &url).status, 404); + assert_eq!(get(&fetcher, &url).status, 404); + assert_eq!(server.requests().len(), 2); + server.join(); + } + + /// 超过单条体积上限的响应不缓存。 + #[test] + fn oversized_body_is_not_cached() { + let big = vec![b'x'; MAX_CACHE_ENTRY_BODY_BYTES + 1]; + let server = Server::start(2, move |_, _| { + respond(200, "OK", &[("Cache-Control", "max-age=60")], &big) + }); + let url = format!("{}/big", server.base()); + let fetcher = fetcher(); + + assert_eq!( + get(&fetcher, &url).body.len(), + MAX_CACHE_ENTRY_BODY_BYTES + 1 + ); + assert_eq!( + get(&fetcher, &url).body.len(), + MAX_CACHE_ENTRY_BODY_BYTES + 1 + ); + assert_eq!(server.requests().len(), 2); // 未被缓存 + server.join(); + } +} diff --git a/crates/nexty-network/src/decode.rs b/crates/nexty-network/src/decode.rs new file mode 100644 index 0000000..272dca6 --- /dev/null +++ b/crates/nexty-network/src/decode.rs @@ -0,0 +1,538 @@ +//! 主文档字符编码探测与解码(feature `decode`)。 +//! +//! 优先级链(本轮 goal 固定):HTTP header `Content-Type` 的 `charset` 参数、 +//! BOM(UTF-8 / UTF-16LE / UTF-16BE)、`<meta charset>` / http-equiv 预扫 +//! (前 [`MAX_PRESCAN_BYTES`] 字节)、默认 UTF-8,取第一个命中的层。 +//! 编码标签 → 解码器由 `encoding_rs` 提供(WHATWG Encoding Standard 的 +//! Firefox 实现);本模块不引入编码自动探测(chardetng 类),样式表不在本层解码。 +//! +//! 与 WHATWG HTML §13.2.3「Determining the character encoding」的偏差:不实现 +//! 用户显式覆盖、父浏览上下文继承、自动探测等步骤;预扫是规范 §13.2.3.5 的 +//! 简化档(见 [`prescan_charset`])。 +//! +//! 已知偏差:HTTP charset 层按「无 BOM 处理」解码——`Encoding::decode` 的 BOM +//! 嗅探会覆盖所选编码,违反 HTTP > BOM 的优先级——解码后剥掉前导 U+FEFF,使 +//! BOM 字节不进入文本;若 HTTP 指定的编码与 BOM 编码族不同(如 charset=GBK 而 +//! 字节流带 UTF-8 BOM),BOM 字节按该编码解出为杂字,不做特殊处理。 + +use encoding_rs::{Encoding, UTF_8}; + +/// meta 预扫只看前多少字节(WHATWG HTML §13.2.3.5 prescan 的上限)。 +pub const MAX_PRESCAN_BYTES: usize = 1024; + +/// 一次解码的结果。 +/// +/// `encoding` 是实际采用的编码名(encoding_rs 的规范名,如 `UTF-8`、`GBK`、 +/// `UTF-16LE`),供样式表等消费方按文档编码降级。 +#[derive(Debug, Clone, PartialEq, Eq)] +pub struct DecodedDocument { + /// 解码后的文本;非法字节按 WHATWG Encoding 的替换语义兜底,不会失败。 + pub text: String, + /// 实际采用的编码名。 + pub encoding: &'static str, +} + +/// 按四层优先级把响应体字节解码为文本。 +/// +/// `content_type` 传响应 `Content-Type` 头的原始值(可为空)。解码永不失败: +/// 未知编码标签视同该层未命中落到下一层;非法字节序列由替换字符兜底。 +/// +/// ``` +/// use nexty_network::decode_document; +/// +/// let doc = decode_document(Some("text/html; charset=gbk"), &[0xD6, 0xD0]); +/// assert_eq!(doc.text, "中"); +/// assert_eq!(doc.encoding, "GBK"); +/// ``` +pub fn decode_document(content_type: Option<&str>, body: &[u8]) -> DecodedDocument { + // 1. HTTP header Content-Type charset。decode() 的 BOM 嗅探会覆盖所选 + // 编码(违反 HTTP > BOM),故用无 BOM 处理入口,随后剥前导 U+FEFF。 + if let Some(encoding) = content_type + .and_then(charset_from_content_type) + .and_then(|label| Encoding::for_label(label.as_bytes())) + { + let (text, _) = encoding.decode_without_bom_handling(body); + return DecodedDocument { + text: strip_leading_bom_char(&text), + encoding: encoding.name(), + }; + } + // 2. BOM(UTF-8 / UTF-16LE / UTF-16BE)。decode() 自带 BOM 嗅探与剥离。 + if let Some(encoding) = bom_encoding(body) { + let (text, encoding, _) = encoding.decode(body); + return DecodedDocument { + text: text.into_owned(), + encoding: encoding.name(), + }; + } + // 3. meta charset / http-equiv 预扫(前 MAX_PRESCAN_BYTES 字节)。 + // 此时字节流已无 BOM 前缀,decode() 与无 BOM 入口等价。 + if let Some(encoding) = prescan_charset(&body[..body.len().min(MAX_PRESCAN_BYTES)]) { + let (text, encoding, _) = encoding.decode(body); + return DecodedDocument { + text: text.into_owned(), + encoding: encoding.name(), + }; + } + // 4. 默认 UTF-8 + let (text, _, _) = UTF_8.decode(body); + DecodedDocument { + text: text.into_owned(), + encoding: UTF_8.name(), + } +} + +/// 解码后剥掉前导 U+FEFF(BOM 字节在编码一致的解码下会变成该字符)。 +fn strip_leading_bom_char(text: &str) -> String { + match text.strip_prefix('\u{FEFF}') { + Some(rest) => rest.to_owned(), + None => text.to_owned(), + } +} + +/// BOM 嗅探:只认 WHATWG Encoding Standard 的三种 BOM。 +fn bom_encoding(body: &[u8]) -> Option<&'static Encoding> { + if body.starts_with(&[0xEF, 0xBB, 0xBF]) { + Some(encoding_rs::UTF_8) + } else if body.starts_with(&[0xFF, 0xFE]) { + Some(encoding_rs::UTF_16LE) + } else if body.starts_with(&[0xFE, 0xFF]) { + Some(encoding_rs::UTF_16BE) + } else { + None + } +} + +/// 从 `Content-Type` 头取 `charset` 参数(如 `text/html; charset=GBK`)。 +/// 无参数或空值 → `None`;允许 `=` 两侧空白,引号按惯例剥掉。 +fn charset_from_content_type(content_type: &str) -> Option<String> { + for part in content_type.split(';') { + let part = part.trim(); + let Some(name) = part.get(..7) else { + continue; + }; + if !name.eq_ignore_ascii_case("charset") { + continue; + } + let Some(value) = part[7..].trim_start().strip_prefix('=') else { + continue; + }; + let value = value.trim_matches(|c: char| c.is_whitespace() || c == '"' || c == '\''); + if !value.is_empty() { + return Some(value.to_owned()); + } + } + None +} + +/// 从 http-equiv meta 的 `content` 值里取编码标签(WHATWG HTML §13.2.3.5 +/// 「getting an encoding」简化档):大小写不敏感找 `charset`,跳过空白与 `=`, +/// 取引号内或至空白 / `;` 为止的标签;`charset` 后不跟 `=` 则继续找下一处。 +fn charset_from_content(content: &str) -> Option<String> { + let lower = content.to_ascii_lowercase(); + let mut from = 0; + while let Some(found) = lower[from..].find("charset") { + let start = from + found; + let after = content.get(start + "charset".len()..)?; + let Some(value) = after.trim_start().strip_prefix('=') else { + from = start + "charset".len(); + continue; + }; + let value = value.trim_start(); + for quote in ['"', '\''] { + if let Some(inner) = value.strip_prefix(quote) { + return inner + .find(quote) + .map(|end| inner[..end].to_owned()) + .filter(|label| !label.is_empty()); + } + } + let end = value + .find(|c: char| c.is_whitespace() || c == ';') + .unwrap_or(value.len()); + return if value[..end].is_empty() { + None + } else { + Some(value[..end].to_owned()) + }; + } + None +} + +/// WHATWG HTML §13.2.3.5「prescan a byte stream to determine its encoding」 +/// 简化档:逐标签扫描,识别 `<meta charset=…>` 与 +/// `<meta http-equiv=content-type content=…charset=…>`(属性顺序无关), +/// 跳过注释 / DOCTYPE / bogus comment;第一个能解析出**已知**编码标签的 +/// `<meta>` 胜出(未知标签继续向后扫,规范同义);标签未闭合(EOF)终止。 +fn prescan_charset(head: &[u8]) -> Option<&'static Encoding> { + let mut i = 0; + while i < head.len() { + if head[i] != b'<' { + i += 1; + continue; + } + let Some(&next) = head.get(i + 1) else { + break; + }; + match next { + b'!' => { + // `<!--` 注释跳到 `-->`;其他 `<!`(DOCTYPE 等)跳到 `>` + if head.get(i + 2) == Some(&b'-') && head.get(i + 3) == Some(&b'-') { + let search = i + 4; + i = match find_subslice(&head[search.min(head.len())..], b"-->") { + Some(pos) => search + pos + 3, + None => head.len(), + }; + } else { + i = match head[i..].iter().position(|&byte| byte == b'>') { + Some(pos) => i + pos + 1, + None => head.len(), + }; + } + } + b'?' => { + // bogus comment(`<?xml …?>`):跳到 `>` + i = match head[i..].iter().position(|&byte| byte == b'>') { + Some(pos) => i + pos + 1, + None => head.len(), + }; + } + byte if byte.is_ascii_alphabetic() => { + let Some(tag) = scan_tag(head, i) else { + break; // 标签未闭合:EOF 终止预扫 + }; + if tag.name == "meta" + && let Some(encoding) = meta_charset(&tag.attrs) + .and_then(|label| Encoding::for_label(label.as_bytes())) + { + return Some(encoding); + } + i = tag.end; + } + _ => i += 1, + } + } + None +} + +fn find_subslice(haystack: &[u8], needle: &[u8]) -> Option<usize> { + haystack + .windows(needle.len()) + .position(|window| window == needle) +} + +/// 预扫解析出的开始标签。 +struct ScannedTag { + /// 小写标签名。 + name: String, + /// 属性表(小写属性名,保留原值)。 + attrs: Vec<(String, String)>, + /// 标签后位置(`>` 的下一个字节)。 + end: usize, +} + +/// 从 `head[start] == b'<'` 起解析一个开始标签。标签未闭合(EOF)返回 `None`。 +fn scan_tag(head: &[u8], start: usize) -> Option<ScannedTag> { + let is_separator = + |byte: u8| matches!(byte, b' ' | b'\t' | b'\n' | b'\x0C' | b'\r' | b'/' | b'>'); + let is_space = |byte: u8| matches!(byte, b' ' | b'\t' | b'\n' | b'\x0C' | b'\r'); + + let mut i = start + 1; // 跳过 '<' + let name_start = i; + while i < head.len() && !is_separator(head[i]) { + i += 1; + } + let name = String::from_utf8_lossy(&head[name_start..i]).to_ascii_lowercase(); + let mut attrs: Vec<(String, String)> = Vec::new(); + loop { + // 跳过空白与斜杠(自闭合 `/` 视为分隔符,简化档不单独区分) + while i < head.len() && (is_space(head[i]) || head[i] == b'/') { + i += 1; + } + let Some(&byte) = head.get(i) else { + return None; // EOF + }; + if byte == b'>' { + return Some(ScannedTag { + name, + attrs, + end: i + 1, + }); + } + // 属性名 + let attr_start = i; + while i < head.len() && !is_separator(head[i]) && head[i] != b'=' { + i += 1; + } + if i >= head.len() { + return None; // EOF + } + let attr_name = String::from_utf8_lossy(&head[attr_start..i]).to_ascii_lowercase(); + while i < head.len() && is_space(head[i]) { + i += 1; + } + let value = if head.get(i) == Some(&b'=') { + i += 1; + while i < head.len() && is_space(head[i]) { + i += 1; + } + match head.get(i) { + Some("e @ (b'"' | b'\'')) => { + i += 1; + let value_start = i; + while i < head.len() && head[i] != quote { + i += 1; + } + if i >= head.len() { + return None; // 引号未闭合:EOF 终止 + } + let value = String::from_utf8_lossy(&head[value_start..i]).into_owned(); + i += 1; // 跳过闭合引号 + value + } + _ => { + let value_start = i; + while i < head.len() && !is_space(head[i]) && head[i] != b'>' { + i += 1; + } + String::from_utf8_lossy(&head[value_start..i]).into_owned() + } + } + } else { + String::new() // 空属性语法 + }; + attrs.push((attr_name, value)); + } +} + +/// `<meta>` 的编码产出:优先 `charset` 属性;否则要求 `http-equiv=content-type` +/// 且从 `content` 属性取(WHATWG §13.2.3.5)。 +fn meta_charset(attrs: &[(String, String)]) -> Option<String> { + if let Some((_, value)) = attrs.iter().find(|(name, _)| name == "charset") { + return Some(value.clone()); + } + let is_content_type = attrs + .iter() + .any(|(name, value)| name == "http-equiv" && value.eq_ignore_ascii_case("content-type")); + if !is_content_type { + return None; + } + let content = attrs + .iter() + .find(|(name, _)| name == "content") + .map(|(_, value)| value.clone())?; + charset_from_content(&content) +} + +#[cfg(test)] +mod tests { + use super::*; + + /// GBK 编码的「中」。 + const GBK_ZHONG: &[u8] = &[0xD6, 0xD0]; + + // ---- 第 1 层:HTTP Content-Type charset ---- + + #[test] + fn http_charset_gbk_decodes() { + let doc = decode_document(Some("text/html; charset=GBK"), GBK_ZHONG); + assert_eq!(doc.text, "中"); + assert_eq!(doc.encoding, "GBK"); + } + + #[test] + fn http_charset_wins_over_bom() { + // UTF-8 BOM 在前也不改变所选编码:HTTP 层优先于 BOM 层 + let mut body = vec![0xEF, 0xBB, 0xBF]; + body.extend_from_slice(GBK_ZHONG); + let doc = decode_document(Some("text/html; charset=gbk"), &body); + assert_eq!(doc.encoding, "GBK"); + } + + #[test] + fn http_charset_wins_over_meta() { + let mut body = b"<meta charset=\"utf-8\">".to_vec(); + body.extend_from_slice(GBK_ZHONG); + let doc = decode_document(Some("text/html; charset=gbk"), &body); + assert_eq!(doc.encoding, "GBK"); + } + + #[test] + fn http_charset_utf8_strips_bom_bytes() { + // BOM 作为编码选择器让位 HTTP,但 BOM 字节本身不应进入文本 + let mut body = vec![0xEF, 0xBB, 0xBF]; + body.extend_from_slice(b"x"); + let doc = decode_document(Some("text/html; charset=utf-8"), &body); + assert_eq!(doc.text, "x"); + assert_eq!(doc.encoding, "UTF-8"); + } + + #[test] + fn http_charset_without_param_falls_to_next_layer() { + // 无 charset 参数 → 落到 BOM / meta 层 + let mut body = GBK_ZHONG.to_vec(); + body.extend_from_slice(b"<meta charset=gbk>"); + let doc = decode_document(Some("text/html"), &body); + assert_eq!(doc.encoding, "GBK"); + } + + #[test] + fn http_unknown_label_falls_to_meta() { + let mut body = b"<meta charset=gbk>".to_vec(); + body.extend_from_slice(GBK_ZHONG); + let doc = decode_document(Some("text/html; charset=not-a-real-label"), &body); + assert_eq!(doc.encoding, "GBK"); + } + + // ---- 第 2 层:BOM ---- + + #[test] + fn bom_utf8_wins_over_meta() { + let mut body = vec![0xEF, 0xBB, 0xBF]; + body.extend_from_slice(b"<meta charset=\"gbk\">\xE4\xB8\xAD"); + let doc = decode_document(None, &body); + assert!(doc.text.contains("中")); + assert_eq!(doc.encoding, "UTF-8"); + } + + #[test] + fn bom_utf16le_decodes() { + let mut body = vec![0xFF, 0xFE]; + body.extend_from_slice(&[0x2D, 0x4E]); // 中 (UTF-16LE) + let doc = decode_document(None, &body); + assert_eq!(doc.text, "中"); + assert_eq!(doc.encoding, "UTF-16LE"); + } + + #[test] + fn bom_utf16be_decodes() { + let mut body = vec![0xFE, 0xFF]; + body.extend_from_slice(&[0x4E, 0x2D]); // 中 (UTF-16BE) + let doc = decode_document(None, &body); + assert_eq!(doc.text, "中"); + assert_eq!(doc.encoding, "UTF-16BE"); + } + + // ---- 第 3 层:meta 预扫 ---- + + #[test] + fn meta_charset_unquoted_and_single_quoted() { + for head in [ + &b"<meta charset=gbk>"[..], + b"<meta charset='gbk'>", + b"<meta charset=\"gbk\">", + b"<META CHARSET = \"GBK\" >", + ] { + let mut body = head.to_vec(); + body.extend_from_slice(GBK_ZHONG); + let doc = decode_document(None, &body); + assert_eq!( + doc.encoding, + "GBK", + "head: {}", + String::from_utf8_lossy(head) + ); + assert!(doc.text.ends_with("中")); + } + } + + #[test] + fn meta_http_equiv_extracts_charset() { + let mut body = + b"<meta http-equiv=\"Content-Type\" content=\"text/html; charset=gbk\">".to_vec(); + body.extend_from_slice(GBK_ZHONG); + let doc = decode_document(None, &body); + assert_eq!(doc.encoding, "GBK"); + assert!(doc.text.ends_with("中")); + } + + #[test] + fn meta_http_equiv_attribute_order_free() { + // content 在前、http-equiv 在后,属性值不带引号 + let mut body = b"<meta content=text/html;charset=gbk http-equiv=Content-Type>".to_vec(); + body.extend_from_slice(GBK_ZHONG); + let doc = decode_document(None, &body); + assert_eq!(doc.encoding, "GBK"); + } + + #[test] + fn meta_charset_must_come_within_1024_bytes() { + // 长注释把 meta 推出 1024 字节窗口 → 不再命中,回落默认 UTF-8 + let mut body = b"<!--".to_vec(); + body.extend(std::iter::repeat_n(b'x', 1030)); + body.extend_from_slice(b"--><meta charset=\"gbk\">"); + body.extend_from_slice(GBK_ZHONG); + let doc = decode_document(None, &body); + assert_eq!(doc.encoding, "UTF-8"); + } + + #[test] + fn comment_hidden_meta_is_ignored() { + let body = b"<!-- <meta charset=gbk> --><meta charset=\"utf-8\">\xE4\xB8\xAD".to_vec(); + let doc = decode_document(None, &body); + assert_eq!(doc.encoding, "UTF-8"); + assert!(doc.text.contains("中")); + } + + #[test] + fn multiple_metas_first_known_label_wins() { + // 第一个 meta 的标签未知:继续向后扫(规范语义),第二个命中 + let mut body = b"<meta charset=bogus-label><meta charset=gbk>".to_vec(); + body.extend_from_slice(GBK_ZHONG); + let doc = decode_document(None, &body); + assert_eq!(doc.encoding, "GBK"); + } + + // ---- 第 4 层:默认 UTF-8 ---- + + #[test] + fn no_hints_defaults_to_utf8() { + let doc = decode_document(None, "中".as_bytes()); + assert_eq!(doc.text, "中"); + assert_eq!(doc.encoding, "UTF-8"); + } + + #[test] + fn invalid_bytes_are_replaced_without_panic() { + let doc = decode_document(None, &[0x80, b'a']); + assert_eq!(doc.text, "\u{FFFD}a"); + assert_eq!(doc.encoding, "UTF-8"); + } + + #[test] + fn empty_body_decodes_to_empty_text() { + let doc = decode_document(None, b""); + assert_eq!(doc.text, ""); + assert_eq!(doc.encoding, "UTF-8"); + } + + // ---- Content-Type 解析 ---- + + #[test] + fn charset_from_content_type_cases() { + assert_eq!( + charset_from_content_type("text/html; charset=GBK").as_deref(), + Some("GBK") + ); + assert_eq!( + charset_from_content_type("text/html;charset=\"gb18030\"").as_deref(), + Some("gb18030") + ); + assert_eq!( + charset_from_content_type("text/html; Charset = Shift_JIS ").as_deref(), + Some("Shift_JIS") + ); + assert_eq!(charset_from_content_type("text/html"), None); + assert_eq!(charset_from_content_type("text/html; charset="), None); + } + + #[test] + fn charset_from_content_restarts_on_missing_equals() { + // 第一处 "charset" 后不跟 =:继续找下一处 + assert_eq!( + charset_from_content("the charset here; charset=gbk").as_deref(), + Some("gbk") + ); + assert_eq!(charset_from_content("no encoding here"), None); + } +} diff --git a/crates/nexty-network/src/lib.rs b/crates/nexty-network/src/lib.rs index 82d6022..dad65c0 100644 --- a/crates/nexty-network/src/lib.rs +++ b/crates/nexty-network/src/lib.rs @@ -1,17 +1,20 @@ //! Nexty 网络 facade。 //! -//! 上游:`reqwest`(MIT/Apache-2.0),提供 TLS、重定向与连接池。 -//! 决策见 `docs/decisions/2026-10-01-crate-selection.md`。 +//! 上游:`reqwest`(MIT/Apache-2.0,抓取后端)、`url`(MIT/Apache-2.0,WHATWG URL +//! 解析)、`encoding_rs`(MIT/Apache-2.0,WHATWG Encoding 解码)。选型决策见 +//! `docs/decisions/2026-10-01-crate-selection.md` 与 `docs/decisions/2026-10-31-url.md`、 +//! `docs/decisions/2026-10-31-encoding.md`。 //! //! 接口当前是同步的:导航与子资源抓取由 chrome 层串行驱动,异步入口等到确有 //! 并发需求时再加。 //! -//! 上游类型一律不得出现在本 crate 的 pub 导出中(AGENTS.md 硬规则); -//! [`ReqwestFetcher`] 持有上游 client,对外只暴露 [`NetworkFetcher`] trait 与 -//! 自有请求 / 响应类型。 +//! 上游类型一律不得出现在本 crate 的 pub 导出中(AGENTS.md 硬规则): +//! [`ReqwestFetcher`] 持有上游 client,[`Url`] 包住 `url::Url`,解码入口以 +//! [`DecodedDocument`] 输出文本,对外只暴露本 crate 的类型。 //! -//! **Feature**:抓取后端与 URL 解析分别由 `fetch` / `resolve` 两个 feature 控制, -//! 默认全开。两者都依赖 reqwest 的 `Url` 类型,故 `resolve` 也隐含 `dep:reqwest`。 +//! **Feature**:能力按四个 feature 拆分,默认全开——`fetch`(reqwest 抓取后端与 +//! trait / 请求 / 响应类型)、`resolve`(`url` 直依赖,不拉 reqwest)、`decode` +//! (encoding_rs 编码探测与解码)、`cache`(内存 HTTP 缓存,隐含 `fetch`)。 #![forbid(unsafe_code)] @@ -20,7 +23,7 @@ use std::time::Duration; /// HTTP 方法。当前只覆盖导航与子资源抓取所需的最小集合。 #[cfg(feature = "fetch")] -#[derive(Debug, Clone, Copy, PartialEq, Eq)] +#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)] pub enum Method { /// GET。 Get, @@ -52,6 +55,10 @@ pub struct Response { pub headers: Vec<(String, String)>, /// 响应体字节。 pub body: Vec<u8>, + /// 最终响应 URL:跟随重定向后的落点,无重定向时即请求 URL(WHATWG fetch 的 + /// final URL 语义)。文档 base 应取本字段——子资源相对地址按落点解析, + /// 不按原始请求 URL。 + pub final_url: String, } /// 抓取后端。 @@ -76,12 +83,62 @@ pub trait NetworkFetcher: Send + Sync { pub enum NetworkError { /// URL 无法解析,或协议不受支持。 InvalidUrl, - /// 连接或传输失败。 + /// 连接或传输失败(含重定向环与超过重定向上限)。 Transport, /// 超过超时限制。 Timeout, } +/// WHATWG URL 的最小自有封装(`url` crate 的类型不外泄,AGENTS.md 硬规则)。 +/// +/// 只暴露当前需要的三个操作:解析、以自身为 base 拼接、取字符串。 +/// 选型见 `docs/decisions/2026-10-31-url.md`。 +#[cfg(feature = "resolve")] +#[derive(Debug, Clone, PartialEq, Eq)] +pub struct Url { + inner: url::Url, +} + +#[cfg(feature = "resolve")] +impl Url { + /// 解析绝对 URL。 + /// + /// # Errors + /// + /// 输入不是合法绝对 URL(WHATWG basic URL parsing 失败)时返回 + /// [`NetworkError::InvalidUrl`]。 + pub fn parse(input: &str) -> Result<Self, NetworkError> { + url::Url::parse(input) + .map(|inner| Self { inner }) + .map_err(|_| NetworkError::InvalidUrl) + } + + /// 以自身为基准解析 `target`,返回新 URL。语义同 [`resolve`]:绝对 URL + /// 原样返回,协议相对(`//host/x`)继承协议,`/x` / `x` / `../x` / `?q` / + /// `#f` 按路径语义解析;空串解析为自身(opaque scheme 的 `join("")` 会 + /// 失败,这里显式短路,与 [`resolve`] 一致)。 + /// + /// # Errors + /// + /// 拼接失败时返回 [`NetworkError::InvalidUrl`]。 + pub fn join(&self, target: &str) -> Result<Self, NetworkError> { + if target.is_empty() { + return Ok(Self { + inner: self.inner.clone(), + }); + } + self.inner + .join(target) + .map(|inner| Self { inner }) + .map_err(|_| NetworkError::InvalidUrl) + } + + /// 序列化后的完整 URL 字符串。 + pub fn as_str(&self) -> &str { + self.inner.as_str() + } +} + /// 以 `base` 为基准解析 `target`,返回绝对 URL。 /// /// 子资源(外链样式表、图片、表单 action…)在文档里以相对形式出现,需按 @@ -108,20 +165,45 @@ pub enum NetworkError { /// [`NetworkError::InvalidUrl`]。 #[cfg(feature = "resolve")] pub fn resolve(base: &str, target: &str) -> Result<String, NetworkError> { - let base = reqwest::Url::parse(base).map_err(|_| NetworkError::InvalidUrl)?; - // 空 target 解析为 base 自身。opaque scheme(about: / data:)的 - // `join("")` 会失败(无 hierarchical path 可继承),这里显式短路。 - if target.is_empty() { - return Ok(base.into()); - } - let resolved = base.join(target).map_err(|_| NetworkError::InvalidUrl)?; - Ok(resolved.into()) + Url::parse(base)? + .join(target) + .map(|url| url.as_str().to_owned()) +} + +/// 一次请求最多跟随的重定向跳数(与 WHATWG fetch 的 redirect count 上限同值)。 +/// 超过即失败,映射 [`NetworkError::Transport`]。 +#[cfg(feature = "fetch")] +pub const MAX_REDIRECTS: usize = 10; + +/// 显式重定向 policy:跟随 ≤ [`MAX_REDIRECTS`] 跳 + 防环。 +/// +/// `Policy::custom` 不自带防环(reqwest 文档明确要求 custom 自行处理),这里 +/// 用 `previous()` 历史判定:`previous()` 的首项是初始 URL,目标 URL 已出现在 +/// 历史中即成环。跳数判式与 `Policy::limited` 对齐(`previous()` 含初始 URL, +/// 故比较用 `>`)。两种失败都映射 [`NetworkError::Transport`]。 +#[cfg(feature = "fetch")] +fn redirect_policy() -> reqwest::redirect::Policy { + reqwest::redirect::Policy::custom(|attempt| { + if attempt + .previous() + .iter() + .any(|visited| visited == attempt.url()) + { + attempt.error("redirect loop detected") + } else if attempt.previous().len() > MAX_REDIRECTS { + attempt.error("too many redirects") + } else { + attempt.follow() + } + }) } /// [`NetworkFetcher`] 的 reqwest 实现。 /// -/// 重定向跟随使用 reqwest 默认策略(最多 10 次);TLS 使用 reqwest 默认的 -/// rustls 配置。[`ReqwestFetcher::with_timeout`] 可设置整请求超时,超时映射为 +/// 重定向语义显式:最多跟随 [`MAX_REDIRECTS`] 跳,且检测重定向环(目标 URL +/// 在本次请求链中重复出现即失败);两者都映射 [`NetworkError::Transport`], +/// 见 [`redirect_policy`]。TLS 使用 reqwest 默认的 rustls 配置。 +/// [`ReqwestFetcher::with_timeout`] 可设置整请求超时,超时映射为 /// [`NetworkError::Timeout`]。 #[cfg(feature = "fetch")] #[derive(Debug)] @@ -139,6 +221,7 @@ impl ReqwestFetcher { pub fn new() -> Result<Self, NetworkError> { Ok(Self { client: reqwest::blocking::Client::builder() + .redirect(redirect_policy()) .build() .map_err(transport_from_builder)?, }) @@ -152,6 +235,7 @@ impl ReqwestFetcher { pub fn with_timeout(timeout: Duration) -> Result<Self, NetworkError> { Ok(Self { client: reqwest::blocking::Client::builder() + .redirect(redirect_policy()) .timeout(timeout) .build() .map_err(transport_from_builder)?, @@ -189,12 +273,15 @@ impl NetworkFetcher for ReqwestFetcher { ) }) .collect(); + // 最终 URL 在消费响应体前取出(bytes() 会消费 Response) + let final_url = response.url().as_str().to_owned(); let body = response.bytes().map_err(map_request_error)?.to_vec(); Ok(Response { status, headers, body, + final_url, }) } } @@ -215,29 +302,175 @@ fn map_request_error(error: reqwest::Error) -> NetworkError { } } -// 测试混合覆盖抓取与URL 解析,需两个 feature 同时开启。 -#[cfg(all(test, feature = "fetch", feature = "resolve"))] -mod tests { - use super::*; +#[cfg(feature = "decode")] +mod decode; +#[cfg(feature = "decode")] +pub use decode::{DecodedDocument, MAX_PRESCAN_BYTES, decode_document}; + +#[cfg(feature = "cache")] +mod cache; +#[cfg(feature = "cache")] +pub use cache::{CachedFetcher, MAX_CACHE_ENTRIES, MAX_CACHE_ENTRY_BODY_BYTES}; + +// 测试共享基建:恰好服务 n 个请求的回环服务器(fetch 相关测试用)。 +#[cfg(all(test, feature = "fetch"))] +pub(crate) mod test_loopback { use std::io::{Read, Write}; use std::net::{TcpListener, TcpStream}; + use std::sync::{Arc, Mutex}; use std::thread::JoinHandle; - /// 起一个只应答一次的本地 HTTP 服务,返回其地址。 - fn serve_once(response: &'static [u8]) -> (String, JoinHandle<()>) { - let listener = TcpListener::bind("127.0.0.1:0").expect("bind loopback"); - let port = listener.local_addr().expect("addr").port(); - let handle = std::thread::spawn(move || { - if let Ok((mut stream, _)) = listener.accept() { - let mut buffer = [0u8; 4096]; - let _ = stream.read(&mut buffer); - let _ = stream.write_all(response); - let _ = stream.flush(); + /// 回环多请求测试服务器:恰好服务 `n` 个请求后线程退出。 + /// 每个请求回调 `handler(序号, 请求头原文)` 生成完整响应字节。 + pub(crate) struct Server { + base: String, + requests: Arc<Mutex<Vec<String>>>, + handle: JoinHandle<()>, + } + + impl Server { + pub(crate) fn start( + n: usize, + handler: impl Fn(usize, &str) -> Vec<u8> + Send + 'static, + ) -> Server { + let listener = TcpListener::bind("127.0.0.1:0").expect("bind loopback"); + let port = listener.local_addr().expect("addr").port(); + let requests: Arc<Mutex<Vec<String>>> = Arc::new(Mutex::new(Vec::new())); + let seen = requests.clone(); + let handle = std::thread::spawn(move || { + let mut served = 0usize; + while served < n { + let Ok((stream, _)) = listener.accept() else { + break; + }; + if serve_connection(stream, &handler, &seen, &mut served, n) { + break; + } + } + }); + Server { + base: format!("http://127.0.0.1:{port}"), + requests, + handle, } - }); - (format!("http://127.0.0.1:{port}/"), handle) + } + + pub(crate) fn base(&self) -> &str { + &self.base + } + + /// 已收到请求的请求头原文(按到达顺序)。 + pub(crate) fn requests(&self) -> Vec<String> { + self.requests.lock().expect("requests").clone() + } + + pub(crate) fn join(self) { + self.handle.join().expect("server thread"); + } + } + + /// 服务一条连接上的若干请求;返回 true 表示已达总请求数,服务器应退出。 + fn serve_connection( + mut stream: TcpStream, + handler: &impl Fn(usize, &str) -> Vec<u8>, + requests: &Mutex<Vec<String>>, + served: &mut usize, + total: usize, + ) -> bool { + let mut buffer: Vec<u8> = Vec::new(); + let mut chunk = [0u8; 4096]; + loop { + if *served >= total { + return true; + } + // 读到请求头结束(\r\n\r\n) + let head_end = loop { + if let Some(pos) = find(&buffer, b"\r\n\r\n") { + break pos; + } + match stream.read(&mut chunk) { + Ok(0) | Err(_) => return false, // 对端关闭,换连接或退出 + Ok(read) => buffer.extend_from_slice(&chunk[..read]), + } + }; + let head = String::from_utf8_lossy(&buffer[..head_end]).into_owned(); + // 请求体(本仓测试只发无体请求,仍按 Content-Length 读完以对齐 keep-alive) + let mut consumed = head_end + 4; + if let Some(len) = content_length(&head) { + let need = head_end + 4 + len; + while buffer.len() < need { + match stream.read(&mut chunk) { + Ok(0) | Err(_) => return false, + Ok(read) => buffer.extend_from_slice(&chunk[..read]), + } + } + consumed = need; + } + buffer.drain(..consumed); + requests.lock().expect("requests").push(head.clone()); + let response = handler(*served, &head); + let _ = stream.write_all(&response); + let _ = stream.flush(); + *served += 1; + } + } + + fn find(haystack: &[u8], needle: &[u8]) -> Option<usize> { + haystack + .windows(needle.len()) + .position(|window| window == needle) + } + + fn content_length(head: &str) -> Option<usize> { + head.lines() + .skip(1) + .take_while(|line| !line.is_empty()) + .find_map(|line| { + let (name, value) = line.split_once(':')?; + if name.trim().eq_ignore_ascii_case("content-length") { + value.trim().parse().ok() + } else { + None + } + }) + } + + /// 构造一个最小合法 HTTP/1.1 响应(显式 Content-Length,keep-alive)。 + pub(crate) fn respond( + status: u16, + reason: &str, + headers: &[(&str, &str)], + body: &[u8], + ) -> Vec<u8> { + let mut head = format!("HTTP/1.1 {status} {reason}\r\n"); + for (name, value) in headers { + head.push_str(&format!("{name}: {value}\r\n")); + } + head.push_str(&format!("Content-Length: {}\r\n\r\n", body.len())); + let mut bytes = head.into_bytes(); + bytes.extend_from_slice(body); + bytes + } + + /// 重定向响应(相对 Location)。 + pub(crate) fn redirect(status: u16, location: &str) -> Vec<u8> { + respond(status, "Redirect", &[("Location", location)], b"") } + /// 请求行里的目标路径。 + pub(crate) fn request_path(head: &str) -> &str { + head.split_whitespace().nth(1).unwrap_or("/") + } +} + +// 抓取回环测试(只需 fetch;resolve 语义测试见下方 resolve_tests)。 +#[cfg(all(test, feature = "fetch"))] +mod tests { + use super::*; + use std::io::Read; + use std::net::{TcpListener, TcpStream}; + use std::thread::JoinHandle; + /// 起一个接受连接但永不回应的服务(触发客户端超时)。 fn serve_silently() -> (String, JoinHandle<()>) { let listener = TcpListener::bind("127.0.0.1:0").expect("bind loopback"); @@ -263,11 +496,11 @@ mod tests { fn get_round_trips_status_headers_and_body() { let response_bytes = b"HTTP/1.1 200 OK\r\nContent-Type: text/plain\r\nX-Test: yes\r\n\r\nhello nexty"; - let (url, server) = serve_once(response_bytes); + let server = test_loopback::Server::start(1, |_, _| response_bytes.to_vec()); let response = fetcher() .fetch(&Request { - url, + url: format!("{}/", server.base()), method: Method::Get, headers: Vec::new(), }) @@ -287,26 +520,20 @@ mod tests { .any(|(name, value)| name == "x-test" && value == "yes") ); assert_eq!(response.body, b"hello nexty"); - server.join().expect("server thread"); + // 无重定向:final_url 即请求 URL(url crate 对空路径补 /) + assert_eq!(response.final_url, format!("{}/", server.base())); + server.join(); } #[test] fn head_request_sends_head_method() { // 校验请求行确实是 HEAD:服务端回读请求首行 - let listener = TcpListener::bind("127.0.0.1:0").expect("bind loopback"); - let port = listener.local_addr().expect("addr").port(); - let server = std::thread::spawn(move || { - let (mut stream, _) = listener.accept().expect("accept"); - let mut buffer = [0u8; 4096]; - let read = stream.read(&mut buffer).expect("read"); - let request_line = String::from_utf8_lossy(&buffer[..read]).into_owned(); - let _ = stream.write_all(b"HTTP/1.1 200 OK\r\nContent-Length: 0\r\n\r\n"); - request_line - }); + let server = + test_loopback::Server::start(1, |_, _| test_loopback::respond(200, "OK", &[], b"")); let response = fetcher() .fetch(&Request { - url: format!("http://127.0.0.1:{port}/"), + url: server.base().to_owned(), method: Method::Head, headers: Vec::new(), }) @@ -314,44 +541,35 @@ mod tests { assert_eq!(response.status, 200); assert!(response.body.is_empty()); - let request_line = server.join().expect("server thread"); + // 服务端记录的请求行校验方法确实是 HEAD + let requests = server.requests(); + assert_eq!(requests.len(), 1); assert!( - request_line.starts_with("HEAD / "), - "request line: {request_line}" + requests[0].starts_with("HEAD / "), + "request line: {}", + requests[0] ); + server.join(); } /// 请求头按给定顺序到达服务端(服务端把目标请求头回显进响应体)。 #[test] fn request_headers_reach_the_server() { - let listener = TcpListener::bind("127.0.0.1:0").expect("bind loopback"); - let port = listener.local_addr().expect("addr").port(); - let server = std::thread::spawn(move || { - let (mut stream, _) = listener.accept().expect("accept"); - let mut buffer = [0u8; 4096]; - let read = stream.read(&mut buffer).expect("read"); - let request = String::from_utf8_lossy(&buffer[..read]).into_owned(); + let server = test_loopback::Server::start(1, |_, head| { let echo = |name: &str| { - request - .lines() + head.lines() .skip(1) // 跳过请求行 .take_while(|line| !line.is_empty()) .find(|line| line.to_ascii_lowercase().starts_with(name)) .map_or_else(String::new, ToString::to_string) }; let body = format!("{}|{}", echo("x-nexty-marker"), echo("user-agent")); - let response = format!( - "HTTP/1.1 200 OK\r\nContent-Length: {}\r\n\r\n{}", - body.len(), - body - ); - let _ = stream.write_all(response.as_bytes()); - let _ = stream.flush(); + test_loopback::respond(200, "OK", &[], body.as_bytes()) }); let response = fetcher() .fetch(&Request { - url: format!("http://127.0.0.1:{port}/"), + url: server.base().to_owned(), method: Method::Get, headers: vec![("X-Nexty-Marker".to_owned(), "nexty-header-test".to_owned())], }) @@ -366,7 +584,7 @@ mod tests { body.to_ascii_lowercase().starts_with("x-nexty-marker"), "请求头顺序应保留: {body}" ); - server.join().expect("server thread"); + server.join(); } #[test] @@ -391,6 +609,180 @@ mod tests { assert_eq!(error, NetworkError::InvalidUrl); } + #[test] + fn unreachable_server_maps_to_transport() { + // 连一个确定无服务的回环端口(先取一个空闲端口再释放) + let listener = TcpListener::bind("127.0.0.1:0").expect("bind loopback"); + let port = listener.local_addr().expect("addr").port(); + drop(listener); + + let error = fetcher() + .fetch(&Request { + url: format!("http://127.0.0.1:{port}/"), + method: Method::Get, + headers: Vec::new(), + }) + .expect_err("connection refused"); + assert_eq!(error, NetworkError::Transport); + } + + #[test] + fn slow_server_maps_to_timeout() { + let (url, server) = serve_silently(); + let fetcher = ReqwestFetcher::with_timeout(Duration::from_millis(100)).expect("fetcher"); + + let error = fetcher + .fetch(&Request { + url, + method: Method::Get, + headers: Vec::new(), + }) + .expect_err("timeout"); + assert_eq!(error, NetworkError::Timeout); + server.join().expect("server thread"); + } + + #[test] + fn connection_failure_after_timeout_builder() { + // with_timeout 构造路径 + let fetcher = ReqwestFetcher::with_timeout(Duration::from_secs(5)).expect("fetcher"); + assert!( + fetcher + .fetch(&Request { + url: "not a url".to_owned(), + method: Method::Get, + headers: Vec::new(), + }) + .is_err() + ); + } + + /// 301 重定向:响应携带落点 final_url,且确实跟随了 Location。 + #[test] + fn redirect_301_exposes_final_url() { + let server = test_loopback::Server::start(2, |index, head| { + if index == 0 { + assert_eq!(test_loopback::request_path(head), "/"); + test_loopback::redirect(301, "/final") + } else { + assert_eq!(test_loopback::request_path(head), "/final"); + test_loopback::respond(200, "OK", &[], b"landing") + } + }); + + let response = fetcher() + .fetch(&Request { + url: format!("{}/", server.base()), + method: Method::Get, + headers: Vec::new(), + }) + .expect("fetch"); + + assert_eq!(response.status, 200); + assert_eq!(response.body, b"landing"); + assert_eq!(response.final_url, format!("{}/final", server.base())); + assert_eq!(server.requests().len(), 2); + server.join(); + } + + /// 302 重定向:同上(相对 Location 也由后端解析)。 + #[test] + fn redirect_302_exposes_final_url() { + let server = test_loopback::Server::start(2, |index, head| { + if index == 0 { + assert_eq!(test_loopback::request_path(head), "/"); + test_loopback::redirect(302, "/final") + } else { + assert_eq!(test_loopback::request_path(head), "/final"); + test_loopback::respond(200, "OK", &[], b"landing") + } + }); + + let response = fetcher() + .fetch(&Request { + url: format!("{}/", server.base()), + method: Method::Get, + headers: Vec::new(), + }) + .expect("fetch"); + + assert_eq!(response.status, 200); + assert_eq!(response.final_url, format!("{}/final", server.base())); + assert_eq!(server.requests().len(), 2); + server.join(); + } + + /// 重定向环:目标 URL 在请求链中重复出现即失败,不悬挂。 + #[test] + fn redirect_loop_fails_instead_of_hanging() { + let server = test_loopback::Server::start(1, |_, _| test_loopback::redirect(302, "/loop")); + + let error = fetcher() + .fetch(&Request { + url: format!("{}/loop", server.base()), + method: Method::Get, + headers: Vec::new(), + }) + .expect_err("redirect loop"); + + assert_eq!(error, NetworkError::Transport); + // 环在第二次跟随前被识破:只有初始请求到达服务器 + assert_eq!(server.requests().len(), 1); + server.join(); + } + + /// 重定向链超过上限:恰好跟随 MAX_REDIRECTS 跳后失败。 + #[test] + fn redirect_chain_stops_at_limit() { + let server = test_loopback::Server::start(MAX_REDIRECTS + 1, |index, _| { + test_loopback::redirect(302, &format!("/r{}", index + 1)) + }); + + let error = fetcher() + .fetch(&Request { + url: format!("{}/r0", server.base()), + method: Method::Get, + headers: Vec::new(), + }) + .expect_err("too many redirects"); + + assert_eq!(error, NetworkError::Transport); + // 初始 + MAX_REDIRECTS 次跟随 = MAX_REDIRECTS + 1 个请求 + assert_eq!(server.requests().len(), MAX_REDIRECTS + 1); + server.join(); + } + + /// 文档 base = 最终 URL:重定向落点后的相对子资源按落点解析。 + #[cfg(feature = "resolve")] + #[test] + fn relative_resolution_uses_final_url_after_redirect() { + let server = test_loopback::Server::start(2, |index, _| { + if index == 0 { + test_loopback::redirect(301, "/final/page.html") + } else { + test_loopback::respond(200, "OK", &[], b"<img src=probe.png>") + } + }); + + let response = fetcher() + .fetch(&Request { + url: format!("{}/", server.base()), + method: Method::Get, + headers: Vec::new(), + }) + .expect("fetch"); + + let probe = resolve(&response.final_url, "probe.png").expect("resolve"); + assert_eq!(probe, format!("{}/final/probe.png", server.base())); + server.join(); + } +} + +// URL 解析语义测试(只需 resolve,不依赖 fetch)。 +#[cfg(all(test, feature = "resolve"))] +mod resolve_tests { + use super::*; + /// 相对路径按 URL 标准解析(WHATWG basic URL parsing)。 #[test] fn resolve_handles_relative_paths() { @@ -473,51 +865,44 @@ mod tests { ); } + /// [`Url`] 封装:parse / join / as_str 与 resolve 同语义。 #[test] - fn unreachable_server_maps_to_transport() { - // 连一个确定无服务的回环端口(先取一个空闲端口再释放) - let listener = TcpListener::bind("127.0.0.1:0").expect("bind loopback"); - let port = listener.local_addr().expect("addr").port(); - drop(listener); - - let error = fetcher() - .fetch(&Request { - url: format!("http://127.0.0.1:{port}/"), - method: Method::Get, - headers: Vec::new(), - }) - .expect_err("connection refused"); - assert_eq!(error, NetworkError::Transport); + fn url_wrapper_parse_join_as_str() { + let base = Url::parse("https://example.test/dir/page.html").expect("parse"); + assert_eq!(base.as_str(), "https://example.test/dir/page.html"); + assert_eq!( + base.join("../img/a.png").expect("join").as_str(), + "https://example.test/img/a.png" + ); + assert_eq!( + base.join("/root.png").expect("join").as_str(), + "https://example.test/root.png" + ); + assert_eq!( + base.join("?q=1").expect("join").as_str(), + "https://example.test/dir/page.html?q=1" + ); + // 绝对 URL 原样 + assert_eq!( + base.join("https://other.test/x").expect("join").as_str(), + "https://other.test/x" + ); + // 非法输入 + assert!(Url::parse("not a url").is_err()); } + /// [`Url::join`] 空串解析为自身。 #[test] - fn slow_server_maps_to_timeout() { - let (url, server) = serve_silently(); - let fetcher = ReqwestFetcher::with_timeout(Duration::from_millis(100)).expect("fetcher"); - - let error = fetcher - .fetch(&Request { - url, - method: Method::Get, - headers: Vec::new(), - }) - .expect_err("timeout"); - assert_eq!(error, NetworkError::Timeout); - server.join().expect("server thread"); + fn url_wrapper_join_empty_returns_self() { + let base = Url::parse("https://example.test/dir/page.html").expect("parse"); + assert_eq!(base.join("").expect("join"), base.clone()); } + /// opaque scheme base:相对 join 失败、空 join 返回自身(与 resolve 一致)。 #[test] - fn connection_failure_after_timeout_builder() { - // with_timeout 构造路径 - let fetcher = ReqwestFetcher::with_timeout(Duration::from_secs(5)).expect("fetcher"); - assert!( - fetcher - .fetch(&Request { - url: "not a url".to_owned(), - method: Method::Get, - headers: Vec::new(), - }) - .is_err() - ); + fn url_wrapper_opaque_base_rejects_relative_join() { + let base = Url::parse("about:blank").expect("parse"); + assert_eq!(base.join("a.png"), Err(NetworkError::InvalidUrl)); + assert_eq!(base.join("").expect("join").as_str(), "about:blank"); } } diff --git a/docs/decisions/2026-10-31-encoding.md b/docs/decisions/2026-10-31-encoding.md new file mode 100644 index 0000000..8c398a1 --- /dev/null +++ b/docs/decisions/2026-10-31-encoding.md @@ -0,0 +1,61 @@ +# ADR: 主文档字符编码探测选用 `encoding_rs` + +- 日期:2026-10-31 +- 状态:已采纳 +- 背景:主文档此前用严格 `String::from_utf8` 解码,GBK / Shift_JIS 等非 UTF-8 + 页面直接解码失败进错误页。需要 WHATWG Encoding Standard 的编码标签表与 + 解码器,按「HTTP charset > BOM > meta 预扫 > UTF-8」四层优先级探测。导航 + 与网络完备轮(network 0.1.5 → 0.1.6)T2 落地(本 ADR 只覆盖 network 层的 + 解码入口;chrome 侧接线为 T5)。 + +## 候选 + +| 候选 | 许可证 | 结论 | +| --- | --- | --- | +| `encoding_rs` 0.8.42 | MIT OR Apache-2.0 | **采纳**。Firefox 维护的 WHATWG Encoding Standard 实现,标签表(`Encoding::for_label` 覆盖 `gbk` / `gb2312` / `shift_jis` 等全部标准标签)与解码器(替换字符语义、BOM 剥离)开箱即用;已是依赖树成员(reqwest 的 charset feature 传递依赖),直依赖化**零新增包** | +| `chardetng` | MIT OR Apache-2.0 | 否决(本轮):它是无元数据时的编码**自动探测**;本轮优先级链由 goal 固定,探测层不存在。后续若加「无任何提示时探测」再评估并另记 ADR | +| 自研编码表 + 解码器 | — | 否决:GBK / GB18030 等编码表体量巨大且语义细节(替换、BOM、UTF-16 字节序)正是「有成熟轮子不自己造」的典型 | + +## 决策 + +1. **依赖接线**:`decode = ["dep:encoding_rs"]`,独立 feature,不依赖 fetch + (纯字节 + 头值输入)。 +2. **解码入口**:`nexty_network::decode_document(content_type: Option<&str>, + body: &[u8]) -> DecodedDocument`(自有类型,`encoding_rs` 类型不外泄), + 返回文本与实际采用编码名(`&'static str`,encoding_rs 规范名)。 +3. **优先级链**(goal 固定):HTTP header `Content-Type` 的 `charset` 参数 > + BOM(UTF-8 / UTF-16LE / UTF-16BE)> `<meta charset>` / http-equiv 预扫 + (前 1024 字节,WHATWG HTML §13.2.3.5 的简化档)> 默认 UTF-8。每层未知 + 标签视同未命中落到下一层。 +4. **HTTP 层用无 BOM 处理解码**:`Encoding::decode` 自带 BOM 嗅探并可覆盖 + 所选编码,违反 HTTP > BOM 的优先级,故 HTTP 层走 + `decode_without_bom_handling`,解码后剥掉前导 U+FEFF(BOM 字节不进文本)。 +5. **边界**:只解码不编码;样式表不在本层解码(chrome 简化档:按文档解码 + 结果或 UTF-8,lossy 兜底);不实现规范的用户显式覆盖、父浏览上下文继承、 + 自动探测等步骤。 + +## 偏差清单 + +- 预扫是 WHATWG §13.2.3.5 的简化档:识别 `<meta charset>` 与 + `<meta http-equiv=content-type content=…charset=…>`(属性顺序无关、跳过 + 注释 / DOCTYPE / bogus comment),不实现完整字节级 prescan 状态机; +- HTTP 指定编码与 BOM 编码族不同时(如 charset=GBK 而字节流带 UTF-8 BOM), + BOM 字节按该编码解出为杂字,不做特殊处理; +- 与 WHATWG HTML §13.2.3 完整算法的步骤差异(用户覆盖、父上下文继承、 + 窗口自动探测)不实现——本轮按 goal 的固定链执行。 + +## 许可证与依赖面 + +- `encoding_rs`(MIT OR Apache-2.0)在 `deny.toml` 白名单内;本就在依赖树 + (reqwest 传递),直依赖化不新增包,deny / about 产出无实质变化(批次收口 + 时按流程重跑并重新注入)。 + +## 验证 + +- `cargo test -p nexty-network --no-default-features --features decode`:20 条 + 单测覆盖四层优先级矩阵(HTTP 胜 BOM / 胜 meta、BOM 三族、meta 引号 / 无引 + 号 / 1024 窗口 / 注释遮蔽 / 多 meta 首个已知标签胜出、非法字节替换、 + Content-Type 解析用例)+ 1 条 doc test; +- 非法字节路径不 panic(替换字符兜底)由 + `invalid_bytes_are_replaced_without_panic` 钉住; +- GBK 页实机渲染(chrome T5 退出条件)待接线后验收。 diff --git a/docs/decisions/2026-10-31-url.md b/docs/decisions/2026-10-31-url.md new file mode 100644 index 0000000..5aef6e8 --- /dev/null +++ b/docs/decisions/2026-10-31-url.md @@ -0,0 +1,47 @@ +# ADR: `url` 改为 nexty-network 直依赖(resolve 特性不再借 reqwest) + +- 日期:2026-10-31 +- 状态:已采纳 +- 背景:`nexty-network` 的 `resolve` 特性原先通过 `resolve = ["dep:reqwest"]` + 拿 reqwest 再导出的 `Url` 类型,导致「只想要 URL 解析」的下游被迫拉入整个 + reqwest + TLS 栈;同时 K3 导航轮(goal T5)需要文档 URL 的解析 / 拼接门面, + 依赖类型不得外泄的硬规则也要求自有封装。导航与网络完备轮(network + 0.1.5 → 0.1.6)T1 落地。 + +## 候选 + +| 候选 | 许可证 | 结论 | +| --- | --- | --- | +| `url` 2.5.8 直依赖 | MIT OR Apache-2.0 | **采纳**。WHATWG URL Standard 的官方 Rust 实现(Servo 出品,Chrome/Firefox 生态共用),本仓库硬规则「WHATWG 规范 > WPT > 成熟 crate > 自研」下的 obviously 正确选择;且已是依赖树成员(reqwest 传递依赖),直依赖化**零新增包** | +| 继续借 reqwest 的 `Url` | MIT OR Apache-2.0 | 否决:resolve 特性拖整个 reqwest + rustls + tokio 运行时依赖面,与「每层最小依赖足迹」相悖;reqwest 也只是 re-export `url::Url`,不提供额外解析能力 | +| 自研 URL 解析 | — | 否决:WHATWG basic URL parsing(IDNA、路径归一、query/fragment 语义)是典型的「有成熟轮子不自己造」,自研违反 AGENTS.md 选型优先级 | + +## 决策 + +1. **依赖接线**:`resolve = ["dep:url"]`,不再隐含 reqwest;`url = { version = + "2.5.8", optional = true }`(锁内已有 2.5.8,不引入版本漂移)。 +2. **API 面**:`pub fn resolve(base, target)` 签名不变(`String` 进出, + `NetworkError` 错误),既有回环测试与 chrome 调用点零改动。 +3. **最小封装**:新增自有类型 `nexty_network::Url`,只暴露 `parse` / + `join` / `as_str` 三个操作(本轮与 T5 所需),`url::Url` 字段私有,不外泄 + 依赖类型(硬规则)。`join("")` 显式短路返回自身,与 `resolve` 的空串语义 + 一致(opaque scheme 的 `join("")` 在 url crate 中会失败)。 +4. **能力边界**:不暴露 scheme / host / path 等访问器,不做序列化构造—— + 下游确有需求时再加(Style Conventions:别为未来需求加参数)。 + +## 许可证与依赖面 + +- `url` 及其传递依赖(`idna` / `form_urlencoded` / `percent-encoding`,MIT OR + Apache-2.0)全部在 `deny.toml` 白名单内;`cargo tree -p nexty-network + --no-default-features --features resolve` 已断言依赖树无 reqwest。 +- 由于 `url` / `encoding_rs` 本就在 Cargo.lock(reqwest 传递),本轮直依赖化 + 不新增任何包,`cargo deny check` 与 `cargo about generate` 产出无实质变化 + (批次收口时按流程重跑并重新注入)。 + +## 验证 + +- `cargo check -p nexty-network --no-default-features --features resolve` 编译 + 通过零 warning;`cargo tree` 断言无 reqwest(见上)。 +- resolve 既有回环测试(`resolve_handles_relative_paths` 等 4 条)在 + resolve-only 配置下不变绿;新增 `Url` 封装单测 3 条(parse/join/as_str、 + 空 join、opaque base)。 From b07e19e7f8c8dfcd5c4c1e5ed545132c70b4e4b4 Mon Sep 17 00:00:00 2001 From: zwork <zwork@local> Date: Sat, 31 Oct 2026 18:30:03 +0800 Subject: [PATCH 09/14] [text] session FontRegistry delegating @font-face matching to fontique CSS Fonts 5.2 (0.1.9) --- ..._ca7e797f-14f7-4cd4-a65e-6a69d7418103.json | 1 + ...24fdb88882b47c23cc0e0c80a30c7d53759.source | 584 ++++++++++++++++ ...4f7-4cd4-a65e-6a69d7418103-35569b193b.json | 14 + crates/nexty-text/Cargo.toml | 6 +- crates/nexty-text/src/lib.rs | 656 ++++++++++++++++-- crates/nexty-text/tests/data/OFL.txt | 93 +++ crates/nexty-text/tests/data/README.md | 11 + .../nexty-text/tests/data/SpaceMono-Bold.ttf | Bin 0 -> 98232 bytes .../tests/data/SpaceMono-Regular.ttf | Bin 0 -> 99356 bytes 9 files changed, 1304 insertions(+), 61 deletions(-) create mode 100644 crates/nexty-text/.mimosa/hook-state/sess_ca7e797f-14f7-4cd4-a65e-6a69d7418103.json create mode 100644 crates/nexty-text/.mimosa/hook-state/sess_ca7e797f-14f7-4cd4-a65e-6a69d7418103.mv39z7b9-7816-6ad66b2354.baseline/b1a35a68f14e696205874893c07fd24fdb88882b47c23cc0e0c80a30c7d53759.source create mode 100644 crates/nexty-text/.mimosa/hook-status/sess_ca7e797f-14f7-4cd4-a65e-6a69d7418103-35569b193b.json create mode 100644 crates/nexty-text/tests/data/OFL.txt create mode 100644 crates/nexty-text/tests/data/README.md create mode 100644 crates/nexty-text/tests/data/SpaceMono-Bold.ttf create mode 100644 crates/nexty-text/tests/data/SpaceMono-Regular.ttf diff --git a/crates/nexty-text/.mimosa/hook-state/sess_ca7e797f-14f7-4cd4-a65e-6a69d7418103.json b/crates/nexty-text/.mimosa/hook-state/sess_ca7e797f-14f7-4cd4-a65e-6a69d7418103.json new file mode 100644 index 0000000..99fbeab --- /dev/null +++ b/crates/nexty-text/.mimosa/hook-state/sess_ca7e797f-14f7-4cd4-a65e-6a69d7418103.json @@ -0,0 +1 @@ +{"touched":["D:\\Nexty\\crates\\nexty-text\\src\\lib.rs"],"bashMutation":false,"reportedFindings":[],"findingEvents":[],"baseline":{"storageId":"mv39z7b9-7816-6ad66b2354","createdAt":"2026-10-11T03:40:20.037Z","files":{"src/lib.rs":{"existed":true,"snapshot":"b1a35a68f14e696205874893c07fd24fdb88882b47c23cc0e0c80a30c7d53759.source"}},"complete":false,"candidateLimit":5000,"discoveredFiles":0,"capturedFiles":1,"truncated":false,"omittedAtLeast":0,"firstOmitted":"","errors":[{"stage":"baseline-capture","target":".","reason":"global task baseline was unavailable; captured only the touched file"},{"stage":"baseline-snapshot","target":"../nexty-layout/src/fragment.rs","reason":"file is outside project"},{"stage":"baseline-snapshot","target":"../nexty-layout/src/fragment.rs","reason":"file is outside project"},{"stage":"baseline-snapshot","target":"../nexty-layout/src/inline.rs","reason":"file is outside project"}]},"stateErrors":[],"omittedReportedFindings":0,"omittedFindingEvents":0,"processing":null,"updatedAt":"2026-10-11T03:43:40.868Z"} \ No newline at end of file diff --git a/crates/nexty-text/.mimosa/hook-state/sess_ca7e797f-14f7-4cd4-a65e-6a69d7418103.mv39z7b9-7816-6ad66b2354.baseline/b1a35a68f14e696205874893c07fd24fdb88882b47c23cc0e0c80a30c7d53759.source b/crates/nexty-text/.mimosa/hook-state/sess_ca7e797f-14f7-4cd4-a65e-6a69d7418103.mv39z7b9-7816-6ad66b2354.baseline/b1a35a68f14e696205874893c07fd24fdb88882b47c23cc0e0c80a30c7d53759.source new file mode 100644 index 0000000..f3b5825 --- /dev/null +++ b/crates/nexty-text/.mimosa/hook-state/sess_ca7e797f-14f7-4cd4-a65e-6a69d7418103.mv39z7b9-7816-6ad66b2354.baseline/b1a35a68f14e696205874893c07fd24fdb88882b47c23cc0e0c80a30c7d53759.source @@ -0,0 +1,584 @@ +//! Nexty 文本整形与字体 facade。 +//! +//! 上游:`parley`(Apache-2.0/MIT)——内部用 `fontique` 做字体选择与回退、 +//! `harfrust`(HarfBuzz 整形算法的 Rust 实现)做字形整形。选型 ADR 中列出的 +//! `swash` 自 parley 0.11 起已不参与整形,本层不再依赖(决策见 +//! `docs/decisions/2026-10-01-crate-selection.md`)。 +//! +//! 行为 ground truth:CSS Text、CSS Fonts 与 Unicode 断行算法;字形定位遵循 +//! OpenType 度量(units_per_em 归一到 CSS px,scale = 1)。 +//! +//! 本层只整形**单行**文本:white-space 折叠(含换行符处理)是 layout 层的 +//! 职责,进入本层的文本应已折叠。 +//! +//! 上游类型一律不得出现在本 crate 的 pub 导出中(AGENTS.md 硬规则)。 +//! +//! **Feature**:单行整形(`shaping`,含 `TextShaper` 与 parley 实现)与字体文件 +//! 解析(`font-resolution`,含 `FontResolver`)分别受feature 控制,默认全开; +//! 二者共享 parley 依赖,故各自隐含 `dep:parley`。 + +#![forbid(unsafe_code)] + +#[cfg(feature = "shaping")] +use std::cell::RefCell; +#[cfg(feature = "font-resolution")] +use std::sync::Mutex; + +#[cfg(feature = "shaping")] +use parley::StyleProperty; + +/// 字体族与字号。 +#[cfg(feature = "shaping")] +#[derive(Debug, Clone, PartialEq)] +pub struct TextStyle { + /// 字体族列表,按 CSS `font-family` 优先顺序排列。 + /// + /// 每一项是一个族名(如 `"Times New Roman"`)或 generic 族关键字 + /// (如 `"serif"` / `"sans-serif"` / `"monospace"`,大小写不敏感), + /// 解析与回退由 parley/fontique 按 CSS Fonts 语义处理。 + pub families: Vec<String>, + /// 字号,CSS px。 + pub size: f32, +} + +/// 整形后的单个字形。 +#[cfg(feature = "shaping")] +#[derive(Debug, Clone, Copy, PartialEq)] +pub struct Glyph { + /// 字体内部字形编号。 + pub id: u32, + /// 相对行首的水平偏移,CSS px。 + pub x: f32, + /// 相对基线的垂直偏移,CSS px(负值在基线上方)。 + pub y: f32, + /// 步进宽度,CSS px。 + pub advance: f32, +} + +/// 一段文本的整形结果。 +/// +/// 坐标系:`x` 从行首起算,`y` 以基线为 0、向下为正;[`ShapedText::height`] +/// 是 parley 按字体度量算出的行高。 +#[cfg(feature = "shaping")] +#[derive(Debug, Clone, PartialEq)] +pub struct ShapedText { + /// 按绘制顺序排列的字形。 + pub glyphs: Vec<Glyph>, + /// 行宽(含行尾空白),CSS px。 + pub width: f32, + /// 行高,CSS px。 + pub height: f32, +} + +/// 字体度量(CSS px;strut / 行盒计算用)。 +#[cfg(feature = "shaping")] +#[derive(Debug, Clone, Copy, PartialEq)] +pub struct FontMetrics { + /// ascent:基线到行内最高点的距离(CSS px,正值)。 + pub ascent: f32, + /// descent:基线到行内最低点的距离(CSS px,正值)。 + pub descent: f32, + /// 该字体的默认行高(ascent + descent + leading,CSS px)。 + pub line_height: f32, +} + +/// 解析出的字体资源:字体文件字节与 collection 内 face 索引。 +/// +/// 供光栅层(paint)构造字形渲染所需的字体数据;字节为共享快照, +/// 解析结果可按族列表缓存。 +#[cfg(feature = "font-resolution")] +#[derive(Clone, PartialEq, Eq)] +pub struct ResolvedFont { + data: std::sync::Arc<[u8]>, + index: u32, +} + +#[cfg(feature = "font-resolution")] +impl ResolvedFont { + /// 字体文件字节(TTC 时为整个 collection)。 + #[must_use] + pub fn data(&self) -> &std::sync::Arc<[u8]> { + &self.data + } + + /// face 在 collection 中的索引(单字体文件为 0)。 + #[must_use] + pub fn index(&self) -> u32 { + self.index + } +} + +#[cfg(feature = "font-resolution")] +impl std::fmt::Debug for ResolvedFont { + fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { + f.debug_struct("ResolvedFont") + .field("bytes", &self.data.len()) + .field("index", &self.index) + .finish() + } +} + +/// 文本整形后端。 +/// +/// 实现方负责把 [`TextStyle`] 映射到具体字体选择与整形引擎, +/// 只对外暴露本 crate 的类型。 +#[cfg(feature = "shaping")] +pub trait TextShaper { + /// 对一段文本整形。 + /// + /// # Errors + /// + /// 字体缺失或整形失败时返回 [`TextError`]。 + fn shape(&self, text: &str, style: &TextStyle) -> Result<ShapedText, TextError>; + + /// 返回字体族列表对应字体的度量。 + /// + /// # Errors + /// + /// 字体族列表为空时返回 [`TextError::FontUnavailable`]。 + fn metrics(&self, style: &TextStyle) -> Result<FontMetrics, TextError>; +} + +/// 文本整形错误。 +#[cfg(feature = "shaping")] +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +pub enum TextError { + /// 请求的字体族列表为空,无法选择字体。 + /// + /// 单个未知族名不会触发本错误:parley/fontique 会按 CSS Fonts 的回退 + /// 语义选择可用字体。 + FontUnavailable, +} + +/// 字体解析器:把 CSS 字体族列表解析为字体文件字节。 +/// +/// 独立于整形器(无布局上下文),内部用 `Mutex` 提供可变性, +/// 可跨线程共享(`Send + Sync`)。 +#[cfg(feature = "font-resolution")] +#[derive(Default)] +pub struct FontResolver { + context: Mutex<parley::FontContext>, +} + +#[cfg(feature = "font-resolution")] +impl std::fmt::Debug for FontResolver { + fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { + f.debug_struct("FontResolver").finish() + } +} + +#[cfg(feature = "font-resolution")] +impl FontResolver { + /// 创建解析器并发现系统字体。 + #[must_use] + pub fn new() -> Self { + Self::default() + } + + /// 按字体族列表解析出可用字体的文件字节。 + /// + /// 族名 / generic 关键字的语义与 [`TextShaper::shape`] 一致;全部族名 + /// 都不可用时按 CSS Fonts 回退语义退到 sans-serif,仍无则返回 `None`。 + /// 空族列表返回 `None`。 + pub fn resolve_font(&self, families: &[String]) -> Option<ResolvedFont> { + if families.is_empty() { + return None; + } + // 族名 / generic 关键字的解析与整形同源(parlance); + // QueryFamily 借用族名字符串,故持有 owned 副本保证生命周期 + enum FamilySpec { + Named(String), + Generic(parley::GenericFamily), + } + fn build_items(specs: &[FamilySpec]) -> Vec<parley::fontique::QueryFamily<'_>> { + specs + .iter() + .map(|spec| match spec { + FamilySpec::Named(name) => parley::fontique::QueryFamily::Named(name), + FamilySpec::Generic(generic) => { + parley::fontique::QueryFamily::Generic(*generic) + } + }) + .collect() + } + let specs: Vec<FamilySpec> = families + .iter() + .filter_map(|family| match parley::FontFamilyName::parse(family)? { + parley::FontFamilyName::Named(name) => Some(FamilySpec::Named(name.into_owned())), + parley::FontFamilyName::Generic(generic) => Some(FamilySpec::Generic(generic)), + }) + .collect(); + + let mut context = self.context.lock().expect("font resolver poisoned"); + // 拆字段借用:collection 与 source_cache 同时可变借用 + let parley::FontContext { + collection, + source_cache, + } = &mut *context; + let mut resolve = |specs: &[FamilySpec]| -> Option<ResolvedFont> { + let items = build_items(specs); + let mut query = collection.query(source_cache); + query.set_families(items); + let mut found = None; + query.matches_with(|font| { + // Blob 是共享引用计数,字节取快照供跨线程使用 + found = Some(ResolvedFont { + data: std::sync::Arc::from(font.blob.as_ref()), + index: font.index, + }); + parley::fontique::QueryStatus::Stop + }); + found + }; + + let mut resolved = resolve(&specs); + if resolved.is_none() { + // 回退:sans-serif(CSS Fonts 的 last-resort 语义简化) + resolved = resolve(&[FamilySpec::Generic(parley::GenericFamily::SansSerif)]); + } + resolved + } +} + +/// [`TextShaper`] 的 parley 实现。 +/// +/// 持有 fontique 字体集合(系统字体)与 parley 布局上下文;上下文可复用, +/// 用 `RefCell` 提供内部可变性(`shape` 只需 `&self`)。 +#[cfg(feature = "shaping")] +pub struct ParleyTextShaper { + font_context: RefCell<parley::FontContext>, + layout_context: RefCell<parley::LayoutContext>, +} + +#[cfg(feature = "shaping")] +impl std::fmt::Debug for ParleyTextShaper { + fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { + f.debug_struct("ParleyTextShaper").finish() + } +} + +#[cfg(feature = "shaping")] +impl Default for ParleyTextShaper { + fn default() -> Self { + Self { + font_context: RefCell::new(parley::FontContext::new()), + layout_context: RefCell::new(parley::LayoutContext::new()), + } + } +} + +#[cfg(feature = "shaping")] +impl ParleyTextShaper { + /// 创建整形器并发现系统字体。 + #[must_use] + pub fn new() -> Self { + Self::default() + } + + /// 按字体族列表解析出可用字体的文件字节。 + /// + /// 语义见 [`FontResolver::resolve_font`]。 + pub fn resolve_font(&self, families: &[String]) -> Option<ResolvedFont> { + FontResolver::new().resolve_font(families) + } + + /// 按样式对文本做单行 parley 布局(不折行)。 + fn build_layout( + &self, + text: &str, + style: &TextStyle, + ) -> Result<parley::Layout<[u8; 4]>, TextError> { + if style.families.is_empty() { + return Err(TextError::FontUnavailable); + } + // CSS font-family 列表的解析(族名/引号/generic 关键字/回退顺序) + // 交给 parley 的 FontFamily::Source + let family_list = style.families.join(", "); + + let mut font_context = self.font_context.borrow_mut(); + let mut layout_context = self.layout_context.borrow_mut(); + let mut builder = layout_context.ranged_builder(&mut font_context, text, 1.0, false); + builder.push_default(StyleProperty::FontFamily(parley::FontFamily::Source( + std::borrow::Cow::Borrowed(&family_list), + ))); + builder.push_default(StyleProperty::FontSize(style.size)); + + let mut layout = builder.build(text); + // max_advance = None:单行整形,不做折行 + layout.break_all_lines(None); + Ok(layout) + } +} + +#[cfg(feature = "shaping")] +impl TextShaper for ParleyTextShaper { + fn shape(&self, text: &str, style: &TextStyle) -> Result<ShapedText, TextError> { + if text.is_empty() { + return Ok(ShapedText { + glyphs: Vec::new(), + width: 0.0, + height: 0.0, + }); + } + + let layout = self.build_layout(text, style)?; + + let mut glyphs = Vec::new(); + for line in layout.lines() { + let baseline = line.metrics().baseline; + for item in line.items() { + let parley::PositionedLayoutItem::GlyphRun(glyph_run) = item else { + continue; + }; + for glyph in glyph_run.positioned_glyphs() { + glyphs.push(Glyph { + id: glyph.id, + // positioned_glyphs 的 y 已含基线偏移,换回相对基线 + x: glyph.x, + y: glyph.y - baseline, + advance: glyph.advance, + }); + } + } + } + + let width = layout + .width() + .max(glyphs.last().map_or(0.0, |glyph| glyph.x + glyph.advance)); + + Ok(ShapedText { + glyphs, + // parley 的行宽按断行测量语义**不含行尾空白**,而本层契约是含 + // (调用方按 ShapedText.width 计词间空白的步进,见 inline 模块的 + // space_after_previous)——取字形右缘与行宽的较大者。 + width, + height: layout.height(), + }) + } + + fn metrics(&self, style: &TextStyle) -> Result<FontMetrics, TextError> { + // 用不换行空格探针取度量:NBSP 在几乎所有字体中都有字形, + // parley 的行度量来自 run 字体的 ascent/descent/leading + let layout = self.build_layout("\u{00A0}", style)?; + let line = layout.lines().next().ok_or(TextError::FontUnavailable)?; + let metrics = line.metrics(); + Ok(FontMetrics { + ascent: metrics.ascent, + descent: metrics.descent, + line_height: metrics.line_height, + }) + } +} + +// 测试覆盖整形与字体解析(shaping 隐含 font-resolution)。 +#[cfg(all(test, feature = "shaping"))] +mod tests { + use super::*; + + fn shaper() -> ParleyTextShaper { + ParleyTextShaper::new() + } + + fn style(families: &[&str], size: f32) -> TextStyle { + TextStyle { + families: families.iter().map(|family| (*family).to_owned()).collect(), + size, + } + } + + #[test] + fn empty_text_yields_empty_output() { + let shaped = shaper() + .shape("", &style(&["serif"], 16.0)) + .expect("empty text shapes to empty"); + assert!(shaped.glyphs.is_empty()); + assert_eq!(shaped.width, 0.0); + } + + #[test] + fn empty_family_list_is_font_unavailable() { + let error = shaper() + .shape("hello", &style(&[], 16.0)) + .expect_err("no families"); + assert_eq!(error, TextError::FontUnavailable); + } + + #[test] + fn ascii_text_shapes_to_positive_metrics() { + let shaped = shaper() + .shape("Hello", &style(&["serif"], 16.0)) + .expect("shaping with system fonts"); + + assert!(!shaped.glyphs.is_empty()); + assert!(shaped.width > 0.0); + assert!(shaped.height > 0.0); + // 每个字形有非负步进,x 单调不减 + let mut previous_x = 0.0; + for glyph in &shaped.glyphs { + assert!(glyph.advance >= 0.0); + assert!(glyph.x >= previous_x - 1e-4); + previous_x = glyph.x; + } + // 宽度与最后一个字形的右缘一致(容差内) + let last = shaped.glyphs.last().expect("non-empty"); + assert!((shaped.width - (last.x + last.advance)).abs() < 1e-3); + } + + #[test] + fn advances_scale_with_font_size() { + let shaper = shaper(); + let small = shaper + .shape("iii", &style(&["serif"], 16.0)) + .expect("small"); + let large = shaper + .shape("iii", &style(&["serif"], 32.0)) + .expect("large"); + + assert_eq!( + small.glyphs.len(), + large.glyphs.len(), + "同字体同文本字形数一致" + ); + let small_advance: f32 = small.glyphs.iter().map(|glyph| glyph.advance).sum(); + let large_advance: f32 = large.glyphs.iter().map(|glyph| glyph.advance).sum(); + let ratio = large_advance / small_advance; + assert!( + (ratio - 2.0).abs() < 0.02, + "advance 比例应约等于字号比例: {ratio}" + ); + } + + #[test] + fn unknown_family_falls_back_gracefully() { + let shaper = shaper(); + // 未知族名按 CSS Fonts 语义回退到可用字体,不报错 + let shaped = shaper + .shape("Hi", &style(&["no-such-family-xyz", "serif"], 16.0)) + .expect("fallback"); + assert!(!shaped.glyphs.is_empty()); + + // 只有未知族名同样回退 + let shaped = shaper + .shape("Hi", &style(&["no-such-family-xyz"], 16.0)) + .expect("fallback with single unknown family"); + assert!(!shaped.glyphs.is_empty()); + } + + #[test] + fn generic_family_keywords_work() { + let shaper = shaper(); + for family in ["sans-serif", "SANS-SERIF", "monospace", "system-ui"] { + let shaped = shaper + .shape("Hi", &style(&[family], 16.0)) + .unwrap_or_else(|error| panic!("{family} should shape: {error:?}")); + assert!(!shaped.glyphs.is_empty(), "{family} produced glyphs"); + } + } + + #[test] + fn trailing_whitespace_is_included_in_width() { + // parley 行宽裁剪行尾空白;ShapedText.width 契约是含行尾空白 + // (空格的步进供行内布局计词间距,见下一测试) + let shaper = shaper(); + let style = style(&["serif"], 16.0); + let space = shaper.shape(" ", &style).expect("shape space"); + assert!(space.width > 0.0, "行尾空白计入宽度:width={}", space.width); + let word = shaper.shape("a", &style).expect("shape a"); + let trailing = shaper.shape("a ", &style).expect("shape a-space"); + assert!( + trailing.width > word.width, + "a 加行尾空格应更宽:{} vs {}", + trailing.width, + word.width + ); + } + + #[test] + fn inter_word_space_advances_position() { + // 词间空白的宽度 = 后词起点与前词右缘之差(行内布局的空格语义) + let shaper = shaper(); + let style = style(&["serif"], 16.0); + let space = shaper.shape(" ", &style).expect("shape space"); + let text = shaper.shape("a b", &style).expect("shape a b"); + let b = text.glyphs.last().expect("b glyph"); + let a = text.glyphs.first().expect("a glyph"); + let gap = b.x - (a.x + a.advance); + assert!( + (gap - space.width).abs() < 1e-3, + "词间空隙 {gap} 应等于空格宽 {}", + space.width + ); + } + + #[test] + fn metrics_are_positive_and_scale_with_size() { + let shaper = shaper(); + let small = shaper + .metrics(&style(&["serif"], 16.0)) + .expect("metrics for serif"); + assert!(small.ascent > 0.0); + assert!(small.descent > 0.0); + assert!(small.line_height >= small.ascent + small.descent); + + let large = shaper + .metrics(&style(&["serif"], 32.0)) + .expect("metrics at 2x size"); + let ratio = large.ascent / small.ascent; + assert!((ratio - 2.0).abs() < 0.05, "ascent 应约随字号翻倍: {ratio}"); + } + + #[test] + fn metrics_empty_family_list_is_font_unavailable() { + let error = shaper() + .metrics(&style(&[], 16.0)) + .expect_err("no families"); + assert_eq!(error, TextError::FontUnavailable); + } + + #[test] + fn resolve_font_returns_bytes_for_known_and_unknown_families() { + let shaper = shaper(); + let resolved = shaper + .resolve_font(&["serif".to_owned()]) + .expect("generic family resolves"); + assert!(!resolved.data().is_empty(), "字体字节非空"); + assert_eq!(resolved.index(), 0, "常规字体文件单 face"); + + // 全部族名未知 → 回退仍能解析出字体 + let fallback = shaper + .resolve_font(&["no-such-family-xyz".to_owned()]) + .expect("fallback resolves"); + assert!(!fallback.data().is_empty()); + } + + #[test] + fn resolve_font_empty_family_list_is_none() { + assert!(shaper().resolve_font(&[]).is_none()); + } + + #[test] + fn resolved_font_bytes_are_valid_font_data() { + // skrifa(parley 的字体解析库依赖路径)能读取为合法 face + let shaper = shaper(); + let resolved = shaper + .resolve_font(&["serif".to_owned()]) + .expect("resolves"); + let face_count = skrifa::FontRef::from_index(resolved.data(), resolved.index()) + .map(|_| 1) + .unwrap_or(0); + assert_eq!(face_count, 1, "字节可被 skrifa 解析"); + } + + #[test] + fn cjk_text_shapes_without_notdef_glyphs() { + // fontique 回退应把缺字码点交给系统 CJK 字体(Windows YaHei 等), + // 不得产出 .notdef(字形 id 0)豆腐块 + let shaper = shaper(); + let shaped = shaper + .shape("中文测试", &style(&["sans-serif"], 16.0)) + .expect("CJK shaping"); + assert!(!shaped.glyphs.is_empty()); + let notdef = shaped.glyphs.iter().filter(|glyph| glyph.id == 0).count(); + assert_eq!(notdef, 0, "中文字形不得有 notdef 豆腐块"); + } +} diff --git a/crates/nexty-text/.mimosa/hook-status/sess_ca7e797f-14f7-4cd4-a65e-6a69d7418103-35569b193b.json b/crates/nexty-text/.mimosa/hook-status/sess_ca7e797f-14f7-4cd4-a65e-6a69d7418103-35569b193b.json new file mode 100644 index 0000000..2023c38 --- /dev/null +++ b/crates/nexty-text/.mimosa/hook-status/sess_ca7e797f-14f7-4cd4-a65e-6a69d7418103-35569b193b.json @@ -0,0 +1,14 @@ +{ + "schemaVersion": "mimosa-hook-status/v1", + "recordedAt": "2026-10-11T03:43:43.354Z", + "sessionId": "sess_ca7e797f-14f7-4cd4-a65e-6a69d7418103", + "event": "PostToolUse", + "toolName": "Edit", + "file": "D:\\Nexty\\crates\\nexty-layout\\src\\inline.rs", + "outcome": "inconclusive", + "coverage": "partial", + "findingCount": 0, + "durationMs": 12, + "hostState": "hook_complete", + "reportHint": ".mimosa/reports/" +} diff --git a/crates/nexty-text/Cargo.toml b/crates/nexty-text/Cargo.toml index dda071d..966a8d9 100644 --- a/crates/nexty-text/Cargo.toml +++ b/crates/nexty-text/Cargo.toml @@ -1,7 +1,7 @@ [package] name = "nexty-text" description = "Nexty 文本整形与字体 facade" -version = "0.1.8" +version = "0.1.9" edition.workspace = true license.workspace = true repository.workspace = true @@ -14,7 +14,9 @@ default = ["shaping", "font-resolution"] # 单行文本整形:TextShaper trait 与 parley(fontique + harfrust)实现。 # ParleyTextShaper 的字体解析复用 FontResolver,故隐含 font-resolution。 shaping = ["dep:parley", "font-resolution"] -# 字体文件解析:FontResolver / ResolvedFont,供 paint 取字体字节。 +# 字体文件解析:FontResolver / ResolvedFont 与 @font-face 注册表 +# (FontRegistry / FontFaceDescriptor),供 paint 取字体字节、chrome 注册 +# Web 字体。 font-resolution = ["dep:parley"] [dependencies] diff --git a/crates/nexty-text/src/lib.rs b/crates/nexty-text/src/lib.rs index ec859db..062e408 100644 --- a/crates/nexty-text/src/lib.rs +++ b/crates/nexty-text/src/lib.rs @@ -12,17 +12,34 @@ //! 回退到系统字体(CJK 在 Windows 命中 YaHei 等)。[`ShapedText::fonts`] //! 记录实际用到的字体、每个 [`Glyph::font`] 指明归属,光栅层按此渲染。 //! +//! Web 字体(@font-face):[`FontRegistry`] 按会话注册字体字节与描述符 +//! (CSS 声明族名 / weight / style),注册时经 fontique 的 +//! `FontInfoOverride` 把 CSS 声明名注入字体集合——声明名与字体内部族名 +//! 解耦(CSS Fonts §4);族内 face 选择(width → style → weight)委托 +//! fontique 的 CSS Fonts §5.2 匹配实现。注册面对整形与解析同时生效: +//! 整形器在每次整形前增量同步,[`FontResolver`] 在每次解析前同步。 +//! //! 本层只整形**单行**文本:white-space 折叠(含换行符处理)是 layout 层的 //! 职责,进入本层的文本应已折叠。 //! //! 上游类型一律不得出现在本 crate 的 pub 导出中(AGENTS.md 硬规则)。 //! +//! **偏差清单(Web 字体简化档)**:同族名的系统字体与注册 face 会合并进 +//! 同一 fontique 族参与匹配——CSS Fonts 要求 @font-face 覆盖同名系统 +//! 字体,此处不保证覆盖顺序(同名共存罕见,接受);多 face collection +//! (TTC)的全部 face 以同一描述符注册(face index 仍按 (blob id, face +//! index) 缓存路径流转);`font-stretch` / `unicode-range` / 可变字体 +//! 轴不支持;oblique 期望由上层映射为 italic;`font-display` 行为在 +//! chrome 层编排。 +//! //! **Feature**:单行整形(`shaping`,含 `TextShaper` 与 parley 实现)与字体文件 -//! 解析(`font-resolution`,含 `FontResolver`)分别受feature 控制,默认全开; -//! 二者共享 parley 依赖,故各自隐含 `dep:parley`。 +//! 解析(`font-resolution`,含 `FontResolver` 与 [`FontRegistry`])分别受 +//! feature 控制,默认全开;二者共享 parley 依赖,故各自隐含 `dep:parley`。 #![forbid(unsafe_code)] +#[cfg(feature = "shaping")] +use std::cell::Cell; #[cfg(feature = "shaping")] use std::cell::RefCell; #[cfg(feature = "shaping")] @@ -142,6 +159,174 @@ impl std::fmt::Debug for ResolvedFont { } } +/// 字体样式(CSS `font-style` 的简化档:仅 normal / italic,无 oblique)。 +/// +/// 期望 oblique 的请求由上层映射为 [`FontStyle::Italic`](偏差见模块文档)。 +#[cfg(feature = "font-resolution")] +#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)] +pub enum FontStyle { + /// 直立体。 + Normal, + /// 斜体。 + Italic, +} + +/// @font-face 字体描述符(CSS Fonts §4 简化档)。 +/// +/// `family` 是 @font-face 规则声明的 CSS 族名,与字体文件内部的族名无关; +/// 注册后按该名参与 `font-family` 匹配(大小写不敏感,与 CSS 一致)。 +/// `weight` 是 font-weight 描述符的单值(1–1000,超界值注册时 clamp); +/// `style` 是 font-style 描述符。 +#[cfg(feature = "font-resolution")] +#[derive(Debug, Clone, PartialEq, Eq)] +pub struct FontFaceDescriptor { + /// @font-face 规则的 font-family 描述符(CSS 声明名)。 + pub family: String, + /// @font-face 规则的 font-weight 描述符(单值,1–1000)。 + pub weight: u16, + /// @font-face 规则的 font-style 描述符。 + pub style: FontStyle, +} + +/// [`FontRegistry::register`] 的失败原因。 +#[cfg(feature = "font-resolution")] +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +pub enum FontRegistryError { + /// 描述符的 family 名为空(或全空白)。 + EmptyFamily, + /// 字体数据无法解析出任何 face(非字体文件或已损坏)。 + InvalidFontData, +} + +/// 会话级 @font-face 字体注册表。 +/// +/// 持有注册的字体字节与描述符;消费方([`FontResolver`] 与整形器 +/// `ParleyTextShaper`)在使用前把新注册面增量注入各自的 fontique 字体 +/// 集合——注册即生效,无需任何「激活」动作。注册只增不减(生命周期与 +/// 会话一致);`Clone` 是廉价的共享句柄(内部 `Arc`),`Send + Sync`。 +#[cfg(feature = "font-resolution")] +#[derive(Clone, Default)] +pub struct FontRegistry { + inner: std::sync::Arc<RegistryInner>, +} + +#[cfg(feature = "font-resolution")] +#[derive(Default)] +struct RegistryInner { + /// 按注册顺序排列的 face;长度即同步代次。 + faces: Mutex<Vec<RegisteredFace>>, +} + +#[cfg(feature = "font-resolution")] +struct RegisteredFace { + descriptor: FontFaceDescriptor, + /// 字体字节共享快照:id 全局唯一,克隆到各消费方后 `(blob id, + /// face index)` 缓存路径与系统字体共用一份逻辑。 + blob: parley::fontique::Blob<u8>, +} + +#[cfg(feature = "font-resolution")] +impl std::fmt::Debug for FontRegistry { + fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { + let count = self + .inner + .faces + .lock() + .map(|faces| faces.len()) + .unwrap_or(0); + f.debug_struct("FontRegistry") + .field("faces", &count) + .finish() + } +} + +#[cfg(feature = "font-resolution")] +impl FontRegistry { + /// 创建空注册表。 + #[must_use] + pub fn new() -> Self { + Self::default() + } + + /// 注册一份字体字节为指定描述符的 face。 + /// + /// 字节先经 fontique 扫描校验(解析不出任何 face 即 + /// [`FontRegistryError::InvalidFontData`],非法字节不进入注册表); + /// 合法面进入注册表,对已接入的解析器 / 整形器在下一次使用时生效。 + /// 多 face collection(TTC)的全部 face 都以该描述符注册(偏差见 + /// 模块文档);face index 由 fontique 扫描得出并随解析结果流转, + /// `(blob id, face index)` 缓存路径与系统字体共用。 + /// + /// # Errors + /// + /// family 名为空返回 [`FontRegistryError::EmptyFamily`];字节不是可 + /// 解析字体返回 [`FontRegistryError::InvalidFontData`]。 + pub fn register( + &self, + data: Vec<u8>, + descriptor: FontFaceDescriptor, + ) -> Result<(), FontRegistryError> { + if descriptor.family.trim().is_empty() { + return Err(FontRegistryError::EmptyFamily); + } + let mut descriptor = descriptor; + descriptor.weight = descriptor.weight.clamp(1, 1000); + let blob: parley::fontique::Blob<u8> = parley::fontique::Blob::from(data); + // 校验用临时集合(不枚举系统字体):扫描不出任何 face 即非法字节 + let mut probe = parley::fontique::Collection::new(parley::fontique::CollectionOptions { + shared: false, + system_fonts: false, + }); + let registered = + probe.register_fonts(blob.clone(), Some(registered_face_override(&descriptor))); + if registered.is_empty() { + return Err(FontRegistryError::InvalidFontData); + } + self.inner + .faces + .lock() + .expect("font registry poisoned") + .push(RegisteredFace { descriptor, blob }); + Ok(()) + } + + /// 把 `*applied` 之后新注册的 face 增量注入 `context` 的字体集合并 + /// 推进代次(幂等;无新注册时空操作)。仅 crate 内部使用。 + pub(crate) fn sync_into(&self, context: &mut parley::FontContext, applied: &mut usize) { + let faces = self.inner.faces.lock().expect("font registry poisoned"); + if *applied >= faces.len() { + return; + } + for face in &faces[*applied..] { + context.collection.register_fonts( + face.blob.clone(), + Some(registered_face_override(&face.descriptor)), + ); + } + *applied = faces.len(); + } +} + +/// 描述符 → fontique 注册元数据覆盖:CSS 声明名与 weight/style 经此 +/// 写入 face 属性(fontique 为 @font-face 类 API 预留的入口)。 +#[cfg(feature = "font-resolution")] +fn registered_face_override( + descriptor: &FontFaceDescriptor, +) -> parley::fontique::FontInfoOverride<'_> { + parley::fontique::FontInfoOverride { + family_name: Some(&descriptor.family), + width: None, + style: Some(match descriptor.style { + FontStyle::Normal => parley::fontique::FontStyle::Normal, + FontStyle::Italic => parley::fontique::FontStyle::Italic, + }), + weight: Some(parley::fontique::FontWeight::new(f32::from( + descriptor.weight, + ))), + axes: None, + } +} + /// 文本整形后端。 /// /// 实现方负责把 [`TextStyle`] 映射到具体字体选择与整形引擎, @@ -177,17 +362,31 @@ pub enum TextError { /// 字体解析器:把 CSS 字体族列表解析为字体文件字节。 /// /// 独立于整形器(无布局上下文),内部用 `Mutex` 提供可变性, -/// 可跨线程共享(`Send + Sync`)。 +/// 可跨线程共享(`Send + Sync`)。可接入会话级 [`FontRegistry`]: +/// 族列表中的 @font-face 声明名命中注册 face,未命中的族走既有系统 +/// 字体回退。 #[cfg(feature = "font-resolution")] #[derive(Default)] pub struct FontResolver { - context: Mutex<parley::FontContext>, + state: Mutex<ResolveState>, + registry: Option<FontRegistry>, +} + +#[cfg(feature = "font-resolution")] +#[derive(Default)] +struct ResolveState { + /// fontique 字体上下文(系统字体 + 已注入的注册 face)。 + context: parley::FontContext, + /// 已注入的注册 face 数(同步代次,见 [`FontRegistry::sync_into`])。 + applied: usize, } #[cfg(feature = "font-resolution")] impl std::fmt::Debug for FontResolver { fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { - f.debug_struct("FontResolver").finish() + f.debug_struct("FontResolver") + .field("with_registry", &self.registry.is_some()) + .finish() } } @@ -199,77 +398,134 @@ impl FontResolver { Self::default() } - /// 按字体族列表解析出可用字体的文件字节。 + /// 创建接入会话级字体注册表的解析器。 + /// + /// `registry` 内部按 `Arc` 共享(克隆廉价);此后每次解析前把新注册 + /// face 增量注入,注册即生效。 + #[must_use] + pub fn with_registry(registry: &FontRegistry) -> Self { + Self { + registry: Some(registry.clone()), + ..Self::default() + } + } + + /// 按字体族列表解析出可用字体的文件字节(期望样式默认 normal/400)。 /// /// 族名 / generic 关键字的语义与 [`TextShaper::shape`] 一致;全部族名 /// 都不可用时按 CSS Fonts 回退语义退到 sans-serif,仍无则返回 `None`。 /// 空族列表返回 `None`。 pub fn resolve_font(&self, families: &[String]) -> Option<ResolvedFont> { + // CSS Fonts 的 normal 关键字 = 400 + self.resolve_font_with(families, 400, FontStyle::Normal) + } + + /// [`FontResolver::resolve_font`] 的带期望样式扩展(@font-face 就近匹配)。 + /// + /// `weight`(CSS 1–1000)与 `style` 作为期望值参与族内匹配:注册 face + /// 与系统 face 同池对待,width → style → weight 逐级就近(CSS Fonts + /// §5.2);族列表按序前进,第一个有可用 face 的族生效。 + pub fn resolve_font_with( + &self, + families: &[String], + weight: u16, + style: FontStyle, + ) -> Option<ResolvedFont> { if families.is_empty() { return None; } - // 族名 / generic 关键字的解析与整形同源(parlance); - // QueryFamily 借用族名字符串,故持有 owned 副本保证生命周期 - enum FamilySpec { - Named(String), - Generic(parley::GenericFamily), + let mut state = self.state.lock().expect("font resolver poisoned"); + if let Some(registry) = &self.registry { + // 解构拆字段借用:MutexGuard 的两次 DerefMut 会整体冲突 + let ResolveState { context, applied } = &mut *state; + registry.sync_into(context, applied); } - fn build_items(specs: &[FamilySpec]) -> Vec<parley::fontique::QueryFamily<'_>> { - specs - .iter() - .map(|spec| match spec { - FamilySpec::Named(name) => parley::fontique::QueryFamily::Named(name), - FamilySpec::Generic(generic) => { - parley::fontique::QueryFamily::Generic(*generic) - } - }) - .collect() - } - let specs: Vec<FamilySpec> = families + resolve_font_in(&mut state.context, families, weight, style) + } +} + +/// 族列表解析的共用实现(`FontResolver` 与整形器共用)。 +/// +/// 调用方负责先把会话级注册 face 注入 `context`(见 +/// [`FontRegistry::sync_into`]);族名 / generic 关键字的解析交给 parley +/// (`FontFamilyName`),查询按 CSS Fonts §5.2 逐族前进,全部未命中时 +/// 回退 sans-serif。 +#[cfg(feature = "font-resolution")] +fn resolve_font_in( + context: &mut parley::FontContext, + families: &[String], + weight: u16, + style: FontStyle, +) -> Option<ResolvedFont> { + // 族名 / generic 关键字的解析与整形同源(parlance); + // QueryFamily 借用族名字符串,故持有 owned 副本保证生命周期 + enum FamilySpec { + Named(String), + Generic(parley::GenericFamily), + } + fn build_items(specs: &[FamilySpec]) -> Vec<parley::fontique::QueryFamily<'_>> { + specs .iter() - .filter_map(|family| match parley::FontFamilyName::parse(family)? { - parley::FontFamilyName::Named(name) => Some(FamilySpec::Named(name.into_owned())), - parley::FontFamilyName::Generic(generic) => Some(FamilySpec::Generic(generic)), + .map(|spec| match spec { + FamilySpec::Named(name) => parley::fontique::QueryFamily::Named(name), + FamilySpec::Generic(generic) => parley::fontique::QueryFamily::Generic(*generic), }) - .collect(); + .collect() + } + let specs: Vec<FamilySpec> = families + .iter() + .filter_map(|family| match parley::FontFamilyName::parse(family)? { + parley::FontFamilyName::Named(name) => Some(FamilySpec::Named(name.into_owned())), + parley::FontFamilyName::Generic(generic) => Some(FamilySpec::Generic(generic)), + }) + .collect(); - let mut context = self.context.lock().expect("font resolver poisoned"); - // 拆字段借用:collection 与 source_cache 同时可变借用 - let parley::FontContext { - collection, - source_cache, - } = &mut *context; - let mut resolve = |specs: &[FamilySpec]| -> Option<ResolvedFont> { - let items = build_items(specs); - let mut query = collection.query(source_cache); - query.set_families(items); - let mut found = None; - query.matches_with(|font| { - // Blob 是共享引用计数,字节取快照供跨线程使用; - // blob id 作实例标识(判等免去字节比较) - found = Some(ResolvedFont { - data: std::sync::Arc::from(font.blob.as_ref()), - index: font.index, - id: font.blob.id(), - }); - parley::fontique::QueryStatus::Stop + // 拆字段借用:collection 与 source_cache 同时可变借用 + let parley::FontContext { + collection, + source_cache, + } = context; + let mut resolve = |specs: &[FamilySpec]| -> Option<ResolvedFont> { + let items = build_items(specs); + let mut query = collection.query(source_cache); + query.set_families(items); + // CSS Fonts §5.2 的族内匹配:width → style → weight 逐级就近。 + // width 恒取查询默认值(本层不支持 font-stretch,见模块偏差清单)。 + query.set_attributes(parley::fontique::Attributes::new( + parley::fontique::FontWidth::default(), + match style { + FontStyle::Normal => parley::fontique::FontStyle::Normal, + FontStyle::Italic => parley::fontique::FontStyle::Italic, + }, + parley::fontique::FontWeight::new(f32::from(weight)), + )); + let mut found = None; + query.matches_with(|font| { + // Blob 是共享引用计数,字节取快照供跨线程使用; + // blob id 作实例标识(判等免去字节比较) + found = Some(ResolvedFont { + data: std::sync::Arc::from(font.blob.as_ref()), + index: font.index, + id: font.blob.id(), }); - found - }; + parley::fontique::QueryStatus::Stop + }); + found + }; - let mut resolved = resolve(&specs); - if resolved.is_none() { - // 回退:sans-serif(CSS Fonts 的 last-resort 语义简化) - resolved = resolve(&[FamilySpec::Generic(parley::GenericFamily::SansSerif)]); - } - resolved + let mut resolved = resolve(&specs); + if resolved.is_none() { + // 回退:sans-serif(CSS Fonts 的 last-resort 语义简化) + resolved = resolve(&[FamilySpec::Generic(parley::GenericFamily::SansSerif)]); } + resolved } /// [`TextShaper`] 的 parley 实现。 /// -/// 持有 fontique 字体集合(系统字体)与 parley 布局上下文;上下文可复用, -/// 用 `RefCell` 提供内部可变性(`shape` 只需 `&self`)。 +/// 持有 fontique 字体集合(系统字体与已注入的注册 face)与 parley 布局 +/// 上下文;上下文可复用,用 `RefCell` 提供内部可变性(`shape` 只需 +/// `&self`)。 #[cfg(feature = "shaping")] pub struct ParleyTextShaper { font_context: RefCell<parley::FontContext>, @@ -281,6 +537,10 @@ pub struct ParleyTextShaper { /// 字体(msyh.ttc)约 20 MB,按文本 chunk 数放大后布局期内存以 GB /// 计(T1 基准实测:2,000 段页面冲到 9 GB 提交内存后分配失败 abort)。 font_cache: RefCell<HashMap<(u64, u32), ResolvedFont>>, + /// 会话级 @font-face 注册表(可选);整形 / 解析前增量注入 font_context。 + registry: Option<FontRegistry>, + /// 注册表同步代次(已注入的注册 face 数)。 + registry_applied: Cell<usize>, } #[cfg(feature = "shaping")] @@ -297,6 +557,8 @@ impl Default for ParleyTextShaper { font_context: RefCell::new(parley::FontContext::new()), layout_context: RefCell::new(parley::LayoutContext::new()), font_cache: RefCell::new(HashMap::new()), + registry: None, + registry_applied: Cell::new(0), } } } @@ -309,11 +571,38 @@ impl ParleyTextShaper { Self::default() } + /// 创建整形器并接入会话级 @font-face 字体注册表。 + /// + /// 注册表中的 face 在此后每次整形 / 解析前增量注入(注册即生效, + /// 无需重建整形器);`registry` 内部按 `Arc` 共享,克隆廉价。 + #[must_use] + pub fn with_registry(registry: &FontRegistry) -> Self { + Self { + registry: Some(registry.clone()), + ..Self::default() + } + } + /// 按字体族列表解析出可用字体的文件字节。 /// - /// 语义见 [`FontResolver::resolve_font`]。 + /// 语义见 [`FontResolver::resolve_font`];整形器接入的注册表(见 + /// [`ParleyTextShaper::with_registry`])同样参与命中。 pub fn resolve_font(&self, families: &[String]) -> Option<ResolvedFont> { - FontResolver::new().resolve_font(families) + if families.is_empty() { + return None; + } + let mut font_context = self.font_context.borrow_mut(); + self.sync_registry(&mut font_context); + resolve_font_in(&mut font_context, families, 400, FontStyle::Normal) + } + + /// 把注册表的新 face 增量注入 `font_context`(未接入注册表时空操作)。 + fn sync_registry(&self, font_context: &mut parley::FontContext) { + if let Some(registry) = &self.registry { + let mut applied = self.registry_applied.get(); + registry.sync_into(font_context, &mut applied); + self.registry_applied.set(applied); + } } /// 按样式对文本做单行 parley 布局(不折行)。 @@ -330,6 +619,8 @@ impl ParleyTextShaper { let family_list = style.families.join(", "); let mut font_context = self.font_context.borrow_mut(); + // @font-face 注册面增量注入(注册即生效) + self.sync_registry(&mut font_context); let mut layout_context = self.layout_context.borrow_mut(); let mut builder = layout_context.ranged_builder(&mut font_context, text, 1.0, false); builder.push_default(StyleProperty::FontFamily(parley::FontFamily::Source( @@ -795,4 +1086,251 @@ mod tests { assert_eq!(notdef, 0, "混排文本不得有 notdef"); } } + + // ===== @font-face 注册表(K4 Web 字体 T2)===== + + /// 读取 tests/data 下的测试字体字节(Space Mono,OFL,见目录 README)。 + fn test_font(name: &str) -> Vec<u8> { + std::fs::read( + std::path::Path::new(env!("CARGO_MANIFEST_DIR")) + .join("tests/data") + .join(name), + ) + .unwrap_or_else(|error| panic!("read test font {name}: {error}")) + } + + fn face_descriptor(family: &str, weight: u16, style: FontStyle) -> FontFaceDescriptor { + FontFaceDescriptor { + family: family.to_owned(), + weight, + style, + } + } + + #[test] + fn registry_rejects_invalid_font_data_and_empty_family() { + let registry = FontRegistry::new(); + assert_eq!( + registry.register( + b"not a font".to_vec(), + face_descriptor("NextyInvalid", 400, FontStyle::Normal) + ), + Err(FontRegistryError::InvalidFontData), + "非字体字节必须被拒绝且不入注册表" + ); + assert_eq!( + registry.register( + test_font("SpaceMono-Regular.ttf"), + face_descriptor(" ", 400, FontStyle::Normal) + ), + Err(FontRegistryError::EmptyFamily), + "空族名描述符必须被拒绝" + ); + } + + #[test] + fn registry_multi_weight_nearest_match() { + // 同一 CSS 族名注册两个 face(声明名与字体内部族名解耦是 + // @font-face 的核心语义):Regular 声明为 400、Bold 声明为 700。 + let registry = FontRegistry::new(); + let regular = test_font("SpaceMono-Regular.ttf"); + let bold = test_font("SpaceMono-Bold.ttf"); + registry + .register( + regular.clone(), + face_descriptor("NextyWeightTest", 400, FontStyle::Normal), + ) + .expect("register regular"); + registry + .register( + bold.clone(), + face_descriptor("NextyWeightTest", 700, FontStyle::Normal), + ) + .expect("register bold"); + let resolver = FontResolver::with_registry(®istry); + let family = ["NextyWeightTest".to_owned()]; + + // 期望 400 / 700 精确命中对应 face + let resolved_400 = resolver + .resolve_font_with(&family, 400, FontStyle::Normal) + .expect("weight 400 resolves"); + assert_eq!( + resolved_400.data().as_ref(), + regular.as_slice(), + "期望 400 命中 Regular face" + ); + let resolved_700 = resolver + .resolve_font_with(&family, 700, FontStyle::Normal) + .expect("weight 700 resolves"); + assert_eq!( + resolved_700.data().as_ref(), + bold.as_slice(), + "期望 700 命中 Bold face" + ); + + // CSS Fonts §5.2 就近匹配:期望 600 → ≥600 升序 → 700 + let resolved_600 = resolver + .resolve_font_with(&family, 600, FontStyle::Normal) + .expect("weight 600 resolves"); + assert_eq!(resolved_600.data().as_ref(), bold.as_slice()); + // 期望 500 → 400–500 区间先查 ≥500(无 500±),再 <500 降序 → 400 + let resolved_500 = resolver + .resolve_font_with(&family, 500, FontStyle::Normal) + .expect("weight 500 resolves"); + assert_eq!(resolved_500.data().as_ref(), regular.as_slice()); + // 期望 300 → <400 降序(无),再 >300 升序 → 400 + let resolved_300 = resolver + .resolve_font_with(&family, 300, FontStyle::Normal) + .expect("weight 300 resolves"); + assert_eq!(resolved_300.data().as_ref(), regular.as_slice()); + } + + #[test] + fn registry_style_italic_preferred() { + // 描述符驱动匹配:Regular 字节声明为 normal、Bold 字节声明为 + // italic,同族两 face 按 style 匹配(weight 同为 400)。 + let registry = FontRegistry::new(); + let regular = test_font("SpaceMono-Regular.ttf"); + let bold = test_font("SpaceMono-Bold.ttf"); + registry + .register( + regular.clone(), + face_descriptor("NextyStyleTest", 400, FontStyle::Normal), + ) + .expect("register normal face"); + registry + .register( + bold.clone(), + face_descriptor("NextyStyleTest", 400, FontStyle::Italic), + ) + .expect("register italic face"); + let resolver = FontResolver::with_registry(®istry); + let family = ["NextyStyleTest".to_owned()]; + + let italic = resolver + .resolve_font_with(&family, 400, FontStyle::Italic) + .expect("italic desired resolves"); + assert_eq!( + italic.data().as_ref(), + bold.as_slice(), + "italic 请求命中 italic 声明 face" + ); + let normal = resolver + .resolve_font_with(&family, 400, FontStyle::Normal) + .expect("normal desired resolves"); + assert_eq!(normal.data().as_ref(), regular.as_slice()); + + // 族内只有 normal face 时,italic 请求退到 normal face(CSS Fonts §5.2) + let only_normal = FontRegistry::new(); + only_normal + .register( + regular.clone(), + face_descriptor("NextyItalicFallback", 400, FontStyle::Normal), + ) + .expect("register"); + let resolved = FontResolver::with_registry(&only_normal) + .resolve_font_with(&["NextyItalicFallback".to_owned()], 400, FontStyle::Italic) + .expect("italic falls back to normal face"); + assert_eq!(resolved.data().as_ref(), regular.as_slice()); + } + + #[test] + fn registry_miss_falls_back_to_system_fonts() { + let registry = FontRegistry::new(); + registry + .register( + test_font("SpaceMono-Regular.ttf"), + face_descriptor("NextyHitFamily", 400, FontStyle::Normal), + ) + .expect("register"); + let resolver = FontResolver::with_registry(®istry); + + // 注册族命中注册字节(旧签名路径,默认 400/normal) + let hit = resolver + .resolve_font(&["NextyHitFamily".to_owned()]) + .expect("registered family resolves"); + assert_eq!( + hit.data().as_ref(), + test_font("SpaceMono-Regular.ttf").as_slice(), + "注册族必须命中注册字节" + ); + + // 未注册族走既有系统字体回退;同一解析器两次调用结果一致 + let miss = resolver + .resolve_font(&["nexty-no-such-family-xyz".to_owned()]) + .expect("system fallback"); + assert!(!miss.data().is_empty(), "回退字体字节非空"); + let miss_again = resolver + .resolve_font(&["nexty-no-such-family-xyz".to_owned()]) + .expect("system fallback again"); + assert_eq!(miss.id(), miss_again.id(), "同一解析器的回退结果必须确定"); + } + + #[test] + fn registered_family_shapes_with_registered_font() { + let registry = FontRegistry::new(); + let regular = test_font("SpaceMono-Regular.ttf"); + registry + .register( + regular.clone(), + face_descriptor("NextyShapeTest", 400, FontStyle::Normal), + ) + .expect("register"); + let shaper = ParleyTextShaper::with_registry(®istry); + + let shaped = shaper + .shape("Hello Web Font", &style(&["NextyShapeTest"], 16.0)) + .expect("shape with registered family"); + assert!(!shaped.glyphs.is_empty()); + assert_eq!(shaped.fonts.len(), 1, "单族单 face 文本只应命中一个字体"); + assert_eq!( + shaped.fonts[0].data().as_ref(), + regular.as_slice(), + "整形产出的字体必须是注册字节(@font-face 命中)" + ); + assert!(shaped.width > 0.0); + assert!( + shaped + .glyphs + .iter() + .all(|glyph| (glyph.font as usize) < shaped.fonts.len()), + "font 下标均在字体表内" + ); + assert_eq!( + shaped.glyphs.iter().filter(|glyph| glyph.id == 0).count(), + 0, + "Latin 文本不得产出 notdef 豆腐块" + ); + + // 同一注册字体的第二次整形共享同一份字节快照——注册字体走与系统 + // 字体相同的 (blob id, face index) 缓存路径 + let again = shaper + .shape("Second run", &style(&["NextyShapeTest"], 16.0)) + .expect("second shape"); + assert!( + std::sync::Arc::ptr_eq(shaped.fonts[0].data(), again.fonts[0].data()), + "注册字体的字节快照必须跨整形共享" + ); + + // 注册表跨消费方共享:解析器与整形器拿到同一 blob id + let resolved = FontResolver::with_registry(®istry) + .resolve_font(&["NextyShapeTest".to_owned()]) + .expect("resolver hit"); + assert_eq!( + resolved.id(), + shaped.fonts[0].id(), + "注册字体 blob id 跨消费方一致" + ); + + // 未接入注册表的整形器不消费注册面(with_registry 是唯一接线点) + let plain = ParleyTextShaper::new(); + let fallback = plain + .shape("Hello", &style(&["NextyShapeTest"], 16.0)) + .expect("unregistered shaper falls back to system"); + assert_ne!( + fallback.fonts[0].id(), + shaped.fonts[0].id(), + "未接线整形器不得命中注册字体" + ); + } } diff --git a/crates/nexty-text/tests/data/OFL.txt b/crates/nexty-text/tests/data/OFL.txt new file mode 100644 index 0000000..a72b0a7 --- /dev/null +++ b/crates/nexty-text/tests/data/OFL.txt @@ -0,0 +1,93 @@ +Copyright 2016 The Space Mono Project Authors (https://github.com/googlefonts/spacemono) + +This Font Software is licensed under the SIL Open Font License, Version 1.1. +This license is copied below, and is also available with a FAQ at: +http://scripts.sil.org/OFL + + +----------------------------------------------------------- +SIL OPEN FONT LICENSE Version 1.1 - 26 February 2007 +----------------------------------------------------------- + +PREAMBLE +The goals of the Open Font License (OFL) are to stimulate worldwide +development of collaborative font projects, to support the font creation +efforts of academic and linguistic communities, and to provide a free and +open framework in which fonts may be shared and improved in partnership +with others. + +The OFL allows the licensed fonts to be used, studied, modified and +redistributed freely as long as they are not sold by themselves. The +fonts, including any derivative works, can be bundled, embedded, +redistributed and/or sold with any software provided that any reserved +names are not used by derivative works. The fonts and derivatives, +however, cannot be released under any other type of license. The +requirement for fonts to remain under this license does not apply +to any document created using the fonts or their derivatives. + +DEFINITIONS +"Font Software" refers to the set of files released by the Copyright +Holder(s) under this license and clearly marked as such. This may +include source files, build scripts and documentation. + +"Reserved Font Name" refers to any names specified as such after the +copyright statement(s). + +"Original Version" refers to the collection of Font Software components as +distributed by the Copyright Holder(s). + +"Modified Version" refers to any derivative made by adding to, deleting, +or substituting -- in part or in whole -- any of the components of the +Original Version, by changing formats or by porting the Font Software to a +new environment. + +"Author" refers to any designer, engineer, programmer, technical +writer or other person who contributed to the Font Software. + +PERMISSION & CONDITIONS +Permission is hereby granted, free of charge, to any person obtaining +a copy of the Font Software, to use, study, copy, merge, embed, modify, +redistribute, and sell modified and unmodified copies of the Font +Software, subject to the following conditions: + +1) Neither the Font Software nor any of its individual components, +in Original or Modified Versions, may be sold by itself. + +2) Original or Modified Versions of the Font Software may be bundled, +redistributed and/or sold with any software, provided that each copy +contains the above copyright notice and this license. These can be +included either as stand-alone text files, human-readable headers or +in the appropriate machine-readable metadata fields within text or +binary files as long as those fields can be easily viewed by the user. + +3) No Modified Version of the Font Software may use the Reserved Font +Name(s) unless explicit written permission is granted by the corresponding +Copyright Holder. This restriction only applies to the primary font name as +presented to the users. + +4) The name(s) of the Copyright Holder(s) or the Author(s) of the Font +Software shall not be used to promote, endorse or advertise any +Modified Version, except to acknowledge the contribution(s) of the +Copyright Holder(s) and the Author(s) or with their explicit written +permission. + +5) The Font Software, modified or unmodified, in part or in whole, +must be distributed entirely under this license, and must not be +distributed under any other license. The requirement for fonts to +remain under this license does not apply to any document created +using the Font Software. + +TERMINATION +This license becomes null and void if any of the above conditions are +not met. + +DISCLAIMER +THE FONT SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, +EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO ANY WARRANTIES OF +MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT +OF COPYRIGHT, PATENT, TRADEMARK, OR OTHER RIGHT. IN NO EVENT SHALL THE +COPYRIGHT HOLDER BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, +INCLUDING ANY GENERAL, SPECIAL, INDIRECT, INCIDENTAL, OR CONSEQUENTIAL +DAMAGES, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING +FROM, OUT OF THE USE OR INABILITY TO USE THE FONT SOFTWARE OR FROM +OTHER DEALINGS IN THE FONT SOFTWARE. diff --git a/crates/nexty-text/tests/data/README.md b/crates/nexty-text/tests/data/README.md new file mode 100644 index 0000000..49d9500 --- /dev/null +++ b/crates/nexty-text/tests/data/README.md @@ -0,0 +1,11 @@ +# 测试字体(仅测试资产,非 cargo 依赖) + +Space Mono(Regular / Bold),SIL Open Font License 1.1(见同目录 `OFL.txt`)。 + +- 来源:<https://github.com/google/fonts/tree/main/ofl/spacemono> +- 快照 commit:`8b0a1d0f5983c89bc2b93f1b5fb55f9e252744b5`(2026-10-31 下载) +- 用途:crates/nexty-text 的 @font-face 注册表(`FontRegistry`)集成测试—— + 经描述符声明为测试族名(CSS 声明名与字体内部族名解耦),供 + weight/style 就近匹配与整形归属断言使用。 +- 合规说明:本字体是随仓库分发的测试资产而非 cargo 依赖,不在 + deny.toml 依赖白名单管辖范围;OFL 许可合规记录进 K4 轮 T4 ADR。 diff --git a/crates/nexty-text/tests/data/SpaceMono-Bold.ttf b/crates/nexty-text/tests/data/SpaceMono-Bold.ttf new file mode 100644 index 0000000000000000000000000000000000000000..2c4f2682f915d988e7314544ff7c9e38c8c733f5 GIT binary patch literal 98232 zcmd44dwiV5bvHiq>|I)2c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hByRd$1hzymzo} z>c>7hz&nLD>%A(MW4}2E9l|JVHQU?*>?a@MKiGNL8$OQ3lTS}fKAw8!sH=wcYaA}N zp0N(M;d&$cyU|r{z?EUSbdVL^S~^QyI$Q14pyR8@Ce+#+uJ%T#zb*WN#U@;Bk7fMa zi1p#EjG~F6<08><iFj~@M&EQe@eSTxZ=9GXPPB^?^Tmlp;>7jh#0}!ajpD>&apKRh ez538w!P|vxbpIBpe|_-$fchAAVb<f&^ZpyK&VRK4 literal 0 HcmV?d00001 diff --git a/crates/nexty-text/tests/data/SpaceMono-Regular.ttf b/crates/nexty-text/tests/data/SpaceMono-Regular.ttf new file mode 100644 index 0000000000000000000000000000000000000000..1cfa3653dc8ddb7aa9f4ef1c9c581e9516137e6e GIT binary patch literal 99356 zcmd4433!~vkvHD`&M9eh--pL@=+<a-AC_f#Ji29hEXlGh`IO`nu#IhuW55_eIBh}* zVI9Icgs=%AEFoiagk-&}Kb9pd%aSbXIIMAuAuLN0Hep%9@(~z+zv_P9nRiAb+py37 zdH#mhywh*>Rb5?GT~*z~IAbgwe~c`xx2wBn?CI4vGd^i!j6dHyv~<~@@49>e<5Rz2 zEbpG)Wy}4a{Numa7{6{KW7emaE~}|O<XM*k*!xh+#D?vYJHNfS?M=p#Uu4V@*synx zBg>cn3}fz3@&54Uom;j~)fjGIEIW^}6x)``t9Bwk4ec56Y2C8zn$4HL)IG{r<=u?u zv#pyZH<r))^E}jFg!j!`kzqb#PQiD;u;Q)T_w4(pE&sO#-#=z7=@;9s+%Q@6FB{*& zt9uzUeY$;e-%jJ=)H1x^2YAPh$?co=D-ZmP@y@$3;Fot^dDWgDEqQi6<9%x|zVGea zy=kZ8%In@ie~STsiV<!&`-dO===TNdQ``T<QVs7ShrRWm->9O`-vsBbV+o;uQg#{_ z;H#M_l#73a&WX@B7*jUly-(RG%gLAYSNT1`D4(%Wl-j~fDCuQu*;nxD<`f$<;H^>F z$nVA*rW{ueBL7bL$$!o2*(b>5rUZkcFva*FW9NO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a literal 0 HcmV?d00001 From 866ee3915a60437aa6c62421166e1c2f4ae47a42 Mon Sep 17 00:00:00 2001 From: zwork <zwork@local> Date: Sat, 31 Oct 2026 18:30:03 +0800 Subject: [PATCH 10/14] [paint] FillRoundedRect/StrokeRoundedRect/FillGradient commands, CSS 5.5 radius scaling + stroke inset in facade (0.1.8) --- ..._ca7e797f-14f7-4cd4-a65e-6a69d7418103.json | 1 + ...24fdb88882b47c23cc0e0c80a30c7d53759.source | 1140 +++++++++++++++++ ...sion_164476f9d97ffaabe4f6dc9715b6aad5.json | 1 + ...4f7-4cd4-a65e-6a69d7418103-35569b193b.json | 14 + ...f9d97ffaabe4f6dc9715b6aad5-5e056c09de.json | 14 + crates/nexty-paint/Cargo.toml | 2 +- crates/nexty-paint/src/lib.rs | 911 ++++++++++++- 7 files changed, 2080 insertions(+), 3 deletions(-) create mode 100644 crates/nexty-paint/.mimosa/hook-state/sess_ca7e797f-14f7-4cd4-a65e-6a69d7418103.json create mode 100644 crates/nexty-paint/.mimosa/hook-state/sess_ca7e797f-14f7-4cd4-a65e-6a69d7418103.mv3a7ihc-51808-6942f59cfa.baseline/b1a35a68f14e696205874893c07fd24fdb88882b47c23cc0e0c80a30c7d53759.source create mode 100644 crates/nexty-paint/.mimosa/hook-state/session_164476f9d97ffaabe4f6dc9715b6aad5.json create mode 100644 crates/nexty-paint/.mimosa/hook-status/sess_ca7e797f-14f7-4cd4-a65e-6a69d7418103-35569b193b.json create mode 100644 crates/nexty-paint/.mimosa/hook-status/session_164476f9d97ffaabe4f6dc9715b6aad5-5e056c09de.json diff --git a/crates/nexty-paint/.mimosa/hook-state/sess_ca7e797f-14f7-4cd4-a65e-6a69d7418103.json b/crates/nexty-paint/.mimosa/hook-state/sess_ca7e797f-14f7-4cd4-a65e-6a69d7418103.json new file mode 100644 index 0000000..4ecb71b --- /dev/null +++ b/crates/nexty-paint/.mimosa/hook-state/sess_ca7e797f-14f7-4cd4-a65e-6a69d7418103.json @@ -0,0 +1 @@ +{"touched":["D:\\Nexty\\crates\\nexty-paint\\src\\lib.rs"],"bashMutation":false,"reportedFindings":[],"findingEvents":[],"baseline":{"storageId":"mv3a7ihc-51808-6942f59cfa","createdAt":"2026-10-11T03:46:47.760Z","files":{"src/lib.rs":{"existed":true,"snapshot":"b1a35a68f14e696205874893c07fd24fdb88882b47c23cc0e0c80a30c7d53759.source"}},"complete":false,"candidateLimit":5000,"discoveredFiles":0,"capturedFiles":1,"truncated":false,"omittedAtLeast":0,"firstOmitted":"","errors":[{"stage":"baseline-capture","target":".","reason":"global task baseline was unavailable; captured only the touched file"},{"stage":"baseline-snapshot","target":"../nexty-chrome/src/pipeline.rs","reason":"file is outside project"},{"stage":"baseline-snapshot","target":"../nexty-chrome/src/ui.rs","reason":"file is outside project"},{"stage":"baseline-snapshot","target":"../nexty-chrome/src/ui.rs","reason":"file is outside project"}]},"stateErrors":[],"omittedReportedFindings":0,"omittedFindingEvents":0,"processing":null,"updatedAt":"2026-10-11T03:49:34.985Z"} \ No newline at end of file diff --git a/crates/nexty-paint/.mimosa/hook-state/sess_ca7e797f-14f7-4cd4-a65e-6a69d7418103.mv3a7ihc-51808-6942f59cfa.baseline/b1a35a68f14e696205874893c07fd24fdb88882b47c23cc0e0c80a30c7d53759.source b/crates/nexty-paint/.mimosa/hook-state/sess_ca7e797f-14f7-4cd4-a65e-6a69d7418103.mv3a7ihc-51808-6942f59cfa.baseline/b1a35a68f14e696205874893c07fd24fdb88882b47c23cc0e0c80a30c7d53759.source new file mode 100644 index 0000000..f939e0e --- /dev/null +++ b/crates/nexty-paint/.mimosa/hook-state/sess_ca7e797f-14f7-4cd4-a65e-6a69d7418103.mv3a7ihc-51808-6942f59cfa.baseline/b1a35a68f14e696205874893c07fd24fdb88882b47c23cc0e0c80a30c7d53759.source @@ -0,0 +1,1140 @@ +//! Nexty 绘制 facade:自有绘制指令 + 可替换光栅后端。 +//! +//! 上游:`vello_cpu`(CPU 光栅,sparse strips)。GPU 后端 `vello_hybrid` 依赖 +//! wgpu device/surface,由 chrome 层提供后接入——本轮从本 crate 依赖中摘除, +//! [`Rasterizer`] trait 即双后端接缝。决策与调研见 +//! `docs/decisions/2026-10-01-crate-selection.md`。 +//! +//! 指令集:`FillRect` / `StrokeRect` / `DrawText` / `DrawImage`, +//! 后续消费方(layout)需要什么指令再扩展什么。 +//! +//! 上游:`vello_cpu`(CPU 光栅,sparse strips)+ `image`(图片解码)。 +//! **解码归属**:解码器只在 [`decode`] 内出现,产出自有类型 [`Image`], +//! 上游类型不外泄(AGENTS.md 硬规则)。只解码不做编码与图像处理—— +//! 裁剪缩放由 layout 算矩形、paint 按矩形采样表达。 +//! +//! 上游类型一律不得出现在本 crate 的 pub 导出中(AGENTS.md 硬规则)。 +//! +//! **渲染隔离**:上游对未支持特性是 panic 而非返回错误,故渲染必须在独立线程 +//! 执行并由 `catch_unwind` 兜底(由 chrome 层持有)。因此 workspace 与各 crate +//! 一律不得设置 `panic = "abort"`(会禁用 unwind,使兜底失效)。 + +#![forbid(unsafe_code)] + +#[cfg(feature = "cpu")] +use std::collections::HashMap; +#[cfg(feature = "cpu")] +use std::sync::Arc; + +/// 图片解码错误。 +#[derive(Debug, Clone, PartialEq, Eq)] +pub enum DecodeError { + /// 字节不是受支持的图片格式,或格式数据损坏。 + /// + /// 上游解码器的错误类型不得外泄,故折叠为单一变体:调用方(chrome 层) + /// 对解码失败的处理是「跳过该资源」,不需要区分具体原因。 + InvalidImage, + /// 图像尺寸为0 或超出可渲染范围。 + SizeUnsupported, +} + +/// 从字节流解码一幅图片(格式由内容嗅探,不依赖扩展名)。 +/// +/// 支持 PNG / JPEG / GIF / WebP(编译期 feature 决定)。产出非预乘 RGBA8, +/// 供 [`Command::DrawImage`] 消费。 +/// +/// # Errors +/// +/// 字节无法识别为受支持格式、格式数据损坏、或尺寸不可渲染时返回 [`DecodeError`]。 +/// +/// 上游 `image` 系列的错误一律映射为 [`DecodeError::InvalidImage`],不引入 +/// `image::error::ImageError`——依赖类型不得出现在 pub 导出中。 +#[cfg(feature = "cpu")] +pub fn decode(bytes: &[u8]) -> Result<Image, DecodeError> { + // 尺寸上限与光栅目标一致(vello 的渲染目标为 u16 像素), + // 避免解出一幅无法绘制的巨图。 + const MAX_DIMENSION: u32 = 65535; + + let reader = image::ImageReader::new(std::io::Cursor::new(bytes)) + .with_guessed_format() + .map_err(|_| DecodeError::InvalidImage)?; + let decoded = reader.decode().map_err(|_| DecodeError::InvalidImage)?; + + let (width, height) = (decoded.width(), decoded.height()); + if width == 0 || height == 0 || width > MAX_DIMENSION || height > MAX_DIMENSION { + return Err(DecodeError::SizeUnsupported); + } + + // 统一转RGBA8(灰度 / 调色板 / RGB 均在此归一),行优先连续排列。 + let rgba = decoded.into_rgba8(); + Ok(Image::new(width, height, rgba.into_raw())) +} + +/// 像素尺寸。 +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +pub struct Size { + /// 宽度,px。 + pub width: u32, + /// 高度,px。 + pub height: u32, +} + +/// 非预乘 RGBA 颜色。 +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +pub struct Color { + /// 红通道。 + pub r: u8, + /// 绿通道。 + pub g: u8, + /// 蓝通道。 + pub b: u8, + /// alpha 通道。 + pub a: u8, +} + +impl Color { + /// 不透明纯色。 + #[must_use] + pub const fn opaque(r: u8, g: u8, b: u8) -> Self { + Self { r, g, b, a: 0xff } + } +} + +/// 轴对齐矩形。 +#[derive(Debug, Clone, Copy, PartialEq)] +pub struct Rect { + /// 左上角 x,px(可为负,越界部分被裁剪)。 + pub x: f32, + /// 左上角 y,px。 + pub y: f32, + /// 宽,px。 + pub width: f32, + /// 高,px。 + pub height: f32, +} + +/// 一个字形(文本 run 内;`y` 相对基线,负值在基线上方)。 +#[derive(Debug, Clone, Copy, PartialEq)] +pub struct TextGlyph { + /// 字体内部字形编号。 + pub id: u32, + /// 相对基线原点的水平偏移,px。 + pub x: f32, + /// 相对基线的垂直偏移,px。 + pub y: f32, + /// 所属字体在 [`Command::DrawText::fonts`] 中的下标(text 层按脚本 + /// 回退后一条 run 可能跨多个字体)。 + pub font: u32, +} + +/// 一条绘制指令。 +#[derive(Debug, Clone, PartialEq)] +pub enum Command { + /// 用纯色填充矩形;后绘制的矩形按 src-over 混合叠加。 + FillRect { + /// 目标矩形。 + rect: Rect, + /// 填充色。 + color: Color, + }, + /// 用纯色描边矩形(线宽向内向外各半),边框绘制用。 + StrokeRect { + /// 目标矩形(描边中心线)。 + rect: Rect, + /// 描边色。 + color: Color, + /// 线宽,px;非正值不绘制。 + width: f32, + }, + /// 绘制一行字形。 + /// + /// 字形必须已经过 text 层整形(字形 id 对应 `fonts[glyph.font]` 字体); + /// `glyphs[i].y` 相对基线,`baseline` 是基线的绝对 y。 + DrawText { + /// 字形序列(x 为绝对坐标,y 相对基线)。 + glyphs: Vec<TextGlyph>, + /// 基线的绝对 y,px。 + baseline: f32, + /// 本次整形实际用到的字体(按脚本回退后可能多于一个)。 + fonts: Vec<ResolvedFont>, + /// 字号,px。 + size: f32, + /// 文本颜色。 + color: Color, + }, + /// 绘制一幅已解码图像。 + /// + /// 像素经 [`Scene::images`] 按下标间接引用,不内联在指令里:`Scene` + /// 每帧都要整体 clone(渲染线程按值接收),内联会让每次 clone 退化成 + /// 大块内存拷贝。 + DrawImage { + /// 目标矩形(图像左上角落点 + 绘制尺寸)。 + rect: Rect, + /// [`Scene::images`] 中的图像下标。 + image: usize, + }, +} + +/// 一幅已解码的图像:非预乘 RGBA8,行优先。 +#[derive(Debug, Clone, PartialEq, Eq)] +pub struct Image { + /// 像素宽。 + pub width: u32, + /// 像素高。 + pub height: u32, + /// 非预乘 RGBA8 字节,长度应为 `width * height * 4`。 + pub data: Vec<u8>, +} + +impl Image { + /// 由像素数据构造图像。 + #[must_use] + pub fn new(width: u32, height: u32, data: Vec<u8>) -> Self { + Self { + width, + height, + data, + } + } + + /// 读取 `(x, y)` 处的 RGBA 分量;越界返回 `None`。 + #[must_use] + pub fn pixel(&self, x: u32, y: u32) -> Option<[u8; 4]> { + if x >= self.width || y >= self.height { + return None; + } + let index = (y as usize * self.width as usize + x as usize) * 4; + self.data + .get(index..index + 4) + .map(|slice| [slice[0], slice[1], slice[2], slice[3]]) + } +} + +/// 一帧的绘制指令列表。 +#[derive(Debug, Clone, Default, PartialEq)] +pub struct Scene { + /// 按绘制顺序排列的指令。 + pub commands: Vec<Command>, + /// 图像资源池;[`Command::DrawImage`] 按下标引用。 + pub images: Vec<Image>, +} + +/// 光栅化结果。 +#[derive(Debug, Clone, PartialEq, Eq)] +pub struct Pixmap { + /// 尺寸。 + pub size: Size, + /// 非预乘 RGBA8 像素,行优先;未被指令覆盖的区域为全透明。 + pub data: Vec<u8>, +} + +impl Pixmap { + /// 读取 `(x, y)` 处像素的 RGBA 分量。 + #[must_use] + pub fn pixel(&self, x: u32, y: u32) -> Option<[u8; 4]> { + if x >= self.size.width || y >= self.size.height { + return None; + } + let index = (y as usize * self.size.width as usize + x as usize) * 4; + Some([ + self.data[index], + self.data[index + 1], + self.data[index + 2], + self.data[index + 3], + ]) + } +} + +/// 字体 / 图像字节的Blob 包装。 +/// +/// vello 的 `Blob` 要求 `AsRef<[u8]>`,但 trait 对象胖指针无法直接满足 +/// `Sized` 约束,故用这个 Sized 包装完成转换。字节按引用计数共享,不复制。 +#[cfg(feature = "cpu")] +#[derive(Clone)] +struct FontBytes(Arc<[u8]>); + +#[cfg(feature = "cpu")] +impl AsRef<[u8]> for FontBytes { + fn as_ref(&self) -> &[u8] { + &self.0 + } +} + +/// 光栅化后端。 +/// +/// 实现方可以是 `vello_cpu`(CPU)或 `vello_hybrid`(CPU/GPU 混合,待接入)。 +/// 调用方须在独立线程中执行并在 `catch_unwind` 内兜底。 +pub trait Rasterizer { + /// 把 [`Scene`] 光栅化为 [`Pixmap`]。 + /// + /// # Errors + /// + /// 尺寸非法或后端不支持场景中的指令时返回 [`RasterError`]。 + fn rasterize(&self, scene: &Scene, size: Size) -> Result<Pixmap, RasterError>; +} + +/// 光栅化错误。 +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +pub enum RasterError { + /// 宽或高为 0。 + EmptySize, + /// 尺寸超出后端上限(vello_cpu 的渲染目标为 u16 像素)。 + SizeExceedsLimit, + /// 后端不支持场景中的指令。 + UnsupportedCommand, +} + +/// [`Rasterizer`] 的 vello_cpu 实现(CPU 光栅)。 +/// [`Rasterizer`] 的 vello_cpu 实现(CPU 光栅)。 +/// +/// `vello_cpu` 对未支持特性是 panic 而非返回错误;按渲染隔离规则, +/// 调用方须把本实现放进独立线程并以 `catch_unwind` 兜底。 +/// +/// 文本渲染的字体数据由 text 层整形结果直接提供([`Command::DrawText::fonts`]): +/// 按脚本回退后一条 run 可跨多个字体,字形归属在整形期已确定,光栅层按 +/// `glyph.font` 分组用对应字体渲染。 +#[cfg(feature = "cpu")] +#[derive(Debug, Default)] +pub struct VelloCpuRasterizer; + +#[cfg(feature = "cpu")] +impl VelloCpuRasterizer { + /// 创建 CPU 光栅后端。 + #[must_use] + pub fn new() -> Self { + Self + } +} + +#[cfg(feature = "cpu")] +impl Rasterizer for VelloCpuRasterizer { + fn rasterize(&self, scene: &Scene, size: Size) -> Result<Pixmap, RasterError> { + if size.width == 0 || size.height == 0 { + return Err(RasterError::EmptySize); + } + let Ok(width) = u16::try_from(size.width) else { + return Err(RasterError::SizeExceedsLimit); + }; + let Ok(height) = u16::try_from(size.height) else { + return Err(RasterError::SizeExceedsLimit); + }; + + let mut context = vello_cpu::RenderContext::new(width, height); + let mut resources = vello_cpu::Resources::new(); + for command in &scene.commands { + match command { + Command::FillRect { rect, color } => { + context.set_paint(vello_cpu::peniko::Color::from_rgba8( + color.r, color.g, color.b, color.a, + )); + context.fill_rect(&vello_cpu::kurbo::Rect::new( + f64::from(rect.x), + f64::from(rect.y), + f64::from(rect.x) + f64::from(rect.width), + f64::from(rect.y) + f64::from(rect.height), + )); + } + Command::StrokeRect { rect, color, width } => { + if *width <= 0.0 { + continue; + } + context.set_paint(vello_cpu::peniko::Color::from_rgba8( + color.r, color.g, color.b, color.a, + )); + context.set_stroke(vello_cpu::kurbo::Stroke::new(f64::from(*width))); + context.stroke_rect(&vello_cpu::kurbo::Rect::new( + f64::from(rect.x), + f64::from(rect.y), + f64::from(rect.x) + f64::from(rect.width), + f64::from(rect.y) + f64::from(rect.height), + )); + } + Command::DrawText { + glyphs, + baseline, + fonts, + size, + color, + } => { + context.set_paint(vello_cpu::peniko::Color::from_rgba8( + color.r, color.g, color.b, color.a, + )); + // 按字体下标分组(组内字形连续,通常只有一组):回退后 + // 一条 run 可跨多个字体,字形 id 只对所属字体有意义 + let mut groups: Vec<(u32, Vec<&TextGlyph>)> = Vec::new(); + for glyph in glyphs { + match groups.last_mut() { + Some((index, group)) if *index == glyph.font => { + group.push(glyph); + } + _ => groups.push((glyph.font, vec![glyph])), + } + } + for (font_index, group) in groups { + // 下标越界(调用方构造错误)时跳过该组而非 panic + let Some(font) = fonts.get(font_index as usize) else { + continue; + }; + // 字体数据按引用计数共享给 vello 的 Blob + let bytes: Arc<dyn AsRef<[u8]> + Send + Sync> = + Arc::new(FontBytes(font.data().clone())); + let font_data = vello_cpu::peniko::FontData::new( + vello_cpu::peniko::Blob::new(bytes), + font.index(), + ); + let glyphs = group.iter().map(|glyph| vello_cpu::Glyph { + id: glyph.id, + x: glyph.x, + y: baseline + glyph.y, + }); + context + .glyph_run(&mut resources, &font_data) + .font_size(*size) + .fill_glyphs(glyphs); + } + } + Command::DrawImage { rect, image } => { + // 下标越界(资源表被改过)时跳过该指令而不是 panic: + // 渲染隔离虽能兜底,但跳过远好过整帧失败。 + let Some(source) = scene.images.get(*image) else { + continue; + }; + draw_image(&mut context, &mut resources, source, rect); + } + } + } + + let mut target = vello_cpu::Pixmap::new(width, height); + context.render(&mut target, &mut resources); + + // vello_cpu 输出预乘像素;facade 契约为非预乘,用上游自带转换 + let data = target + .take_unpremultiplied() + .iter() + .flat_map(|pixel| [pixel.r, pixel.g, pixel.b, pixel.a]) + .collect(); + Ok(Pixmap { size, data }) + } +} + +/// 绘制一幅已解码图像到目标矩形。 +/// +/// vello_cpu 没有专门的 image 绘制入口(只有 `fill_path` / `glyph_run`), +/// 所以这里把图像作为 `Brush::Image` 填进矩形路径。缩放由 paint transform +/// 表达:源图像 1px 对应 `scale` 个目标 px。 +/// +/// 尺寸越界(转 u16 失败)或数据长度不符时**直接返回不绘制**——绘制路径 +/// 无法返回错误,静默跳过优于让上游 panic(渲染隔离虽兜底,但会丢掉整帧)。 +#[cfg(feature = "cpu")] +fn draw_image( + context: &mut vello_cpu::RenderContext, + resources: &mut vello_cpu::Resources, + source: &Image, + rect: &Rect, +) { + // 图像尺寸须能放进 vello 的 u16 渲染目标 + let (Ok(width), Ok(height)) = (u16::try_from(source.width), u16::try_from(source.height)) + else { + return; + }; + let expected = (source.width as usize) + .saturating_mul(source.height as usize) + .saturating_mul(4); + if source.data.len() < expected || source.width == 0 || source.height == 0 { + return; + } + // 目标矩形宽高为非正时不绘制 + if rect.width <= 0.0 || rect.height <= 0.0 { + return; + } + + // vello 的 Pixmap 存预乘 RGBA8,facade 契约是非预乘,故逐像素转换。 + // 每帧重建 Pixmap 是 CPU 光栅的固有成本(像素本就在内存里)。 + let mut pixmap = vello_cpu::Pixmap::new(width, height); + for y in 0..height { + for x in 0..width { + let index = (y as usize * width as usize + x as usize) * 4; + // 非预乘 → 预乘:各颜色通道乘 alpha。 + // 用整数舍入(+128 >>8)与 vello 内部转换一致,避免浮点误差。 + let alpha = u16::from(source.data[index + 3]); + let premultiply = |channel: u8| ((u16::from(channel) * alpha + 128) >> 8) as u8; + pixmap.set_pixel( + x, + y, + vello_cpu::color::PremulRgba8::from_u8_array([ + premultiply(source.data[index]), + premultiply(source.data[index + 1]), + premultiply(source.data[index + 2]), + source.data[index + 3], + ]), + ); + } + } + // 注册进资源表拿句柄,再组装成 image paint + let image_id = resources.register_image(Arc::new(pixmap)); + let image_source = vello_cpu::ImageSource::opaque_id(image_id); + let brush = vello_cpu::peniko::ImageBrush { + image: image_source, + sampler: Default::default(), + }; + context.set_paint(vello_cpu::PaintType::Image(brush)); + + // 用 paint transform 表达缩放:源 1px → 目标 scale px。 + // 先缩放再平移,使图像左上角对齐 rect 左上角。 + let scale_x = f64::from(rect.width) / f64::from(source.width); + let scale_y = f64::from(rect.height) / f64::from(source.height); + let transform = vello_cpu::kurbo::Affine::scale_non_uniform(scale_x, scale_y).then_translate( + vello_cpu::kurbo::Vec2::new(f64::from(rect.x), f64::from(rect.y)), + ); + context.set_paint_transform(transform); + + // 几何用**场景坐标**(目标矩形),paint transform 只负责把图像的 + // 像素空间映射到同一位置——两者必须指向同一个矩形,否则图像会被 + // 采样到路径之外。 + // kurbo 的 Shape trait 提供 to_path(tolerance),需引入该 trait。 + use vello_cpu::kurbo::Shape as _; + let target_rect = vello_cpu::kurbo::Rect::new( + f64::from(rect.x), + f64::from(rect.y), + f64::from(rect.x) + f64::from(rect.width), + f64::from(rect.y) + f64::from(rect.height), + ); + context.fill_path(&target_rect.to_path(0.1)); + context.reset_paint_transform(); +} + +// 测试需要 CPU 光栅后端与图片解码(`image`),二者同属 `cpu` feature。 +#[cfg(all(test, feature = "cpu"))] +mod tests { + use super::*; + + fn size(width: u32, height: u32) -> Size { + Size { width, height } + } + + fn rect(x: f32, y: f32, width: f32, height: f32) -> Rect { + Rect { + x, + y, + width, + height, + } + } + + fn fill(x: f32, y: f32, width: f32, height: f32, color: Color) -> Command { + Command::FillRect { + rect: rect(x, y, width, height), + color, + } + } + + #[test] + fn fill_rect_covers_exactly_its_area() { + let scene = Scene { + commands: vec![fill(2.0, 1.0, 4.0, 3.0, Color::opaque(255, 0, 0))], + images: Vec::new(), + }; + let pixmap = VelloCpuRasterizer::new() + .rasterize(&scene, size(10, 8)) + .expect("rasterize"); + + assert_eq!(pixmap.size, size(10, 8)); + assert_eq!(pixmap.data.len(), 10 * 8 * 4); + + for y in 0..8u32 { + for x in 0..10u32 { + let pixel = pixmap.pixel(x, y).expect("in bounds"); + let inside = (2..6).contains(&x) && (1..4).contains(&y); + if inside { + assert_eq!(pixel, [255, 0, 0, 255], "({x}, {y}) should be red"); + } else { + assert_eq!(pixel, [0, 0, 0, 0], "({x}, {y}) should stay transparent"); + } + } + } + } + + #[test] + fn later_rects_composite_over_earlier_ones() { + let scene = Scene { + commands: vec![ + fill(0.0, 0.0, 4.0, 4.0, Color::opaque(255, 0, 0)), + fill(2.0, 0.0, 4.0, 4.0, Color::opaque(0, 255, 0)), + ], + images: Vec::new(), + }; + let pixmap = VelloCpuRasterizer::new() + .rasterize(&scene, size(8, 4)) + .expect("rasterize"); + + // 像素中心采样:红色覆盖 [0,4),绿色覆盖 [2,6) + assert_eq!(pixmap.pixel(0, 0), Some([255, 0, 0, 255])); + assert_eq!(pixmap.pixel(2, 0), Some([0, 255, 0, 255])); + assert_eq!(pixmap.pixel(5, 0), Some([0, 255, 0, 255])); + assert_eq!(pixmap.pixel(6, 0), Some([0, 0, 0, 0])); + } + + #[test] + fn alpha_blends_with_src_over() { + // 半透明黑叠在不透明白上 → 灰 + let scene = Scene { + commands: vec![ + fill(0.0, 0.0, 2.0, 2.0, Color::opaque(255, 255, 255)), + Command::FillRect { + rect: rect(0.0, 0.0, 2.0, 2.0), + color: Color { + r: 0, + g: 0, + b: 0, + a: 128, + }, + }, + ], + images: Vec::new(), + }; + let pixmap = VelloCpuRasterizer::new() + .rasterize(&scene, size(2, 2)) + .expect("rasterize"); + + let [r, g, b, a] = pixmap.pixel(0, 0).expect("pixel"); + assert_eq!(a, 255); + // 255 * (1 - 128/255) ≈ 127,光栅化允许 ±1 量化差 + assert!((i16::from(r) - 127).abs() <= 1, "r = {r}"); + assert_eq!(g, r); + assert_eq!(b, r); + } + + #[test] + fn fractional_rects_conserve_coverage() { + // 分数坐标矩形按几何面积做覆盖抗锯齿:部分覆盖 → 部分 alpha + let scene = Scene { + commands: vec![fill(0.5, 0.5, 3.5, 1.0, Color::opaque(0, 0, 255))], + images: Vec::new(), + }; + let pixmap = VelloCpuRasterizer::new() + .rasterize(&scene, size(6, 2)) + .expect("rasterize"); + + // 行内被覆盖的 alpha 总量守恒:x 覆盖 3.5px × y 覆盖 0.5px ≈ 1.75 + for y in [0u32, 1] { + let coverage: f32 = (0..6u32) + .filter_map(|x| pixmap.pixel(x, y)) + .map(|pixel| f32::from(pixel[3]) / 255.0) + .sum(); + assert!( + (coverage - 1.75).abs() < 0.05, + "row {y} coverage = {coverage}" + ); + } + // 未触及的区域保持全透明 + assert_eq!(pixmap.pixel(5, 0), Some([0, 0, 0, 0])); + } + + #[test] + fn empty_size_is_rejected() { + let error = VelloCpuRasterizer::new() + .rasterize(&Scene::default(), size(0, 10)) + .expect_err("zero width"); + assert_eq!(error, RasterError::EmptySize); + + let error = VelloCpuRasterizer::new() + .rasterize(&Scene::default(), size(10, 0)) + .expect_err("zero height"); + assert_eq!(error, RasterError::EmptySize); + } + + #[test] + fn oversize_is_rejected() { + let error = VelloCpuRasterizer::new() + .rasterize(&Scene::default(), size(u32::from(u16::MAX) + 1, 10)) + .expect_err("width over u16"); + assert_eq!(error, RasterError::SizeExceedsLimit); + } + + #[test] + fn empty_scene_yields_transparent_pixmap() { + let pixmap = VelloCpuRasterizer::new() + .rasterize(&Scene::default(), size(3, 3)) + .expect("rasterize"); + assert!(pixmap.data.iter().all(|byte| *byte == 0)); + } + + /// 用 text 层整形一个字符,返回其字形与基线度量。 + fn shape_char(character: char) -> (Vec<TextGlyph>, f32) { + use nexty_text::TextShaper; + let shaper = nexty_text::ParleyTextShaper::new(); + let style = nexty_text::TextStyle { + families: vec!["serif".to_owned()], + size: 32.0, + }; + let text = character.to_string(); + let shaped = shaper.shape(&text, &style).expect("shape"); + let metrics = shaper.metrics(&style).expect("metrics"); + let glyphs = shaped + .glyphs + .iter() + .map(|glyph| TextGlyph { + id: glyph.id, + x: glyph.x, + y: glyph.y, + }) + .collect(); + (glyphs, metrics.ascent) + } + + #[test] + fn draw_text_produces_opaque_pixels() { + let (glyphs, ascent) = shape_char('A'); + let scene = Scene { + commands: vec![Command::DrawText { + glyphs, + baseline: 40.0, + families: vec!["serif".to_owned()], + size: 32.0, + color: Color::opaque(0, 0, 0), + }], + images: Vec::new(), + }; + let pixmap = VelloCpuRasterizer::new() + .rasterize(&scene, size(48, 48)) + .expect("rasterize"); + + // 字形区域内应有大量不透明像素(基线在 40,字形主体在其上方) + let opaque = (0..48u32) + .flat_map(|x| (0..ascent as u32 + 8).map(move |y| (x, y))) + .filter(|(x, y)| pixmap.pixel(*x, *y).is_some_and(|p| p[3] > 200)) + .count(); + assert!(opaque > 20, "字形应产生不透明像素,实际 {opaque}"); + } + + #[test] + fn draw_text_honors_color_and_draw_order() { + let (glyphs, _) = shape_char('A'); + let scene = Scene { + commands: vec![ + Command::FillRect { + rect: rect(0.0, 0.0, 48.0, 48.0), + color: Color::opaque(255, 255, 255), + }, + Command::DrawText { + glyphs, + baseline: 40.0, + families: vec!["serif".to_owned()], + size: 32.0, + color: Color::opaque(255, 0, 0), + }, + ], + images: Vec::new(), + }; + let pixmap = VelloCpuRasterizer::new() + .rasterize(&scene, size(48, 48)) + .expect("rasterize"); + + // 存在偏红的字形像素(抗锯齿边缘允许混色) + let has_red = (0..48u32).any(|x| { + (0..48u32).any(|y| { + pixmap + .pixel(x, y) + .is_some_and(|p| p[3] > 200 && p[0] > 150 && p[1] < 120) + }) + }); + assert!(has_red, "白底上的红色字形应可辨"); + } + + #[test] + fn stroke_rect_draws_outline_only() { + let scene = Scene { + commands: vec![Command::StrokeRect { + rect: rect(2.0, 2.0, 10.0, 10.0), + color: Color::opaque(255, 0, 0), + width: 2.0, + }], + images: Vec::new(), + }; + let pixmap = VelloCpuRasterizer::new() + .rasterize(&scene, size(16, 16)) + .expect("rasterize"); + + // 边框线上有红色 + assert_eq!(pixmap.pixel(2, 2), Some([255, 0, 0, 255])); + assert_eq!(pixmap.pixel(11, 2), Some([255, 0, 0, 255])); + assert_eq!(pixmap.pixel(11, 11), Some([255, 0, 0, 255])); + // 中心保持透明(只描边不填心) + assert_eq!(pixmap.pixel(7, 7), Some([0, 0, 0, 0])); + assert_eq!(pixmap.pixel(6, 6), Some([0, 0, 0, 0])); + } + + #[test] + fn stroke_rect_zero_width_is_noop() { + let scene = Scene { + commands: vec![Command::StrokeRect { + rect: rect(2.0, 2.0, 8.0, 8.0), + color: Color::opaque(255, 0, 0), + width: 0.0, + }], + images: Vec::new(), + }; + let pixmap = VelloCpuRasterizer::new() + .rasterize(&scene, size(16, 16)) + .expect("rasterize"); + assert!(pixmap.data.iter().all(|byte| *byte == 0)); + } + + /// 构造一幅纯色图像。 + fn solid_image(width: u32, height: u32, color: [u8; 4]) -> Image { + Image::new(width, height, color.repeat((width * height) as usize)) + } + + /// 断言像素接近期望颜色(图像采样有±1 的插值舍入误差)。 + fn assert_pixel_near(pixmap: &Pixmap, x: u32, y: u32, expected: [u8; 4]) { + let actual = pixmap.pixel(x, y).expect("pixel in bounds"); + for (index, (got, want)) in actual.iter().zip(expected).enumerate() { + assert!( + i32::from(*got).abs_diff(i32::from(want)) <= 1, + "({x}, {y}) 通道{index}:实际 {got},期望 {want}±1" + ); + } + } + + #[test] + fn draw_image_places_pixels_at_target_rect() { + let scene = Scene { + commands: vec![Command::DrawImage { + rect: rect(2.0, 3.0, 4.0, 5.0), + image: 0, + }], + images: vec![solid_image(4, 5, [0, 128, 255, 255])], + }; + let pixmap = VelloCpuRasterizer::new() + .rasterize(&scene, size(10, 12)) + .expect("rasterize"); + + // 目标矩形内应是图像色 + assert_pixel_near(&pixmap, 2, 3, [0, 128, 255, 255]); + assert_pixel_near(&pixmap, 5, 7, [0, 128, 255, 255]); + // 矩形外保持透明 + assert_eq!(pixmap.pixel(1, 3), Some([0, 0, 0, 0])); + assert_eq!(pixmap.pixel(6, 3), Some([0, 0, 0, 0])); + assert_eq!(pixmap.pixel(2, 2), Some([0, 0, 0, 0])); + assert_eq!(pixmap.pixel(2, 8), Some([0, 0, 0, 0])); + } + + #[test] + fn draw_image_scales_to_target_rect() { + // 2x2 图像画到 4x4:像素应被放大(采样最近邻,仍是纯色) + let scene = Scene { + commands: vec![Command::DrawImage { + rect: rect(0.0, 0.0, 4.0, 4.0), + image: 0, + }], + images: vec![solid_image(2, 2, [255, 0, 0, 255])], + }; + let pixmap = VelloCpuRasterizer::new() + .rasterize(&scene, size(6, 6)) + .expect("rasterize"); + // 整个 4x4 区域都被覆盖 + // 4x4 目标矩形覆盖 [0,4)² + for y in 0..4u32 { + for x in 0..4u32 { + assert_pixel_near(&pixmap, x, y, [255, 0, 0, 255]); + } + } + assert_eq!(pixmap.pixel(5, 5), Some([0, 0, 0, 0])); + } + + #[test] + fn draw_image_clips_at_canvas_edge() { + // 目标矩形部分超出画布:越界部分被裁剪,不panic + let scene = Scene { + commands: vec![Command::DrawImage { + rect: rect(6.0, 6.0, 8.0, 8.0), + image: 0, + }], + images: vec![solid_image(8, 8, [0, 255, 0, 255])], + }; + let pixmap = VelloCpuRasterizer::new() + .rasterize(&scene, size(10, 10)) + .expect("rasterize"); + assert_pixel_near(&pixmap, 7, 7, [0, 255, 0, 255]); + assert_pixel_near(&pixmap, 9, 9, [0, 255, 0, 255]); + assert_eq!(pixmap.pixel(5, 5), Some([0, 0, 0, 0])); + } + + #[test] + fn draw_image_preserves_transparency() { + // 半透明图像:alpha 应体现在结果里 + let scene = Scene { + commands: vec![Command::DrawImage { + rect: rect(0.0, 0.0, 4.0, 4.0), + image: 0, + }], + images: vec![solid_image(4, 4, [255, 255, 255, 128])], + }; + let pixmap = VelloCpuRasterizer::new() + .rasterize(&scene, size(6, 6)) + .expect("rasterize"); + let pixel = pixmap.pixel(2, 2).expect("pixel"); + assert_eq!(pixel[3], 128, "alpha 保持"); + // 非预乘输出:白色半透明 → RGB 应接近 255 + assert!(pixel[0] > 240, "r = {}", pixel[0]); + } + + #[test] + fn draw_image_with_out_of_range_index_is_skipped() { + // 资源表被改过导致下标越界:跳过该指令而不是 panic + let scene = Scene { + commands: vec![Command::DrawImage { + rect: rect(0.0, 0.0, 4.0, 4.0), + image: 7, + }], + images: vec![solid_image(4, 4, [255, 0, 0, 255])], + }; + let pixmap = VelloCpuRasterizer::new() + .rasterize(&scene, size(6, 6)) + .expect("rasterize"); + assert!( + pixmap.data.iter().all(|byte| *byte == 0), + "越界下标应被跳过,画布保持全透明" + ); + } + + #[test] + fn draw_image_with_malformed_data_is_skipped() { + // 数据长度不足:不绘制且不 panic + let scene = Scene { + commands: vec![Command::DrawImage { + rect: rect(0.0, 0.0, 4.0, 4.0), + image: 0, + }], + images: vec![Image::new(4, 4, vec![255, 0, 0])], + }; + let pixmap = VelloCpuRasterizer::new() + .rasterize(&scene, size(6, 6)) + .expect("rasterize"); + assert!(pixmap.data.iter().all(|byte| *byte == 0)); + } + + #[test] + fn draw_image_composites_over_existing_pixels() { + // 图像应按 src-over 叠在已有填充之上 + let scene = Scene { + commands: vec![ + fill(0.0, 0.0, 6.0, 6.0, Color::opaque(0, 0, 255)), + Command::DrawImage { + rect: rect(1.0, 1.0, 4.0, 4.0), + image: 0, + }, + ], + images: vec![solid_image(4, 4, [255, 0, 0, 255])], + }; + let pixmap = VelloCpuRasterizer::new() + .rasterize(&scene, size(6, 6)) + .expect("rasterize"); + assert_pixel_near(&pixmap, 2, 2, [255, 0, 0, 255]); + assert_eq!(pixmap.pixel(0, 0), Some([0, 0, 255, 255]), "蓝底仍可见"); + } + + #[test] + fn image_pixel_accessor_handles_bounds() { + let image = solid_image(2, 2, [1, 2, 3, 4]); + assert_eq!(image.pixel(0, 0), Some([1, 2, 3, 4])); + assert_eq!(image.pixel(1, 1), Some([1, 2, 3, 4])); + assert_eq!(image.pixel(2, 0), None); + assert_eq!(image.pixel(0, 2), None); + } + + /// 生成一张指定颜色的 PNG 字节(用 image 编码,覆盖我们声明支持的格式)。 + fn encode_png(width: u32, height: u32, color: [u8; 4]) -> Vec<u8> { + let mut buffer = Vec::new(); + image::DynamicImage::ImageRgba8(image::RgbaImage::from_pixel( + width, + height, + image::Rgba(color), + )) + .write_to( + &mut std::io::Cursor::new(&mut buffer), + image::ImageFormat::Png, + ) + .expect("encode png"); + buffer + } + + #[test] + fn decode_png_yields_rgba8() { + let bytes = encode_png(3, 2, [10, 20, 30, 255]); + let image = decode(&bytes).expect("decode png"); + assert_eq!((image.width, image.height), (3, 2)); + assert_eq!(image.data.len(), 3 * 2 * 4); + // 所有像素都是同一个颜色 + for y in 0..2u32 { + for x in 0..3u32 { + assert_eq!(image.pixel(x, y), Some([10, 20, 30, 255])); + } + } + } + + #[test] + fn decode_normalizes_rgb_and_grayscale_to_rgba() { + // RGB(无 alpha)解码后 alpha 应为 255 + let mut buffer = Vec::new(); + image::DynamicImage::ImageRgb8(image::RgbImage::from_pixel( + 2, + 2, + image::Rgb([200, 100, 50]), + )) + .write_to( + &mut std::io::Cursor::new(&mut buffer), + image::ImageFormat::Png, + ) + .expect("encode png"); + let image = decode(&buffer).expect("decode rgb png"); + assert_eq!(image.pixel(0, 0), Some([200, 100, 50, 255])); + + // 灰度图应复制到 RGB 三通道 + let mut buffer = Vec::new(); + image::DynamicImage::ImageLuma8(image::GrayImage::from_pixel(2, 2, image::Luma([128]))) + .write_to( + &mut std::io::Cursor::new(&mut buffer), + image::ImageFormat::Png, + ) + .expect("encode png"); + let image = decode(&buffer).expect("decode luma png"); + assert_eq!(image.pixel(1, 1), Some([128, 128, 128, 255])); + } + + #[test] + fn decode_preserves_alpha() { + let bytes = encode_png(1, 1, [1, 2, 3, 128]); + let image = decode(&bytes).expect("decode"); + assert_eq!(image.pixel(0, 0), Some([1, 2, 3, 128])); + } + + #[test] + fn decode_detects_format_by_content_not_extension() { + // 字节里没有文件名线索,格式靠魔数嗅探 + let png = encode_png(2, 2, [9, 9, 9, 255]); + let mut jpeg = Vec::new(); + image::DynamicImage::ImageRgb8(image::RgbImage::from_pixel(2, 2, image::Rgb([9, 9, 9]))) + .write_to( + &mut std::io::Cursor::new(&mut jpeg), + image::ImageFormat::Jpeg, + ) + .expect("encode jpeg"); + // JPEG 魔噪点使像素不完全无损,只断言尺寸与类型 + assert_eq!(decode(&png).expect("png").width, 2); + assert_eq!(decode(&jpeg).expect("jpeg").width, 2); + } + + #[test] + fn decode_rejects_non_image_bytes() { + // HTML 文档不是图片 + let error = decode(b"<!DOCTYPE html><html><body>hi</body></html>").expect_err("not image"); + assert_eq!(error, DecodeError::InvalidImage); + // 空字节 + assert_eq!(decode(&[]).expect_err("empty"), DecodeError::InvalidImage); + } + + #[test] + fn decode_rejects_corrupt_image_data() { + let mut bytes = encode_png(4, 4, [7, 7, 7, 255]); + // 破坏压缩数据(保留魔数,使格式嗅探通过但解码失败) + let tail = bytes.len(); + for byte in bytes.iter_mut().skip(tail / 2).take(16) { + *byte ^= 0xff; + } + assert_eq!( + decode(&bytes).expect_err("corrupt"), + DecodeError::InvalidImage + ); + } + + #[test] + fn decoded_image_feeds_draw_image() { + // 端到端:解码 → 资源池 → 光栅 + let bytes = encode_png(2, 2, [0, 200, 0, 255]); + let image = decode(&bytes).expect("decode"); + let scene = Scene { + commands: vec![Command::DrawImage { + rect: rect(0.0, 0.0, 4.0, 4.0), + image: 0, + }], + images: vec![image], + }; + let pixmap = VelloCpuRasterizer::new() + .rasterize(&scene, size(6, 6)) + .expect("rasterize"); + assert_pixel_near(&pixmap, 1, 1, [0, 200, 0, 255]); + assert_pixel_near(&pixmap, 3, 3, [0, 200, 0, 255]); + } + + /// gif / webp 是 paint 显式开启的 feature,必须与 png/jpeg 一样有解码 + /// 测试——否则「声明支持」与「实际可用」可能脱节。 + #[test] + fn decode_gif_yields_rgba() { + let mut buffer = Vec::new(); + image::DynamicImage::ImageRgba8(image::RgbaImage::from_pixel( + 3, + 2, + image::Rgba([12, 34, 56, 255]), + )) + .write_to( + &mut std::io::Cursor::new(&mut buffer), + image::ImageFormat::Gif, + ) + .expect("encode gif"); + let decoded = decode(&buffer).expect("decode gif"); + assert_eq!((decoded.width, decoded.height), (3, 2)); + assert_eq!(decoded.pixel(0, 0), Some([12, 34, 56, 255])); + } + + #[test] + fn decode_webp_yields_rgba() { + let mut buffer = Vec::new(); + // WebP 有损,断言尺寸与「不透明」而非精确颜色 + image::DynamicImage::ImageRgba8(image::RgbaImage::from_pixel( + 4, + 4, + image::Rgba([200, 100, 50, 255]), + )) + .write_to( + &mut std::io::Cursor::new(&mut buffer), + image::ImageFormat::WebP, + ) + .expect("encode webp"); + let decoded = decode(&buffer).expect("decode webp"); + assert_eq!((decoded.width, decoded.height), (4, 4)); + let pixel = decoded.pixel(2, 2).expect("pixel"); + assert_eq!(pixel[3], 255, "alpha 应不透明"); + // 颜色在有损压缩误差范围内 + assert!( + i32::from(pixel[0]).abs_diff(200) <= 12 + && i32::from(pixel[1]).abs_diff(100) <= 12 + && i32::from(pixel[2]).abs_diff(50) <= 12, + "webp 颜色应在误差内,实际 {pixel:?}" + ); + } + + /// 四种声明支持的格式都要能被嗅探解码——feature 与实现不得脱节。 + #[test] + fn all_declared_formats_decode() { + let source = image::DynamicImage::ImageRgba8(image::RgbaImage::from_pixel( + 2, + 2, + image::Rgba([30, 60, 90, 255]), + )); + for format in [ + image::ImageFormat::Png, + image::ImageFormat::Jpeg, + image::ImageFormat::Gif, + image::ImageFormat::WebP, + ] { + let mut buffer = Vec::new(); + source + .write_to(&mut std::io::Cursor::new(&mut buffer), format) + .expect("encode"); + let decoded = + decode(&buffer).unwrap_or_else(|error| panic!("{format:?} 应可解码: {error:?}")); + assert_eq!((decoded.width, decoded.height), (2, 2), "{format:?} 尺寸"); + } + } +} diff --git a/crates/nexty-paint/.mimosa/hook-state/session_164476f9d97ffaabe4f6dc9715b6aad5.json b/crates/nexty-paint/.mimosa/hook-state/session_164476f9d97ffaabe4f6dc9715b6aad5.json new file mode 100644 index 0000000..2316ae0 --- /dev/null +++ b/crates/nexty-paint/.mimosa/hook-state/session_164476f9d97ffaabe4f6dc9715b6aad5.json @@ -0,0 +1 @@ +{"touched":[],"bashMutation":false,"reportedFindings":[],"findingEvents":[],"baseline":{"storageId":"mvmhigcz-92724-0fc0df5c2c","createdAt":"2026-10-24T14:18:52.883Z","files":{},"complete":false,"candidateLimit":5000,"discoveredFiles":0,"capturedFiles":0,"truncated":false,"omittedAtLeast":0,"firstOmitted":"","errors":[{"stage":"baseline-capture","target":".","reason":"global task baseline was unavailable; captured only the touched file"},{"stage":"baseline-snapshot","target":"../nexty-chrome/src/resources.rs","reason":"file is outside project"},{"stage":"baseline-snapshot","target":"../nexty-chrome/src/resources.rs","reason":"file is outside project"},{"stage":"baseline-snapshot","target":"../nexty-chrome/src/resources.rs","reason":"file is outside project"},{"stage":"baseline-snapshot","target":"../nexty-chrome/src/resources.rs","reason":"file is outside project"},{"stage":"baseline-snapshot","target":"../nexty-chrome/src/app.rs","reason":"file is outside project"},{"stage":"baseline-snapshot","target":"../nexty-chrome/src/app.rs","reason":"file is outside project"},{"stage":"baseline-snapshot","target":"../nexty-chrome/src/app.rs","reason":"file is outside project"},{"stage":"baseline-snapshot","target":"../nexty-chrome/src/app.rs","reason":"file is outside project"},{"stage":"baseline-snapshot","target":"../nexty-chrome/src/app.rs","reason":"file is outside project"},{"stage":"baseline-snapshot","target":"../nexty-chrome/src/app.rs","reason":"file is outside project"}]},"stateErrors":[],"omittedReportedFindings":0,"omittedFindingEvents":0,"processing":null,"updatedAt":"2026-10-24T14:22:22.845Z"} \ No newline at end of file diff --git a/crates/nexty-paint/.mimosa/hook-status/sess_ca7e797f-14f7-4cd4-a65e-6a69d7418103-35569b193b.json b/crates/nexty-paint/.mimosa/hook-status/sess_ca7e797f-14f7-4cd4-a65e-6a69d7418103-35569b193b.json new file mode 100644 index 0000000..e0ab836 --- /dev/null +++ b/crates/nexty-paint/.mimosa/hook-status/sess_ca7e797f-14f7-4cd4-a65e-6a69d7418103-35569b193b.json @@ -0,0 +1,14 @@ +{ + "schemaVersion": "mimosa-hook-status/v1", + "recordedAt": "2026-10-11T03:49:37.503Z", + "sessionId": "sess_ca7e797f-14f7-4cd4-a65e-6a69d7418103", + "event": "PostToolUse", + "toolName": "Edit", + "file": "D:\\Nexty\\crates\\nexty-chrome\\src\\ui.rs", + "outcome": "inconclusive", + "coverage": "partial", + "findingCount": 0, + "durationMs": 13, + "hostState": "hook_complete", + "reportHint": ".mimosa/reports/" +} diff --git a/crates/nexty-paint/.mimosa/hook-status/session_164476f9d97ffaabe4f6dc9715b6aad5-5e056c09de.json b/crates/nexty-paint/.mimosa/hook-status/session_164476f9d97ffaabe4f6dc9715b6aad5-5e056c09de.json new file mode 100644 index 0000000..a4ff5bd --- /dev/null +++ b/crates/nexty-paint/.mimosa/hook-status/session_164476f9d97ffaabe4f6dc9715b6aad5-5e056c09de.json @@ -0,0 +1,14 @@ +{ + "schemaVersion": "mimosa-hook-status/v1", + "recordedAt": "2026-10-24T14:22:25.344Z", + "sessionId": "session_164476f9d97ffaabe4f6dc9715b6aad5", + "event": "PostToolUse", + "toolName": "Edit", + "file": "D:\\Nexty\\crates\\nexty-chrome\\src\\app.rs", + "outcome": "inconclusive", + "coverage": "partial", + "findingCount": 0, + "durationMs": 24, + "hostState": "hook_complete", + "reportHint": ".mimosa/reports/" +} diff --git a/crates/nexty-paint/Cargo.toml b/crates/nexty-paint/Cargo.toml index 3aaed21..71842e9 100644 --- a/crates/nexty-paint/Cargo.toml +++ b/crates/nexty-paint/Cargo.toml @@ -1,7 +1,7 @@ [package] name = "nexty-paint" description = "Nexty 绘制 facade:自有绘制指令 + 可替换光栅后端(CPU 后端已落地,GPU 后端待 chrome 层接入)" -version = "0.1.7" +version = "0.1.8" edition.workspace = true license.workspace = true repository.workspace = true diff --git a/crates/nexty-paint/src/lib.rs b/crates/nexty-paint/src/lib.rs index a2a8652..2949538 100644 --- a/crates/nexty-paint/src/lib.rs +++ b/crates/nexty-paint/src/lib.rs @@ -5,8 +5,8 @@ //! [`Rasterizer`] trait 即双后端接缝。决策与调研见 //! `docs/decisions/2026-10-01-crate-selection.md`。 //! -//! 指令集:`FillRect` / `StrokeRect` / `DrawText` / `DrawImage`, -//! 后续消费方(layout)需要什么指令再扩展什么。 +//! 指令集:`FillRect` / `StrokeRect` / `FillRoundedRect` / `StrokeRoundedRect` / +//! `FillGradient` / `DrawText` / `DrawImage`,后续消费方需要什么指令再扩展什么。 //! //! 上游:`vello_cpu`(CPU 光栅,sparse strips)+ `image`(图片解码)。 //! **解码归属**:解码器只在 [`decode`] 内出现,产出自有类型 [`Image`], @@ -158,6 +158,15 @@ pub struct TextGlyph { pub font: u32, } +/// 线性渐变的色标(CSS Images §3.4)。 +#[derive(Debug, Clone, Copy, PartialEq)] +pub struct GradientStop { + /// 色标在渐变线上的位置:0.0 = 起点,1.0 = 终点。 + pub offset: f32, + /// 色标颜色(非预乘)。 + pub color: Color, +} + /// 一条绘制指令。 #[derive(Debug, Clone, PartialEq)] pub enum Command { @@ -177,6 +186,54 @@ pub enum Command { /// 线宽,px;非正值不绘制。 width: f32, }, + /// 用纯色填充圆角矩形(CSS Backgrounds §5.5 border-radius 语义)。 + /// + /// 半径顺序为左上、右上、右下、左下(CSS `border-radius` 简写序)。相邻角 + /// 半径之和超过边长时按 CSS §5.5 等比缩减;负值与非有限半径按 0 处理 + /// (渲染为直角);矩形坐标非有限或宽高非正时整条指令跳过。 + FillRoundedRect { + /// 目标矩形。 + rect: Rect, + /// 四角半径 `[左上, 右上, 右下, 左下]`,px。 + radii: [f32; 4], + /// 填充色。 + color: Color, + }, + /// 用纯色描边圆角矩形,圆角边框绘制用。 + /// + /// 与 [`Command::StrokeRect`](中心线描边)不同,本指令的 `rect` 是 + /// border-box 外缘,绘制的带落在内侧 `[0, width]`:中心线路径整体内缩 + /// `width/2`、半径减 `width/2`(负值钳 0),CSS §5.5 缩减在内缩后施加。 + /// 线宽非有限或非正、内缩后矩形退化时整条指令跳过。 + StrokeRoundedRect { + /// 目标矩形(border-box 外缘)。 + rect: Rect, + /// 四角半径 `[左上, 右上, 右下, 左下]`,px(相对 border-box 外缘)。 + radii: [f32; 4], + /// 描边色。 + color: Color, + /// 带宽,px。 + width: f32, + }, + /// 用线性渐变填充(可带圆角的)矩形——单条指令覆盖渐变 × border-radius + /// 组合,无需调用方自算裁剪。 + /// + /// `start` / `end` 是**场景坐标**下的渐变线两端(CSS Images §3.4 的角度 / + /// 关键字 → 端点换算由调用方完成);色标交给后端按 sRGB、预乘 alpha 插值, + /// stop 范围外 Pad 外推取端色——均与 CSS 默认语义一致。offset 非有限的 + /// 色标被丢弃;全部被丢弃、端点或矩形非法时整条指令跳过。 + FillGradient { + /// 目标矩形。 + rect: Rect, + /// 四角半径 `[左上, 右上, 右下, 左下]`,px;全 0 即直角。 + radii: [f32; 4], + /// 渐变线起点(场景坐标)。 + start: [f32; 2], + /// 渐变线终点(场景坐标)。 + end: [f32; 2], + /// 色标列表(offset 0 = 起点,1 = 终点)。 + stops: Vec<GradientStop>, + }, /// 绘制一行字形。 /// /// 字形必须已经过 text 层整形(字形 id 对应 `fonts[glyph.font]` 字体); @@ -281,6 +338,48 @@ impl Scene { color: *color, width: *width, }, + Command::FillRoundedRect { rect, radii, color } => Command::FillRoundedRect { + rect: Rect { + x: rect.x + dx, + y: rect.y + dy, + ..*rect + }, + radii: *radii, + color: *color, + }, + Command::StrokeRoundedRect { + rect, + radii, + color, + width, + } => Command::StrokeRoundedRect { + rect: Rect { + x: rect.x + dx, + y: rect.y + dy, + ..*rect + }, + radii: *radii, + color: *color, + width: *width, + }, + Command::FillGradient { + rect, + radii, + start, + end, + stops, + } => Command::FillGradient { + rect: Rect { + x: rect.x + dx, + y: rect.y + dy, + ..*rect + }, + radii: *radii, + // 渐变端点是场景坐标:必须与矩形同步平移,否则滚动后渐变错位 + start: [start[0] + dx, start[1] + dy], + end: [end[0] + dx, end[1] + dy], + stops: stops.clone(), + }, Command::DrawText { glyphs, baseline, @@ -450,6 +549,82 @@ impl Rasterizer for VelloCpuRasterizer { f64::from(rect.y) + f64::from(rect.height), )); } + Command::FillRoundedRect { rect, radii, color } => { + // 非法输入跳过而非 panic(对齐 draw_image 先例) + if let Some(path) = rounded_rect_path(*rect, *radii) { + context.set_paint(vello_cpu::peniko::Color::from_rgba8( + color.r, color.g, color.b, color.a, + )); + context.fill_path(&path); + } + } + Command::StrokeRoundedRect { + rect, + radii, + color, + width, + } => { + if !width.is_finite() || *width <= 0.0 { + continue; + } + // CSS 边框带在 border-box 内侧:中心线路径整体内缩 width/2, + // 圆角半径减 width/2(负值钳 0) + let half = *width / 2.0; + let inner = Rect { + x: rect.x + half, + y: rect.y + half, + width: rect.width - *width, + height: rect.height - *width, + }; + let radii = sanitize_radii(*radii).map(|r| (r - half).max(0.0)); + if let Some(path) = rounded_rect_path(inner, radii) { + context.set_paint(vello_cpu::peniko::Color::from_rgba8( + color.r, color.g, color.b, color.a, + )); + context.set_stroke(vello_cpu::kurbo::Stroke::new(f64::from(*width))); + context.stroke_path(&path); + } + } + Command::FillGradient { + rect, + radii, + start, + end, + stops, + } => { + let Some(path) = rounded_rect_path(*rect, *radii) else { + continue; + }; + if !start.iter().all(|v| v.is_finite()) || !end.iter().all(|v| v.is_finite()) { + continue; + } + // offset 非有限的色标丢弃;一条不剩则无渐变可画 + let peniko_stops: Vec<vello_cpu::peniko::ColorStop> = stops + .iter() + .filter(|stop| stop.offset.is_finite()) + .map(|stop| { + vello_cpu::peniko::ColorStop::from(( + stop.offset, + gradient_color(stop.color), + )) + }) + .collect(); + if peniko_stops.is_empty() { + continue; + } + let source = vello_cpu::peniko::ColorStops::from(peniko_stops.as_slice()); + let gradient: vello_cpu::peniko::Gradient = + vello_cpu::peniko::Gradient::new_linear( + vello_cpu::kurbo::Point::new(f64::from(start[0]), f64::from(start[1])), + vello_cpu::kurbo::Point::new(f64::from(end[0]), f64::from(end[1])), + ) + .with_stops(&source); + // 渐变端点与路径同处场景坐标系,默认恒等 paint transform + // 直接可用(draw_image 的 transform 只服务于图像像素空间映射, + // 其收尾已 reset,无状态残留)。 + context.set_paint(gradient); + context.fill_path(&path); + } Command::DrawText { glyphs, baseline, @@ -604,6 +779,94 @@ fn draw_image( context.reset_paint_transform(); } +/// 把圆角半径收敛为有限非负值:负值与非有限值一律按 0 处理(渲染为直角)。 +/// +/// 渲染后端对非法数值是 panic 而非返回错误,入口先收敛(对齐 `draw_image` +/// 的「跳过优于 panic」先例——半径语义上 0 总是安全的降级)。 +#[cfg(feature = "cpu")] +fn sanitize_radii(radii: [f32; 4]) -> [f32; 4] { + radii.map(|radius| { + if radius.is_finite() { + radius.max(0.0) + } else { + 0.0 + } + }) +} + +/// CSS Backgrounds §5.5(角重叠):任一边上相邻两角半径之和超过边长时, +/// 全部四角半径按 `f = min(边长 / 半径和)`(只取超限边)等比缩减。 +/// +/// 输入须已过 [`sanitize_radii`](有限非负)且边长为正——本函数是纯几何 +/// 计算,不做输入防御。 +#[cfg(feature = "cpu")] +fn scale_overlapping_radii(width: f32, height: f32, radii: [f32; 4]) -> [f32; 4] { + // 四条边上的(相邻角半径和, 边长) + let edges = [ + (radii[0] + radii[1], width), // 上:左上 + 右上 + (radii[1] + radii[2], height), // 右:右上 + 右下 + (radii[2] + radii[3], width), // 下:右下 + 左下 + (radii[3] + radii[0], height), // 左:左下 + 左上 + ]; + let mut factor = f32::INFINITY; + for (sum, length) in edges { + if sum > length { + factor = factor.min(length / sum); + } + } + if factor < 1.0 { + radii.map(|radius| radius * factor) + } else { + radii + } +} + +/// 矩形是否可绘制:坐标有限且宽高为正。 +#[cfg(feature = "cpu")] +fn rect_is_paintable(rect: &Rect) -> bool { + rect.x.is_finite() + && rect.y.is_finite() + && rect.width.is_finite() + && rect.height.is_finite() + && rect.width > 0.0 + && rect.height > 0.0 +} + +/// 圆角矩形 → 光栅路径;矩形不可绘制时返回 `None`(调用方跳过该指令)。 +/// +/// 半径先经 [`sanitize_radii`] 收敛、再按 [`scale_overlapping_radii`] +/// 缩减(CSS Backgrounds §5.5)。已知偏差:kurbo 的 `RoundedRect::from_rect` +/// 会把每个半径再钳到最短边一半——不对称大半径(如 40×100 盒上单角 40px, +/// CSS 渲染四分之一圆)会被进一步压小,按降级语义接受。 +#[cfg(feature = "cpu")] +fn rounded_rect_path(rect: Rect, radii: [f32; 4]) -> Option<vello_cpu::kurbo::BezPath> { + if !rect_is_paintable(&rect) { + return None; + } + let radii = scale_overlapping_radii(rect.width, rect.height, sanitize_radii(radii)); + let kurbo_rect = vello_cpu::kurbo::Rect::new( + f64::from(rect.x), + f64::from(rect.y), + f64::from(rect.x) + f64::from(rect.width), + f64::from(rect.y) + f64::from(rect.height), + ); + let kurbo_radii = vello_cpu::kurbo::RoundedRectRadii::new( + f64::from(radii[0]), + f64::from(radii[1]), + f64::from(radii[2]), + f64::from(radii[3]), + ); + use vello_cpu::kurbo::Shape as _; + Some(vello_cpu::kurbo::RoundedRect::from_rect(kurbo_rect, kurbo_radii).to_path(0.1)) +} + +/// 非预乘 RGBA8 → peniko 渐变色标颜色(依赖类型不进入 pub 导出)。 +#[cfg(feature = "cpu")] +fn gradient_color(color: Color) -> vello_cpu::peniko::color::DynamicColor { + use vello_cpu::peniko::color::{AlphaColor, Srgb}; + AlphaColor::<Srgb>::from_rgba8(color.r, color.g, color.b, color.a).into() +} + // 测试需要 CPU 光栅后端与图片解码(`image`),二者同属 `cpu` feature。 #[cfg(all(test, feature = "cpu"))] mod tests { @@ -1376,4 +1639,648 @@ mod tests { other => panic!("source changed: {other:?}"), } } + + /// 断言像素接近期望颜色(`tol` 为每通道容差;渐变插值与抖动用较宽容差)。 + fn assert_pixel_within(pixmap: &Pixmap, x: u32, y: u32, expected: [u8; 4], tol: u32) { + let actual = pixmap.pixel(x, y).expect("pixel in bounds"); + for (index, (got, want)) in actual.iter().zip(expected).enumerate() { + assert!( + i32::from(*got).abs_diff(i32::from(want)) <= tol, + "({x}, {y}) 通道{index}: 实际 {got},期望 {want}±{tol},像素 {actual:?}" + ); + } + } + + // ---- 圆角矩形填充(FillRoundedRect) ---- + + #[test] + fn fill_rounded_rect_cuts_all_four_corners() { + // 48×48 盒((8,8)–(56,56))半径 12:角圆心 (20,20)/(44,20)/(44,44)/(20,44) + let scene = Scene { + commands: vec![Command::FillRoundedRect { + rect: rect(8.0, 8.0, 48.0, 48.0), + radii: [12.0; 4], + color: Color::opaque(255, 0, 0), + }], + images: Vec::new(), + }; + let pixmap = VelloCpuRasterizer::new() + .rasterize(&scene, size(64, 64)) + .expect("rasterize"); + + // 中心、直边中点与圆角内侧:完全不透明 + for (x, y) in [ + (32, 32), + (32, 9), + (9, 32), + (55, 32), + (32, 55), + (24, 24), + (40, 24), + (40, 40), + (24, 40), + ] { + assert_pixel_within(&pixmap, x, y, [255, 0, 0, 255], 8); + } + // 四角外侧(圆角截掉的区域):透明 + for (x, y) in [(9, 9), (55, 9), (55, 55), (9, 55)] { + let pixel = pixmap.pixel(x, y).expect("in bounds"); + assert!(pixel[3] <= 8, "({x}, {y}) 应在圆角外,实际 {pixel:?}"); + } + } + + #[test] + fn fill_rounded_rect_invalid_radii_render_sharp() { + // 负值 / NaN / 无穷半径一律按 0 处理 → 直角矩形,四角全覆盖 + let scene = Scene { + commands: vec![Command::FillRoundedRect { + rect: rect(8.0, 8.0, 48.0, 48.0), + radii: [-5.0, f32::NAN, f32::INFINITY, -0.5], + color: Color::opaque(255, 0, 0), + }], + images: Vec::new(), + }; + let pixmap = VelloCpuRasterizer::new() + .rasterize(&scene, size(64, 64)) + .expect("rasterize"); + for (x, y) in [(9, 9), (55, 9), (55, 55), (9, 55), (32, 32)] { + assert_pixel_within(&pixmap, x, y, [255, 0, 0, 255], 8); + } + } + + #[test] + fn fill_rounded_rect_invalid_rect_is_skipped() { + let cases = [ + Rect { + x: f32::NAN, + y: 0.0, + width: 10.0, + height: 10.0, + }, + Rect { + x: 0.0, + y: f32::NAN, + width: 10.0, + height: 10.0, + }, + Rect { + x: 0.0, + y: 0.0, + width: f32::NAN, + height: 10.0, + }, + Rect { + x: 0.0, + y: 0.0, + width: 0.0, + height: 10.0, + }, + Rect { + x: 0.0, + y: 0.0, + width: 10.0, + height: -3.0, + }, + Rect { + x: f32::INFINITY, + y: 0.0, + width: 10.0, + height: 10.0, + }, + ]; + for invalid in cases { + let scene = Scene { + commands: vec![Command::FillRoundedRect { + rect: invalid, + radii: [4.0; 4], + color: Color::opaque(255, 0, 0), + }], + images: Vec::new(), + }; + let pixmap = VelloCpuRasterizer::new() + .rasterize(&scene, size(16, 16)) + .expect("rasterize"); + assert!( + pixmap.data.iter().all(|byte| *byte == 0), + "非法矩形 {invalid:?} 应被跳过" + ); + } + } + + // ---- 圆角矩形描边(StrokeRoundedRect:border-box 内侧带) ---- + + #[test] + fn stroke_rounded_rect_band_geometry_and_hollow_center() { + // border-box (8,8)–(56,56) 半径 12、带宽 4 → 中心线 (10,10)–(54,54) + // 半径 10;直边带 y∈[8,12],角带半径 ∈[8,12](角圆心 (20,20)) + let scene = Scene { + commands: vec![Command::StrokeRoundedRect { + rect: rect(8.0, 8.0, 48.0, 48.0), + radii: [12.0; 4], + color: Color::opaque(0, 0, 255), + width: 4.0, + }], + images: Vec::new(), + }; + let pixmap = VelloCpuRasterizer::new() + .rasterize(&scene, size(64, 64)) + .expect("rasterize"); + + // 直边带与弧带 + assert_pixel_within(&pixmap, 32, 9, [0, 0, 255, 255], 8); + assert_pixel_within(&pixmap, 13, 13, [0, 0, 255, 255], 8); + // 带外(上侧)、空心中心与角圆心 + for (x, y) in [(32, 7), (32, 32), (20, 20)] { + let pixel = pixmap.pixel(x, y).expect("in bounds"); + assert!(pixel[3] == 0, "({x}, {y}) 应空心,实际 {pixel:?}"); + } + // border-box 外无描边 + let pixel = pixmap.pixel(9, 9).expect("in bounds"); + assert!(pixel[3] <= 8, "border-box 外应无描边,实际 {pixel:?}"); + } + + #[test] + fn stroke_rounded_rect_invalid_width_is_noop() { + for width in [0.0f32, -2.0, f32::NAN, f32::INFINITY] { + let scene = Scene { + commands: vec![Command::StrokeRoundedRect { + rect: rect(8.0, 8.0, 48.0, 48.0), + radii: [12.0; 4], + color: Color::opaque(0, 0, 255), + width, + }], + images: Vec::new(), + }; + let pixmap = VelloCpuRasterizer::new() + .rasterize(&scene, size(64, 64)) + .expect("rasterize"); + assert!( + pixmap.data.iter().all(|byte| *byte == 0), + "线宽 {width} 应不绘制" + ); + } + } + + #[test] + fn stroke_rounded_rect_degenerate_inner_rect_is_skipped() { + // 带宽 ≥ 盒边长:中心线内缩后退化,无带可画 → 跳过而非 panic + for width in [48.0f32, 60.0] { + let scene = Scene { + commands: vec![Command::StrokeRoundedRect { + rect: rect(8.0, 8.0, 48.0, 48.0), + radii: [12.0; 4], + color: Color::opaque(0, 0, 255), + width, + }], + images: Vec::new(), + }; + let pixmap = VelloCpuRasterizer::new() + .rasterize(&scene, size(64, 64)) + .expect("rasterize"); + assert!( + pixmap.data.iter().all(|byte| *byte == 0), + "带宽 {width} ≥ 边长应跳过" + ); + } + } + + // ---- 线性渐变填充(FillGradient) ---- + + #[test] + fn fill_gradient_endpoints_and_midpoint() { + // 水平渐变(场景坐标端点 (0,8)→(64,8)),矩形 (0,8,64,16) + let scene = Scene { + commands: vec![Command::FillGradient { + rect: rect(0.0, 8.0, 64.0, 16.0), + radii: [0.0; 4], + start: [0.0, 8.0], + end: [64.0, 8.0], + stops: vec![ + GradientStop { + offset: 0.0, + color: Color::opaque(255, 0, 0), + }, + GradientStop { + offset: 1.0, + color: Color::opaque(0, 0, 255), + }, + ], + }], + images: Vec::new(), + }; + let pixmap = VelloCpuRasterizer::new() + .rasterize(&scene, size(64, 32)) + .expect("rasterize"); + + // t = x/64 的 sRGB 线性插值(光栅抖动容差 ±16) + assert_pixel_within(&pixmap, 2, 16, [247, 0, 8, 255], 16); + assert_pixel_within(&pixmap, 32, 16, [128, 0, 128, 255], 16); + assert_pixel_within(&pixmap, 62, 16, [8, 0, 247, 255], 16); + // 矩形外透明 + assert_eq!(pixmap.pixel(32, 4), Some([0, 0, 0, 0])); + assert_eq!(pixmap.pixel(32, 28), Some([0, 0, 0, 0])); + } + + #[test] + fn fill_gradient_explicit_stop_offsets() { + // 显式 offset 三色标:25% 处纯绿,绿→蓝插值中点在 t=0.625 → x=40 + let scene = Scene { + commands: vec![Command::FillGradient { + rect: rect(0.0, 0.0, 64.0, 8.0), + radii: [0.0; 4], + start: [0.0, 0.0], + end: [64.0, 0.0], + stops: vec![ + GradientStop { + offset: 0.0, + color: Color::opaque(255, 0, 0), + }, + GradientStop { + offset: 0.25, + color: Color::opaque(0, 255, 0), + }, + GradientStop { + offset: 1.0, + color: Color::opaque(0, 0, 255), + }, + ], + }], + images: Vec::new(), + }; + let pixmap = VelloCpuRasterizer::new() + .rasterize(&scene, size(64, 16)) + .expect("rasterize"); + + assert_pixel_within(&pixmap, 16, 4, [0, 255, 0, 255], 8); + assert_pixel_within(&pixmap, 40, 4, [0, 128, 128, 255], 16); + assert_pixel_within(&pixmap, 62, 4, [0, 8, 247, 255], 16); + } + + #[test] + fn fill_gradient_clipped_by_rounded_radii() { + // 渐变 × 圆角:单条指令完成,角外被路径裁剪 + let scene = Scene { + commands: vec![Command::FillGradient { + rect: rect(8.0, 8.0, 48.0, 48.0), + radii: [12.0; 4], + start: [8.0, 0.0], + end: [56.0, 0.0], + stops: vec![ + GradientStop { + offset: 0.0, + color: Color::opaque(255, 0, 0), + }, + GradientStop { + offset: 1.0, + color: Color::opaque(0, 0, 255), + }, + ], + }], + images: Vec::new(), + }; + let pixmap = VelloCpuRasterizer::new() + .rasterize(&scene, size(64, 64)) + .expect("rasterize"); + + // 中心与直边中点都在渐变中部(x=32 → t≈0.5) + assert_pixel_within(&pixmap, 32, 32, [128, 0, 128, 255], 20); + assert_pixel_within(&pixmap, 32, 9, [128, 0, 128, 255], 20); + // 圆角外被裁剪 + for (x, y) in [(9, 9), (55, 9), (55, 55), (9, 55)] { + let pixel = pixmap.pixel(x, y).expect("in bounds"); + assert!( + pixel[3] <= 8, + "({x}, {y}) 渐变应在圆角外被裁剪,实际 {pixel:?}" + ); + } + } + + #[test] + fn fill_gradient_invalid_input_is_skipped() { + let stops = || { + vec![ + GradientStop { + offset: 0.0, + color: Color::opaque(255, 0, 0), + }, + GradientStop { + offset: 1.0, + color: Color::opaque(0, 0, 255), + }, + ] + }; + let cases = [ + // 端点非有限 + ( + rect(0.0, 0.0, 64.0, 8.0), + [f32::NAN, 0.0], + [64.0, 0.0], + stops(), + ), + ( + rect(0.0, 0.0, 64.0, 8.0), + [0.0, 0.0], + [f32::NEG_INFINITY, 0.0], + stops(), + ), + // 色标为空 + ( + rect(0.0, 0.0, 64.0, 8.0), + [0.0, 0.0], + [64.0, 0.0], + Vec::new(), + ), + // 矩形非法 + ( + Rect { + x: f32::NAN, + y: 0.0, + width: 64.0, + height: 8.0, + }, + [0.0, 0.0], + [64.0, 0.0], + stops(), + ), + ]; + for (invalid_rect, start, end, stops) in cases { + let scene = Scene { + commands: vec![Command::FillGradient { + rect: invalid_rect, + radii: [0.0; 4], + start, + end, + stops, + }], + images: Vec::new(), + }; + let pixmap = VelloCpuRasterizer::new() + .rasterize(&scene, size(64, 16)) + .expect("rasterize"); + assert!( + pixmap.data.iter().all(|byte| *byte == 0), + "非法渐变输入应被跳过" + ); + } + } + + #[test] + fn fill_gradient_drops_non_finite_offset_stops() { + // 中间色标 offset 为 NaN:该色标被丢弃,红→蓝照常插值 + let scene = Scene { + commands: vec![Command::FillGradient { + rect: rect(0.0, 8.0, 64.0, 16.0), + radii: [0.0; 4], + start: [0.0, 8.0], + end: [64.0, 8.0], + stops: vec![ + GradientStop { + offset: 0.0, + color: Color::opaque(255, 0, 0), + }, + GradientStop { + offset: f32::NAN, + color: Color::opaque(0, 255, 0), + }, + GradientStop { + offset: 1.0, + color: Color::opaque(0, 0, 255), + }, + ], + }], + images: Vec::new(), + }; + let pixmap = VelloCpuRasterizer::new() + .rasterize(&scene, size(64, 32)) + .expect("rasterize"); + assert_pixel_within(&pixmap, 2, 16, [247, 0, 8, 255], 16); + assert_pixel_within(&pixmap, 32, 16, [128, 0, 128, 255], 16); + assert_pixel_within(&pixmap, 62, 16, [8, 0, 247, 255], 16); + } + + // ---- CSS Backgrounds §5.5 半径缩减(纯函数 + 像素级) ---- + + #[test] + fn sanitize_radii_clamps_negative_and_non_finite_to_zero() { + assert_eq!( + sanitize_radii([3.0, -2.0, f32::NAN, f32::INFINITY]), + [3.0, 0.0, 0.0, 0.0] + ); + } + + #[test] + fn scale_radii_noop_when_adjacent_sums_fit_edges() { + assert_eq!( + scale_overlapping_radii(100.0, 60.0, [40.0, 40.0, 0.0, 0.0]), + [40.0, 40.0, 0.0, 0.0] + ); + } + + #[test] + fn scale_radii_applies_min_factor_across_all_edges() { + // 100×60,radii [80,40,0,0]:上边和 120/100 → f≈0.833;左边和 80/60 → + // f=0.75;取最小 f=0.75 施加到**全部**四角(CSS §5.5) + assert_eq!( + scale_overlapping_radii(100.0, 60.0, [80.0, 40.0, 0.0, 0.0]), + [60.0, 30.0, 0.0, 0.0] + ); + } + + #[test] + fn scale_radii_single_oversized_corner_is_capped_to_edge() { + // 32×32 单角 128:相邻和 128 > 32 → f = 0.25 → 半径缩到边长 + assert_eq!( + scale_overlapping_radii(32.0, 32.0, [128.0, 0.0, 0.0, 0.0]), + [32.0, 0.0, 0.0, 0.0] + ); + } + + #[test] + fn scale_radii_zero_sums_need_no_scaling() { + assert_eq!(scale_overlapping_radii(32.0, 32.0, [0.0; 4]), [0.0; 4]); + } + + #[test] + fn fill_rounded_rect_overlarge_radii_scale_down_per_css() { + // 40×40 盒四角半径 30:相邻和 60 > 40 → f = 2/3 → 全部缩到 20, + // 四角圆心重合于盒中心 (32,32),形状恰为半径 20 的圆 + let scene = Scene { + commands: vec![Command::FillRoundedRect { + rect: rect(12.0, 12.0, 40.0, 40.0), + radii: [30.0; 4], + color: Color::opaque(255, 0, 0), + }], + images: Vec::new(), + }; + let pixmap = VelloCpuRasterizer::new() + .rasterize(&scene, size(64, 64)) + .expect("rasterize"); + + // 缩减后(r=20,圆心 (32,32))在形状内;若未缩减(r=30,圆心 (42,42)), + // (20,20) 距圆心 31.1 在形状外——该点是缩减行为的判别点 + assert_pixel_within(&pixmap, 20, 20, [255, 0, 0, 255], 8); + assert_pixel_within(&pixmap, 32, 32, [255, 0, 0, 255], 8); + assert_pixel_within(&pixmap, 45, 32, [255, 0, 0, 255], 8); + // 圆外:距 (32,32) 24.7 > 20 + let pixel = pixmap.pixel(14, 14).expect("in bounds"); + assert!(pixel[3] <= 8, "缩减后 (14,14) 应在形状外,实际 {pixel:?}"); + } + + // ---- M6 兼容:新指令进 Scene::translated 平移路径 ---- + + #[test] + fn translated_shifts_rounded_and_gradient_commands() { + let red = Color::opaque(255, 0, 0); + let blue = Color::opaque(0, 0, 255); + let stops = vec![ + GradientStop { + offset: 0.0, + color: red, + }, + GradientStop { + offset: 1.0, + color: blue, + }, + ]; + let scene = Scene { + commands: vec![ + Command::FillRoundedRect { + rect: rect(1.0, 2.0, 3.0, 4.0), + radii: [1.0, 2.0, 3.0, 4.0], + color: red, + }, + Command::StrokeRoundedRect { + rect: rect(5.0, 6.0, 7.0, 8.0), + radii: [4.0; 4], + color: blue, + width: 2.0, + }, + Command::FillGradient { + rect: rect(0.0, 0.0, 10.0, 10.0), + radii: [0.0; 4], + start: [10.0, 20.0], + end: [30.0, 40.0], + stops: stops.clone(), + }, + ], + images: Vec::new(), + }; + let moved = scene.translated(3.0, -1.0); + match &moved.commands[0] { + Command::FillRoundedRect { rect, radii, color } => { + assert_eq!( + (rect.x, rect.y, rect.width, rect.height), + (4.0, 1.0, 3.0, 4.0) + ); + assert_eq!(*radii, [1.0, 2.0, 3.0, 4.0]); + assert_eq!(*color, red); + } + other => panic!("first command changed: {other:?}"), + } + match &moved.commands[1] { + Command::StrokeRoundedRect { + rect, + radii, + color, + width, + } => { + assert_eq!( + (rect.x, rect.y, rect.width, rect.height), + (8.0, 5.0, 7.0, 8.0) + ); + assert_eq!(*radii, [4.0; 4]); + assert_eq!((*color, *width), (blue, 2.0)); + } + other => panic!("second command changed: {other:?}"), + } + match &moved.commands[2] { + Command::FillGradient { + rect, + radii, + start, + end, + stops: moved_stops, + } => { + assert_eq!((rect.x, rect.y), (3.0, -1.0)); + assert_eq!(*radii, [0.0; 4]); + // 渐变端点是场景坐标:必须与矩形同步平移(漏移则滚动后错位) + assert_eq!(*start, [13.0, 19.0]); + assert_eq!(*end, [33.0, 39.0]); + assert_eq!(*moved_stops, stops); + } + other => panic!("third command changed: {other:?}"), + } + // 源场景不受影响 + match &scene.commands[2] { + Command::FillGradient { start, end, .. } => { + assert_eq!((*start, *end), ([10.0, 20.0], [30.0, 40.0])); + } + other => panic!("source changed: {other:?}"), + } + } + + #[test] + fn translated_new_commands_render_identically_at_offset() { + // 整数平移后逐像素一致(亚像素相位不变),渐变端点随矩形同步平移 + let red = Color::opaque(255, 0, 0); + let blue = Color::opaque(0, 0, 255); + let scene = Scene { + commands: vec![ + Command::FillRoundedRect { + rect: rect(2.0, 2.0, 20.0, 20.0), + radii: [6.0; 4], + color: red, + }, + Command::StrokeRoundedRect { + rect: rect(2.0, 26.0, 20.0, 20.0), + radii: [4.0; 4], + color: blue, + width: 3.0, + }, + Command::FillGradient { + rect: rect(2.0, 50.0, 20.0, 12.0), + radii: [3.0, 0.0, 3.0, 0.0], + start: [2.0, 50.0], + end: [22.0, 62.0], + stops: vec![ + GradientStop { + offset: 0.0, + color: red, + }, + GradientStop { + offset: 1.0, + color: blue, + }, + ], + }, + ], + images: Vec::new(), + }; + let direct = VelloCpuRasterizer::new() + .rasterize(&scene, size(32, 72)) + .expect("rasterize"); + let moved = scene.translated(8.0, 4.0); + let shifted = VelloCpuRasterizer::new() + .rasterize(&moved, size(32, 72)) + .expect("rasterize"); + + // 非空验证:三条指令各自应有像素落下(防止双方全透明导致空断言) + assert_eq!(direct.pixel(12, 12), Some([255, 0, 0, 255])); + assert_eq!(direct.pixel(12, 27), Some([0, 0, 255, 255])); + assert_pixel_within(&direct, 12, 56, [128, 0, 128, 255], 16); + + // 平移场景在 (+8, +4) 处与原场景逐像素一致(渐变抖动允许 ±2) + for y in 0..68u32 { + for x in 0..24u32 { + let want = direct.pixel(x, y).expect("in bounds"); + let got = shifted.pixel(x + 8, y + 4).expect("in bounds"); + for (index, (g, w)) in got.iter().zip(want).enumerate() { + assert!( + i32::from(*g).abs_diff(i32::from(w)) <= 2, + "({x}, {y}) 通道{index}: 平移后 {g},原始 {w}" + ); + } + } + } + } } From 26c4c46ba64254661a05444971218746664adc9c Mon Sep 17 00:00:00 2001 From: zwork <zwork@local> Date: Sat, 31 Oct 2026 18:30:13 +0800 Subject: [PATCH 11/14] [chrome] K1 event wiring + K2 drawing emit + K3 navigation orchestration + K4 font orchestration (0.1.29) --- ...sion_164476f9d97ffaabe4f6dc9715b6aad5.json | 1 + ...4aff5f0674d7fae884f2416f905b9c092af.source | 860 ++++++++++++++ ...52fbcef87b5e360662bb527c96d9a615542.source | 59 + ...f9d97ffaabe4f6dc9715b6aad5-5e056c09de.json | 14 + crates/nexty-chrome/Cargo.toml | 2 +- crates/nexty-chrome/src/app.rs | 397 ++++--- crates/nexty-chrome/src/app/events.rs | 469 ++++++++ crates/nexty-chrome/src/lib.rs | 8 +- crates/nexty-chrome/src/pipeline.rs | 1002 ++++++++++++++++- crates/nexty-chrome/src/resources.rs | 779 +++++++++++-- crates/nexty-chrome/tests/chrome.rs | 530 ++++++++- crates/nexty-chrome/tests/selection.rs | 4 +- docs/decisions/2026-10-31-addressbar-url.md | 40 + 13 files changed, 3902 insertions(+), 263 deletions(-) create mode 100644 crates/nexty-chrome/.mimosa/hook-state/session_164476f9d97ffaabe4f6dc9715b6aad5.json create mode 100644 crates/nexty-chrome/.mimosa/hook-state/session_164476f9d97ffaabe4f6dc9715b6aad5.mvmhprgt-42404-bfa3e379d5.baseline/1b82306d7da63053340a3ce98304e4aff5f0674d7fae884f2416f905b9c092af.source create mode 100644 crates/nexty-chrome/.mimosa/hook-state/session_164476f9d97ffaabe4f6dc9715b6aad5.mvmhprgt-42404-bfa3e379d5.baseline/2e9d962a08321605940b5a657135052fbcef87b5e360662bb527c96d9a615542.source create mode 100644 crates/nexty-chrome/.mimosa/hook-status/session_164476f9d97ffaabe4f6dc9715b6aad5-5e056c09de.json create mode 100644 crates/nexty-chrome/src/app/events.rs create mode 100644 docs/decisions/2026-10-31-addressbar-url.md diff --git a/crates/nexty-chrome/.mimosa/hook-state/session_164476f9d97ffaabe4f6dc9715b6aad5.json b/crates/nexty-chrome/.mimosa/hook-state/session_164476f9d97ffaabe4f6dc9715b6aad5.json new file mode 100644 index 0000000..a612c9b --- /dev/null +++ b/crates/nexty-chrome/.mimosa/hook-state/session_164476f9d97ffaabe4f6dc9715b6aad5.json @@ -0,0 +1 @@ +{"touched":["D:\\Nexty\\crates\\nexty-chrome\\Cargo.toml","D:\\Nexty\\crates\\nexty-chrome\\tests\\chrome.rs","D:\\Nexty\\crates\\nexty-chrome\\build.rs"],"bashMutation":true,"reportedFindings":[],"findingEvents":[],"baseline":{"storageId":"mvmhprgt-42404-bfa3e379d5","createdAt":"2026-10-24T14:24:33.869Z","files":{"Cargo.toml":{"existed":true,"snapshot":"2e9d962a08321605940b5a657135052fbcef87b5e360662bb527c96d9a615542.source"},"tests/chrome.rs":{"existed":true,"snapshot":"1b82306d7da63053340a3ce98304e4aff5f0674d7fae884f2416f905b9c092af.source"},"build.rs":{"existed":false}},"complete":false,"candidateLimit":5000,"discoveredFiles":0,"capturedFiles":3,"truncated":false,"omittedAtLeast":0,"firstOmitted":"","errors":[{"stage":"baseline-capture","target":".","reason":"global task baseline was unavailable; captured only the touched file"},{"stage":"baseline-snapshot","target":"../nexty-paint/Cargo.toml","reason":"file is outside project"}]},"stateErrors":[],"omittedReportedFindings":0,"omittedFindingEvents":0,"processing":null,"updatedAt":"2026-10-24T15:03:17.637Z"} \ No newline at end of file diff --git a/crates/nexty-chrome/.mimosa/hook-state/session_164476f9d97ffaabe4f6dc9715b6aad5.mvmhprgt-42404-bfa3e379d5.baseline/1b82306d7da63053340a3ce98304e4aff5f0674d7fae884f2416f905b9c092af.source b/crates/nexty-chrome/.mimosa/hook-state/session_164476f9d97ffaabe4f6dc9715b6aad5.mvmhprgt-42404-bfa3e379d5.baseline/1b82306d7da63053340a3ce98304e4aff5f0674d7fae884f2416f905b9c092af.source new file mode 100644 index 0000000..9161676 --- /dev/null +++ b/crates/nexty-chrome/.mimosa/hook-state/session_164476f9d97ffaabe4f6dc9715b6aad5.mvmhprgt-42404-bfa3e379d5.baseline/1b82306d7da63053340a3ce98304e4aff5f0674d7fae884f2416f905b9c092af.source @@ -0,0 +1,860 @@ +//! chrome 层集成测试:端到端管线与渲染隔离线程。 +//! +//! 窗口/GPU 胶水(app 模块)无法无头测试,不在此覆盖。 + +use std::sync::Arc; +use std::sync::atomic::{AtomicUsize, Ordering}; + +use nexty_paint::{Color, Command, Pixmap, RasterError, Rasterizer, Scene, Size}; +use nexty_text::ParleyTextShaper; + +use nexty_chrome::pipeline::{self, Viewport}; +use nexty_chrome::render::{RenderError, RenderThread}; + +fn approx(a: f32, b: f32) -> bool { + (a - b).abs() < 0.01 +} + +#[test] +fn end_to_end_page_renders_background_and_border() { + let page = pipeline::load_page( + "<body><div id=\"box\">hello</div></body>", + "body { background-color: #ffffff } #box { background-color: rgb(0 128 255); border: 3px solid red; height: 50px }", + ); + let shaper = ParleyTextShaper::new(); + let root = pipeline::layout_page(&page, &shaper, 400.0).expect("root"); + let scene = pipeline::build_scene(&page, &root); + + // 显示列表应包含:body 白底、box 蓝底、四条红边、一条文本 + let fills: Vec<_> = scene + .commands + .iter() + .filter_map(|command| match command { + Command::FillRect { rect, color } => Some((*rect, *color)), + _ => None, + }) + .collect(); + let texts: Vec<_> = scene + .commands + .iter() + .filter(|command| matches!(command, Command::DrawText { .. })) + .collect(); + + let has_white = fills.iter().any(|(rect, color)| { + color.r == 255 && color.g == 255 && color.b == 255 && rect.width > 300.0 + }); + let has_blue = fills + .iter() + .any(|(_, color)| *color == Color::opaque(0, 128, 255)); + let red_strips = fills + .iter() + .filter(|(_, color)| *color == Color::opaque(255, 0, 0)) + .count(); + assert!(has_white, "body 白底"); + assert!(has_blue, "box 蓝底"); + assert_eq!(red_strips, 4, "四条红边"); + assert_eq!(texts.len(), 1, "hello 一个文本 run"); + + // 光栅化后像素验证 + let rasterizer = nexty_paint::VelloCpuRasterizer::new(); + let pixmap = rasterizer + .rasterize( + &scene, + Viewport { + width: 400, + height: 300, + }, + ) + .expect("rasterize"); + // box 的位置由布局决定:找蓝底填充带的 y,在其中心取像素 + let (blue_rect, _) = fills + .iter() + .find(|(_, color)| *color == Color::opaque(0, 128, 255)) + .expect("blue rect"); + let sample_x = (blue_rect.x + blue_rect.width / 2.0) as u32; + let sample_y = (blue_rect.y + blue_rect.height / 2.0) as u32; + assert_eq!( + pixmap.pixel(sample_x, sample_y), + Some([0, 128, 255, 255]), + "box 中心是蓝底(边框内)" + ); + // 边框线上是红色 + let border_y = (blue_rect.y + 1.0) as u32; + assert_eq!(pixmap.pixel(sample_x, border_y), Some([255, 0, 0, 255])); + // 文字有非透明像素 + let text_pixels = (0..400u32) + .flat_map(|x| (0..300u32).map(move |y| (x, y))) + .filter(|(x, y)| { + pixmap.pixel(*x, *y).is_some_and(|p| { + p[3] > 0 + && !(p == [255, 255, 255, 255] + || p == [0, 128, 255, 255] + || p == [255, 0, 0, 255]) + }) + }) + .count(); + assert!(text_pixels > 0, "文本产生可见像素"); +} + +#[test] +fn anonymous_fragments_draw_no_background_or_border() { + let page = pipeline::load_page( + "<body>text <b>bold</b><div style=\"height: 4px\"></div>more text</body>", + "", + ); + let shaper = ParleyTextShaper::new(); + let root = pipeline::layout_page(&page, &shaper, 400.0).expect("root"); + let scene = pipeline::build_scene(&page, &root); + + // 除 body 背景(若 UA 给了)外,不允许出现匿名背景/边框; + // 匿名片段的指令只可能是 DrawText + let text_count = scene + .commands + .iter() + .filter(|command| matches!(command, Command::DrawText { .. })) + .count(); + assert!(text_count >= 2, "两段文本各自成行"); +} + +/// T0 回归:折行段落的每行 baseline 必须按行高递增(此前所有行画在同一 +/// baseline 上,第二行起与首行重叠)。 +#[test] +fn multiline_baselines_advance_by_line_height() { + let text = "aaa bbb ccc ddd eee fff ggg hhh iii jjj kkk lll mmm nnn ooo ppp qqq rrr sss ttt"; + let page = pipeline::load_page(&format!("<p>{text}</p>"), ""); + let shaper = ParleyTextShaper::new(); + let root = pipeline::layout_page(&page, &shaper, 300.0).expect("root"); + let scene = pipeline::build_scene(&page, &root); + + let mut baselines: Vec<f32> = scene + .commands + .iter() + .filter_map(|command| match command { + Command::DrawText { baseline, .. } => Some(*baseline), + _ => None, + }) + .collect(); + baselines.sort_by(|a, b| a.partial_cmp(b).expect("finite")); + assert!(baselines.len() >= 2, "该文本在 300px 视口下应折成多行"); + for pair in baselines.windows(2) { + assert!( + pair[1] > pair[0], + "相邻两行 baseline 相同({pair:?})→ 行重叠" + ); + } +} + +/// T8:行内原子盒(inline-block)的内容进入显示列表——背景与内部文本。 +#[test] +fn inline_block_content_is_emitted_into_scene() { + let page = pipeline::load_page( + "<body>out <span style=\"display: inline-block; width: 80px; height: 30px; background-color: rgb(0 200 0)\">in</span></body>", + "", + ); + let shaper = ParleyTextShaper::new(); + let root = pipeline::layout_page(&page, &shaper, 400.0).expect("root"); + let scene = pipeline::build_scene(&page, &root); + + let green: Vec<_> = scene + .commands + .iter() + .filter_map(|command| match command { + Command::FillRect { rect, color } => Some((*rect, *color)), + _ => None, + }) + .filter(|(_, color)| *color == Color::opaque(0, 200, 0)) + .collect(); + assert_eq!(green.len(), 1, "inline-block 背景下发"); + let (rect, _) = green[0]; + assert!(approx(rect.width, 80.0)); + assert!(approx(rect.height, 30.0)); + // 原子盒内部文本也在场景里:外层 out 与盒内 in 各一段 run + let text_count = scene + .commands + .iter() + .filter(|command| matches!(command, Command::DrawText { .. })) + .count(); + assert_eq!(text_count, 2, "out 与 in 分别下发"); +} + +/// T4:块级链接命中 → href 原文 → 相对地址归一;空白区不产生链接。 +#[test] +fn hit_test_finds_block_link_and_resolves_href() { + let page = pipeline::load_page( + "<body><a href=\"/target\" style=\"display: block; height: 20px\">block link</a></body>", + "body { margin: 0; height: 50px }", + ); + let shaper = ParleyTextShaper::new(); + let root = pipeline::layout_page(&page, &shaper, 200.0).expect("root"); + + let node = pipeline::hit_test(&root, 10.0, 5.0).expect("命中链接"); + assert_eq!( + pipeline::link_target(&page, node).as_deref(), + Some("/target") + ); + let resolved = nexty_network::resolve("https://origin.test/dir/page", "/target"); + assert_eq!(resolved.as_deref(), Ok("https://origin.test/target")); + + // a(高 20)之外、body(高 50)之内:命中 body,无链接 + let node = pipeline::hit_test(&root, 10.0, 30.0).expect("命中 body"); + assert!(pipeline::link_target(&page, node).is_none()); +} + +/// T4:行内链接文本 run 命中(坐标取自 run 字形范围)。 +#[test] +fn hit_test_finds_inline_link_text_run() { + let page = pipeline::load_page( + "<body><p style=\"margin: 0\"><a href=\"https://a.test/x\">linktext</a></p></body>", + "body { margin: 0 }", + ); + let shaper = ParleyTextShaper::new(); + let root = pipeline::layout_page(&page, &shaper, 200.0).expect("root"); + let body = &root.children[0]; + let p = &body.children[0]; + let run = &p.lines[0].runs[0]; + let first = run.glyphs[0]; + let last = run.glyphs.last().expect("glyphs"); + let mid = (first.x + last.x + last.advance) / 2.0; + + let node = pipeline::hit_test(p, mid, 2.0).expect("命中行内链接"); + assert_eq!( + pipeline::link_target(&page, node).as_deref(), + Some("https://a.test/x") + ); + // p 盒内、run 之外(右侧空白):命中 p 本身,无链接 + let node = pipeline::hit_test(p, p.border_box.width - 1.0, 2.0).expect("命中 p"); + assert!(pipeline::link_target(&page, node).is_none()); +} + +/// T4:链接内的图片命中后沿祖先链找到 `<a href>`。 +#[test] +fn hit_test_finds_image_inside_anchor() { + let page = pipeline::load_page( + "<body><a href=\"logo\" style=\"display: block\"><img width=40 height=30 src=a.png></a></body>", + "body { margin: 0 }", + ); + let shaper = ParleyTextShaper::new(); + let root = pipeline::layout_page(&page, &shaper, 200.0).expect("root"); + let body = &root.children[0]; + let anchor = &body.children[0]; + + let node = pipeline::hit_test(anchor, 10.0, 10.0).expect("命中图片"); + assert_eq!(pipeline::link_target(&page, node).as_deref(), Some("logo")); + // 图片矩形之外(a 盒内、图片下方)→ a 自身,仍有链接 + let node = pipeline::hit_test(anchor, 10.0, anchor.border_box.height - 1.0).expect("命中 a"); + assert_eq!(pipeline::link_target(&page, node).as_deref(), Some("logo")); +} + +/// T4:`<a>` 缺 href 不产生链接目标;盒外命中测试返回 None。 +#[test] +fn link_target_requires_href_and_miss_returns_none() { + let page = pipeline::load_page( + "<body><a style=\"display: block; height: 20px\">no href</a></body>", + "body { margin: 0 }", + ); + let shaper = ParleyTextShaper::new(); + let root = pipeline::layout_page(&page, &shaper, 200.0).expect("root"); + let node = pipeline::hit_test(&root, 5.0, 5.0).expect("命中 a"); + assert!(pipeline::link_target(&page, node).is_none()); + // body 之外(视口下方远处) + assert!(pipeline::hit_test(&root, 5.0, 300.0).is_none()); +} + +/// T4:悬停光标语义——链接(文本/块级/图片)→ 手型,正文文本 → I 形,空白 → 默认。 +#[test] +fn hover_kind_follows_links_text_and_blank() { + let page = pipeline::load_page( + "<body style=\"margin: 0\">\ + <p style=\"margin: 0\"><a href=\"/x\">linktext</a></p>\ + <p style=\"margin: 0\">plaintext</p>\ + </body>", + "", + ); + let shaper = ParleyTextShaper::new(); + let root = pipeline::layout_page(&page, &shaper, 300.0).expect("root"); + let body = &root.children[0]; + let link_p = &body.children[0]; + let plain_p = &body.children[1]; + + // 链接文本 run 中点 → 手型 + let run = &link_p.lines[0].runs[0]; + let first = run.glyphs[0]; + let last = run.glyphs.last().expect("glyphs"); + let mid = (first.x + last.x + last.advance) / 2.0; + let y = link_p.border_box.y + 2.0; + assert_eq!( + pipeline::hover_kind(&page, body, mid, y), + pipeline::HoverKind::Pointer, + "链接文本 → 手型" + ); + + // 正文文本 run 中点 → I 形 + let run = &plain_p.lines[0].runs[0]; + let first = run.glyphs[0]; + let last = run.glyphs.last().expect("glyphs"); + let mid = (first.x + last.x + last.advance) / 2.0; + let y = plain_p.border_box.y + 2.0; + assert_eq!( + pipeline::hover_kind(&page, body, mid, y), + pipeline::HoverKind::Text, + "正文文本 → I 形" + ); + + // 盒内空白(文本右侧、行纵向之外)→ 默认;盒外 → 默认 + assert_eq!( + pipeline::hover_kind(&page, body, plain_p.border_box.width - 1.0, y), + pipeline::HoverKind::Default, + "盒内非文本区 → 默认" + ); + assert_eq!( + pipeline::hover_kind(&page, body, 10.0, -50.0), + pipeline::HoverKind::Default, + "盒外 → 默认" + ); +} + +/// T4:块级链接整个盒 → 手型;链接内图片 → 手型,且命中类型区分为图片。 +#[test] +fn hover_kind_covers_block_link_and_image() { + let page = pipeline::load_page( + "<body><a href=\"t\" style=\"display: block; height: 20px\">block</a>\ + <a href=\"logo\" style=\"display: block\"><img width=40 height=30 src=a.png></a></body>", + "body { margin: 0 }", + ); + let shaper = ParleyTextShaper::new(); + let root = pipeline::layout_page(&page, &shaper, 200.0).expect("root"); + let body = &root.children[0]; + let block_link = &body.children[0]; + let image_link = &body.children[1]; + + // 块级链接盒内(文本之下)仍是链接 + assert_eq!( + pipeline::hover_kind( + &page, + body, + 10.0, + block_link.border_box.y + block_link.border_box.height - 2.0 + ), + pipeline::HoverKind::Pointer, + "块级链接 → 手型" + ); + + // 链接内图片:命中类型为 Image,光标仍是手型 + let hit = pipeline::hit_test_ex(body, 10.0, image_link.border_box.y + 10.0).expect("命中图片"); + assert_eq!(hit.kind, pipeline::HitKind::Image); + assert_eq!( + pipeline::hover_kind(&page, body, 10.0, image_link.border_box.y + 10.0), + pipeline::HoverKind::Pointer + ); +} + +/// T4:`hit_test` 仍是 `hit_test_ex` 的薄封装(节点一致)。 +#[test] +fn hit_test_wrapper_matches_hit_test_ex_node() { + let page = pipeline::load_page( + "<body><p style=\"margin: 0\">hello</p></body>", + "body { margin: 0 }", + ); + let shaper = ParleyTextShaper::new(); + let root = pipeline::layout_page(&page, &shaper, 200.0).expect("root"); + let node = pipeline::hit_test(&root, 5.0, 5.0).expect("命中"); + let hit = pipeline::hit_test_ex(&root, 5.0, 5.0).expect("命中"); + assert_eq!(Some(node), Some(hit.node)); + assert_eq!(hit.kind, pipeline::HitKind::TextRun, "命中的是文本 run"); +} + +/// T5:`<title>` 文本提取;空白/缺失/非 HTML 命名空间返回 None。 +#[test] +fn document_title_extraction() { + let page = pipeline::load_page( + "<html><head><title>文档标题", + "", + ); + assert_eq!( + pipeline::document_title(&page.document).as_deref(), + Some("文档标题") + ); + + // 空白 title 视为缺失 + let page = pipeline::load_page(" ", ""); + assert!(pipeline::document_title(&page.document).is_none()); + + // 无 title + let page = pipeline::load_page("", ""); + assert!(pipeline::document_title(&page.document).is_none()); +} + +#[test] +fn render_thread_round_trips() { + let thread = RenderThread::spawn(Arc::new(nexty_paint::VelloCpuRasterizer::new())); + let scene = Scene { + commands: vec![Command::FillRect { + rect: nexty_paint::Rect { + x: 0.0, + y: 0.0, + width: 4.0, + height: 4.0, + }, + color: Color::opaque(255, 0, 0), + }], + images: Vec::new(), + }; + let pixmap = thread + .render( + &scene, + Size { + width: 8, + height: 8, + }, + ) + .expect("render"); + assert_eq!(pixmap.pixel(0, 0), Some([255, 0, 0, 255])); + assert_eq!(pixmap.pixel(7, 7), Some([0, 0, 0, 0])); +} + +/// 首次调用 panic 的 Rasterizer(验证兜底后线程仍可服务)。 +struct PanicsOnce { + calls: AtomicUsize, +} + +impl Rasterizer for PanicsOnce { + fn rasterize(&self, _scene: &Scene, _size: Size) -> Result { + if self.calls.fetch_add(1, Ordering::SeqCst) == 0 { + panic!("injected rasterizer failure"); + } + Ok(Pixmap { + size: Size { + width: 1, + height: 1, + }, + data: vec![1, 2, 3, 4], + }) + } +} + +#[test] +fn render_thread_survives_panic_and_keeps_serving() { + let thread = RenderThread::spawn(Arc::new(PanicsOnce { + calls: AtomicUsize::new(0), + })); + let scene = Scene::default(); + let size = Size { + width: 4, + height: 4, + }; + + let error = thread.render(&scene, size).expect_err("first call panics"); + match error { + RenderError::Panicked(message) => assert!(message.contains("injected")), + RenderError::Raster(_) => panic!("expected panic error"), + } + + // 兜底后线程存活:第二次调用正常返回 + let pixmap = thread.render(&scene, size).expect("second call succeeds"); + assert_eq!(pixmap.data, vec![1, 2, 3, 4]); +} + +#[test] +fn render_thread_reports_raster_errors() { + struct AlwaysEmpty; + impl Rasterizer for AlwaysEmpty { + fn rasterize(&self, _scene: &Scene, _size: Size) -> Result { + Err(RasterError::EmptySize) + } + } + let thread = RenderThread::spawn(Arc::new(AlwaysEmpty)); + let error = thread + .render( + &Scene::default(), + Size { + width: 0, + height: 0, + }, + ) + .expect_err("raster error"); + assert_eq!(error, RenderError::Raster(RasterError::EmptySize)); +} + +#[test] +fn viewport_alias_and_helpers() { + // Viewport 是 paint::Size 的别名,尺寸直通 + let viewport = Viewport { + width: 10, + height: 20, + }; + assert!(approx(viewport.width as f32, 10.0)); +} + +// ---- T5:子资源抓取与页面重组(无头端到端) ---- + +use nexty_chrome::resources::{self, Subresources}; +use nexty_dom::Document; +use nexty_html::ParseOptions; +use nexty_network::{NetworkError, NetworkFetcher, Request, Response}; +use std::collections::BTreeMap; +use std::sync::Mutex; + +/// 内存 mock fetcher:URL → body / 状态码;未登记的 URL 返回 404。 +struct MockFetcher { + routes: Mutex, u16>>>, +} + +impl MockFetcher { + fn new() -> Self { + Self { + routes: Mutex::new(BTreeMap::new()), + } + } + + fn serve(&self, url: &str, body: &[u8]) { + self.routes + .lock() + .unwrap() + .insert(url.to_owned(), Ok(body.to_vec())); + } + + fn fail(&self, url: &str, status: u16) { + self.routes + .lock() + .unwrap() + .insert(url.to_owned(), Err(status)); + } +} + +impl NetworkFetcher for MockFetcher { + fn fetch(&self, request: &Request) -> Result { + let routes = self.routes.lock().unwrap(); + match routes.get(&request.url) { + Some(Ok(body)) => Ok(Response { + status: 200, + headers: Vec::new(), + body: body.clone(), + }), + Some(Err(status)) => Ok(Response { + status: *status, + headers: Vec::new(), + body: Vec::new(), + }), + None => Ok(Response { + status: 404, + headers: Vec::new(), + body: Vec::new(), + }), + } + } +} + +/// 1×1 蓝色 PNG。 +fn tiny_png() -> Vec { + let mut buffer = Vec::new(); + image::DynamicImage::ImageRgba8(image::RgbaImage::from_pixel( + 1, + 1, + image::Rgba([0, 0, 255, 255]), + )) + .write_to( + &mut std::io::Cursor::new(&mut buffer), + image::ImageFormat::Png, + ) + .expect("encode png"); + buffer +} + +/// 加载入口(与 app.rs 后台线程相同的编排序列)。 +fn load_page_with_resources( + fetcher: &MockFetcher, + base_url: &str, + html: &str, +) -> (Document, Subresources) { + let document = nexty_html::parse_document(html, ParseOptions::default()); + let resources = resources::fetch_subresources(fetcher, base_url, &document); + (document, resources) +} + +/// 含外链 CSS + 图片的页面:级联按源顺序,图片按 DrawImage 下发。 +#[test] +fn subresources_load_and_scene_carries_external_css_and_image() { + let fetcher = MockFetcher::new(); + // 外链表覆盖 inline 表的同名属性:后者应胜出 + fetcher.serve( + "https://page.test/ext.css", + b"p { color: blue; border: 2px solid rgb(0 128 0) }", + ); + fetcher.serve("https://page.test/logo.png", &tiny_png()); + let html = "\ + \ +

hi

"; + + let (_, sub) = load_page_with_resources(&fetcher, "https://page.test/index.html", html); + assert_eq!(sub.stylesheets.len(), 2, "inline + 外链按源顺序"); + assert_eq!(sub.images.len(), 1, "图片已解码"); + + // 组装页面 → 布局 → Scene + let document = nexty_html::parse_document(html, ParseOptions::default()); + let page = pipeline::build_page(document, sub.stylesheets, sub.images); + let shaper = ParleyTextShaper::new(); + let root = pipeline::layout_page(&page, &shaper, 400.0).expect("root"); + let scene = pipeline::build_scene(&page, &root); + + // Scene 指令序列:图片指令 + 图片池 + 文本 + let images_drawn: Vec<_> = scene + .commands + .iter() + .filter_map(|command| match command { + Command::DrawImage { rect, image } => Some((*rect, *image)), + _ => None, + }) + .collect(); + assert_eq!(images_drawn.len(), 1, "一张图片一条 DrawImage"); + let (rect, index) = images_drawn[0]; + assert_eq!(scene.images.len(), 1, "图片池一份像素"); + assert_eq!(index, 0); + assert!(approx(rect.width, 10.0) && approx(rect.height, 10.0)); + // 图片落点在地址栏下方内容区(y > 0)且在文本之后 + assert!(rect.y > 0.0); + assert!( + scene + .commands + .iter() + .any(|command| matches!(command, Command::DrawText { .. })), + "文本指令仍在" + ); + + // 级联顺序:外链表的 blue 压过 inline 的 red —— 光栅化像素验证 + let rasterizer = nexty_paint::VelloCpuRasterizer::new(); + let pixmap = rasterizer + .rasterize( + &scene, + Viewport { + width: 400, + height: 300, + }, + ) + .expect("rasterize"); + let pixel = pixmap + .pixel(rect.x as u32 + 5, rect.y as u32 + 5) + .expect("像素在画布内"); + // vello_cpu 预乘/反预乘往返有 ±1 量化误差 + assert!( + pixel[0] <= 1 && pixel[1] <= 1 && pixel[2] >= 254 && pixel[3] == 255, + "1×1 PNG 的蓝色落在目标矩形内,实际 {pixel:?}" + ); +} + +/// 单个子资源失败不影响其余渲染(降级而非白屏)。 +#[test] +fn failing_subresources_degrade_without_blocking_render() { + let fetcher = MockFetcher::new(); + fetcher.fail("https://page.test/broken.css", 500); + fetcher.fail("https://page.test/lost.png", 404); + fetcher.serve("https://page.test/junk.png", b"not an image"); + let html = "\ +

still here

"; + + let (_, sub) = load_page_with_resources(&fetcher, "https://page.test/index.html", html); + assert!(sub.stylesheets.is_empty(), "失败的外链表不参与级联"); + assert!(sub.images.is_empty(), "失败图片无像素"); + + let document = nexty_html::parse_document(html, ParseOptions::default()); + let page = pipeline::build_page(document, sub.stylesheets, sub.images); + let shaper = ParleyTextShaper::new(); + let root = pipeline::layout_page(&page, &shaper, 400.0).expect("root"); + let scene = pipeline::build_scene(&page, &root); + + // 文本照常渲染;无图片指令(失败图片不产生 DrawImage) + assert!( + scene + .commands + .iter() + .any(|command| matches!(command, Command::DrawText { .. })), + "文本内容不受子资源失败影响" + ); + assert!( + !scene + .commands + .iter() + .any(|command| matches!(command, Command::DrawImage { .. })), + "无像素的图片不下发指令" + ); +} + +/// 抓取不到自然尺寸的图片:布局回退默认对象尺寸,失败图片无指令。 +#[test] +fn image_natural_size_flows_from_decoding_into_layout() { + // 3×2 蓝色 PNG:无 width/height 属性时按自然尺寸 + let mut png = Vec::new(); + image::DynamicImage::ImageRgba8(image::RgbaImage::from_pixel( + 3, + 2, + image::Rgba([10, 20, 30, 255]), + )) + .write_to(&mut std::io::Cursor::new(&mut png), image::ImageFormat::Png) + .expect("encode"); + let fetcher = MockFetcher::new(); + fetcher.serve("https://page.test/n.png", &png); + let html = ""; + + let (_, sub) = load_page_with_resources(&fetcher, "https://page.test/index.html", html); + let document = nexty_html::parse_document(html, ParseOptions::default()); + let page = pipeline::build_page(document, sub.stylesheets, sub.images); + let shaper = ParleyTextShaper::new(); + let root = pipeline::layout_page(&page, &shaper, 400.0).expect("root"); + let scene = pipeline::build_scene(&page, &root); + + let drawn: Vec<_> = scene + .commands + .iter() + .filter_map(|command| match command { + Command::DrawImage { rect, .. } => Some(*rect), + _ => None, + }) + .collect(); + assert_eq!(drawn.len(), 1); + assert!( + approx(drawn[0].width, 3.0) && approx(drawn[0].height, 2.0), + "自然尺寸 3×2 从解码流入布局,实际 {:?}", + (drawn[0].width, drawn[0].height) + ); +} + +// ---- 不可信输入边界加固:全链回归(本轮验收旗舰用例) ---- + +use nexty_dom::MAX_TREE_DEPTH; +use nexty_dom::NodeKind; +use nexty_layout::Fragment; + +/// CRC-32(IEEE,PNG chunk 校验用)。 +fn crc32(data: &[u8]) -> u32 { + let mut crc: u32 = 0xFFFF_FFFF; + for &byte in data { + crc ^= u32::from(byte); + for _ in 0..8 { + let mask = (crc & 1).wrapping_neg(); + crc = (crc >> 1) ^ (0xEDB8_8320 & mask); + } + } + !crc +} + +/// 真实 1×1 PNG,IHDR 尺寸改写为 65535×65535(重算 CRC)——头部声明巨图、 +/// 像素数据只有 1×1 的攻击样本。 +fn declared_huge_png() -> Vec { + let mut png = tiny_png(); + png[16..20].copy_from_slice(&65535u32.to_be_bytes()); + png[20..24].copy_from_slice(&65535u32.to_be_bytes()); + let crc = crc32(&png[12..29]); + png[29..33].copy_from_slice(&crc.to_be_bytes()); + png +} + +/// 片段树所有几何值必须有限(污染即在此可见)。 +fn assert_geometry_finite(fragment: &Fragment) { + let border_box = fragment.border_box; + assert!( + border_box.x.is_finite() + && border_box.y.is_finite() + && border_box.width.is_finite() + && border_box.height.is_finite(), + "片段几何有限,实际 {border_box:?}" + ); + for line in &fragment.lines { + assert!(line.baseline.is_finite() && line.height.is_finite()); + for run in &line.runs { + assert!( + run.glyphs + .iter() + .all(|glyph| glyph.x.is_finite() && glyph.advance.is_finite()) + ); + } + for image in &line.images { + assert!( + image.x.is_finite() + && image.y.is_finite() + && image.width.is_finite() + && image.height.is_finite() + ); + } + } + for child in &fragment.children { + assert_geometry_finite(child); + } +} + +/// 组合攻击面(深嵌套 + 巨数属性 + 巨图声明 + 巨数 CSS)走完整管线: +/// parse → 子资源抓取(含解码预检)→ 级联 → 布局 → TextMap → 标题/资源清单 +/// ——不崩、有限时间、几何有限。 +/// +/// 嵌套规模取上限 2 倍(1000 层):html5ever 对每个起始标签都在 open +/// elements 栈上线性扫描(O(深度²)),更大语料在测试里不可行(实测 +/// debug 1000 层 ≈ 0.8s、2000 层 ≈ 3s);截断语义已由 nexty-html 单测钉住。 +#[test] +fn hardening_full_chain_survives_adversarial_page() { + let huge = "9".repeat(45); + let mut html = String::from( + "加固回归\ + \ + ", + ); + // 深嵌套部分:超上限,解析入口截断 + html.push_str(&"
".repeat(1_000)); + html.push_str(&"
".repeat(1_000)); + // 浅层部分:巨数尺寸属性 + 指向巨图声明的 (在截断预算内存活) + html.push_str(&format!( + "

before after

" + )); + + let fetcher = MockFetcher::new(); + fetcher.serve("https://page.test/huge.png", &declared_huge_png()); + + // parse → 子资源抓取(解码预检在 fetch 阶段拒绝巨图声明) + let (document, sub) = + load_page_with_resources(&fetcher, "https://page.test/index.html", &html); + assert!(sub.images.is_empty(), "巨图声明预检被拒,无像素"); + + // 深度截断:树中任意节点 ≤ MAX_TREE_DEPTH,深嵌套部分只保留预算内的层 + let mut max_depth = 0u32; + let mut div_count = 0usize; + let mut stack = vec![document.root()]; + while let Some(id) = stack.pop() { + max_depth = max_depth.max(document.depth(id)); + if let Some(NodeKind::Element(data)) = document.node(id) + && data.name == "div" + { + div_count += 1; + } + for child in document.children(id) { + stack.push(child); + } + } + assert!((max_depth as usize) <= MAX_TREE_DEPTH, "深度有界"); + assert_eq!(div_count, MAX_TREE_DEPTH - 2, "html/body 之外只保留预算内 div"); + + // 标题与资源清单在全链末端仍可用 + assert_eq!(pipeline::document_title(&document).as_deref(), Some("加固回归")); + assert_eq!(nexty_html::collect_image_resources(&document).len(), 1); + + // 级联 → 布局 → TextMap:页面可布局且几何全部有限 + let page = pipeline::build_page(document, sub.stylesheets, sub.images); + let shaper = ParleyTextShaper::new(); + let root = pipeline::layout_page(&page, &shaper, 400.0).expect("root"); + let text_map = nexty_layout::TextMap::new(&root); + let _ = &text_map; + assert_geometry_finite(&root); + + // 显示列表可构建:文本指令在(浅层段落的 before/after) + let scene = pipeline::build_scene(&page, &root); + assert!( + scene + .commands + .iter() + .any(|command| matches!(command, Command::DrawText { .. })), + "文本照常下发" + ); + assert!( + !scene + .commands + .iter() + .any(|command| matches!(command, Command::DrawImage { .. })), + "巨图声明无像素、无 DrawImage" + ); +} diff --git a/crates/nexty-chrome/.mimosa/hook-state/session_164476f9d97ffaabe4f6dc9715b6aad5.mvmhprgt-42404-bfa3e379d5.baseline/2e9d962a08321605940b5a657135052fbcef87b5e360662bb527c96d9a615542.source b/crates/nexty-chrome/.mimosa/hook-state/session_164476f9d97ffaabe4f6dc9715b6aad5.mvmhprgt-42404-bfa3e379d5.baseline/2e9d962a08321605940b5a657135052fbcef87b5e360662bb527c96d9a615542.source new file mode 100644 index 0000000..a5be959 --- /dev/null +++ b/crates/nexty-chrome/.mimosa/hook-state/session_164476f9d97ffaabe4f6dc9715b6aad5.mvmhprgt-42404-bfa3e379d5.baseline/2e9d962a08321605940b5a657135052fbcef87b5e360662bb527c96d9a615542.source @@ -0,0 +1,59 @@ +[package] +name = "nexty-chrome" +description = "Nexty 浏览器外壳:窗口、输入、导航与自绘 UI" +version = "0.1.18" +edition.workspace = true +license.workspace = true +repository.workspace = true +rust-version.workspace = true + +[features] +# 默认开启全部已实现能力。`window` 是二进制外壳本体(winit+wgpu), +# 关闭后本 crate 只剩可无头测试的纯逻辑模块(history/ui/scrollbar/pipeline)。 +default = [ + "pipeline", "resources", "render", "history", "ui", "scrollbar", "selection", "window", +] +# 导航管线:HTML → 级联 → 布局 → 片段树 → paint 显示列表(纯逻辑,可测试)。 +pipeline = [] +# 子资源清单解析、并发抓取与解码编排(纯逻辑,可测试)。 +resources = [] +# 渲染隔离线程:panic 兜底,线程存活可继续服务。 +render = [] +# 会话历史栈(纯逻辑,可测试)。 +history = [] +# 自绘工具带状态机(纯逻辑,可测试)。 +ui = [] +# 滚动几何与拖拽状态机(纯逻辑,可测试)。 +scrollbar = [] +# 页面文本选区状态机(纯逻辑)+ 复制到系统剪贴板。 +selection = ["pipeline", "dep:arboard"] +# 浏览器外壳本体:winit 事件循环 + wgpu 呈现(`run()` 入口)。 +# 依赖 winit / wgpu / pollster 与下层各 crate,故隐含它们。 +window = ["pipeline", "resources", "render", "history", "ui", "scrollbar", "selection", + "dep:winit", "dep:wgpu", "dep:pollster"] + +[dependencies] +nexty-dom = { path = "../nexty-dom", version = "0.1.0" } +nexty-html = { path = "../nexty-html", version = "0.1.0" } +nexty-css = { path = "../nexty-css", version = "0.1.0" } +nexty-layout = { path = "../nexty-layout", version = "0.1.0" } +nexty-text = { path = "../nexty-text", version = "0.1.0" } +nexty-paint = { path = "../nexty-paint", version = "0.1.0" } +nexty-network = { path = "../nexty-network", version = "0.1.0" } +winit = { version = "0.30.13", optional = true } +wgpu = { version = "29", optional = true } +# wgpu 的异步初始化在 winit 事件循环外的同步入口完成 +pollster = { version = "0.4", optional = true } +# 系统剪贴板(选区复制)。只要文本:关闭 default 的 image-data,避免引入 +# 图片剪贴板后端;选型与边界见 docs/decisions/2026-10-23-clipboard.md。 +arboard = { version = "3.7", default-features = false, optional = true } + +[dev-dependencies] +# 仅测试用:构造 PNG 字节喂给资源编排测试(与 nexty-paint 同一依赖) +image = { version = "0.25.10", default-features = false, features = ["png"] } + +# 浏览器可执行入口,仅在 `window` feature 下构建(关闭 window 时无窗口可启)。 +[[bin]] +name = "nexty" +path = "src/bin/nexty.rs" +required-features = ["window"] diff --git a/crates/nexty-chrome/.mimosa/hook-status/session_164476f9d97ffaabe4f6dc9715b6aad5-5e056c09de.json b/crates/nexty-chrome/.mimosa/hook-status/session_164476f9d97ffaabe4f6dc9715b6aad5-5e056c09de.json new file mode 100644 index 0000000..70a3aad --- /dev/null +++ b/crates/nexty-chrome/.mimosa/hook-status/session_164476f9d97ffaabe4f6dc9715b6aad5-5e056c09de.json @@ -0,0 +1,14 @@ +{ + "schemaVersion": "mimosa-hook-status/v1", + "recordedAt": "2026-10-24T15:03:17.639Z", + "sessionId": "session_164476f9d97ffaabe4f6dc9715b6aad5", + "event": "PostToolUse", + "toolName": "Edit", + "file": "Cargo.toml", + "outcome": "inconclusive", + "coverage": "partial", + "findingCount": 0, + "durationMs": 11, + "hostState": "hook_complete", + "reportHint": ".mimosa/reports/" +} diff --git a/crates/nexty-chrome/Cargo.toml b/crates/nexty-chrome/Cargo.toml index 55a91cf..929de5b 100644 --- a/crates/nexty-chrome/Cargo.toml +++ b/crates/nexty-chrome/Cargo.toml @@ -1,7 +1,7 @@ [package] name = "nexty-chrome" description = "Nexty 浏览器外壳:窗口、输入、导航与自绘 UI" -version = "0.1.25" +version = "0.1.29" edition.workspace = true license.workspace = true repository.workspace = true diff --git a/crates/nexty-chrome/src/app.rs b/crates/nexty-chrome/src/app.rs index ec2b9ef..f46afe4 100644 --- a/crates/nexty-chrome/src/app.rs +++ b/crates/nexty-chrome/src/app.rs @@ -1,8 +1,9 @@ //! winit + wgpu 呈现:窗口、输入转译与 Pixmap 上屏。 //! -//! 本模块是无法在无头环境自动化测试的薄胶水层:窗口创建、surface 配置、 -//! 纹理上传与 blit 呈现。所有可测试逻辑(管线、渲染线程、UI 状态机) -//! 都在其余模块并有单测覆盖。 +//! 本模块的 winit/GPU 胶水是无法在无头环境自动化测试的薄层:窗口创建、 +//! surface 配置、纹理上传与 blit 呈现。所有可测试逻辑(管线、渲染线程、 +//! UI 状态机)都在其余模块并有单测覆盖;交互事件接线与生命周期派发集中在 +//! 子模块 [`events`](纯函数部分有无头单测,K1 T3)。 //! //! 呈现路径:页面 + 地址栏 → Scene → [`RenderThread`](隔离线程 + //! `catch_unwind`)→ Pixmap → `wgpu` 纹理 → 全屏 `textureLoad` blit → @@ -11,8 +12,9 @@ use std::sync::Arc; use std::time::{Duration, Instant}; +use nexty_dom::{DeltaMode, NodeId}; use nexty_layout::{Fragment, TextMap}; -use nexty_network::{Method, NetworkError, NetworkFetcher, ReqwestFetcher}; +use nexty_network::{CachedFetcher, NetworkFetcher, ReqwestFetcher}; use nexty_paint::{Pixmap, Scene, Size}; use winit::application::ApplicationHandler; use winit::event::{ElementState, MouseButton, MouseScrollDelta, WindowEvent}; @@ -27,6 +29,8 @@ use crate::scrollbar::{self, ScrollGeometry, Scrollbar, ScrollbarHit}; use crate::selection::{self, Selection}; use crate::ui::{self, AddressBar, BAR_HEIGHT, BarCommand, CaretDirection, UiEvent}; +mod events; + /// 滚轮一格(LineDelta 1.0)对应的滚动距离,px。 const WHEEL_LINE_PX: f32 = 40.0; @@ -55,20 +59,39 @@ impl std::error::Error for AppError {} /// 后台抓取完成后经事件代理送回的载荷。 enum BackgroundEvent { - /// 页面(含子资源:外链 CSS + 解码图片)就绪。载荷装箱(Page 较大, - /// 与单元变体并列时避免枚举整体膨胀)。 + /// 抓取数据面(HTML + 子资源字节/像素)就绪。载荷装箱(与单元变体 + /// 并列时避免枚举整体膨胀)。 PageLoaded(Box), + /// 字体字节就绪(K4 T3):注册进会话注册表,有新注册触发恰好一轮 + /// 重排 + 重绘。 + FontsReady(Box), /// 渲染线程完成一份光栅作业(异步呈现:主线程发请求即返回,不阻塞 /// 等待——巨页帧可达数十秒,阻塞会让窗口进入系统「无响应」状态并 /// 触发 WM_PAINT/WM_SIZE 重绘风暴)。 FrameReady, } +/// [`BackgroundEvent::FontsReady`] 的载荷(K4 T3):抓取成功的字体字节 + +/// 描述符。`url` 是发起抓取的导航 URL(跨页保护:页面已离开时只入库, +/// 不重排当前页)。 +struct FontsReadyPayload { + url: String, + fonts: Vec, +} + /// [`BackgroundEvent::PageLoaded`] 的载荷。 +/// +/// K1 起载荷只携带全 `Send` 数据面([`crate::resources::FetchedPageData`]): +/// `Document` 含监听器注册表(!Send)只能在主线程构建——后台线程只投 +/// 信号与字节,不触碰 Document。K3 T5 起后台编排同步完成(解析 + settle) +/// 后事件才到达,生命周期门控在到达点即满足,不再携带中途信号字段。 struct PageLoadedPayload { url: String, - /// 页面构建结果;错误携带用户可读信息。 - result: Result, + /// 文档 base:响应最终 URL(重定向落点);错误路径与请求 URL 同值 + /// (错误页无子资源,不参与查表)。 + base_url: String, + /// 抓取产物;错误携带用户可读信息。 + result: Result, } /// 启动浏览器窗口。阻塞直至窗口关闭。 @@ -102,11 +125,14 @@ struct Gpu { staging_cache: Option<((u32, u32, u32), Vec)>, } -/// 页面左键按下手势(链接目标在按下时解析,释放且未拖动才导航)。 +/// 页面左键按下手势(链接目标在按下时解析,释放且未拖动才导航; +/// 命中节点存入 `Press`,供 mousedown/mouseup/click 派发作目标)。 struct Press { x: f32, y: f32, link: Option, + /// mousedown 时命中测试的节点(无命中为 None,事件退回文档根)。 + node: Option, } /// 浏览器应用状态。 @@ -117,9 +143,14 @@ struct BrowserApp { renderer: Option, /// 网络接驳缝:后端可整体替换(reqwest 实现或其他 `NetworkFetcher`)。 fetcher: Option>, + /// @font-face 字体编排会话(K4 T3):会话级注册表 + 已注册 URL 集。 + fonts: crate::resources::FontOrchestrator, shaper: nexty_text::ParleyTextShaper, bar: AddressBar, history: History, + /// DOM 宏任务队列(K1):生命周期事件经 post_task 派发、 + /// `run_pending_tasks` 排空(FIFO,派发中 post 不重入)。 + dom_loop: nexty_dom::EventLoop, /// 滚动条交互状态(悬停 / 拖拽)。 scrollbar: Scrollbar, /// Alt 修饰键按住状态(后退/前进快捷键)。 @@ -168,15 +199,21 @@ struct BrowserApp { impl BrowserApp { fn new(proxy: EventLoopProxy) -> Self { + // 字体注册表先于整形器创建:整形器经 with_registry 接线(K4 T3), + // 此后 register 即生效、无需重建(nexty-text T2 语义)。 + let fonts = crate::resources::FontOrchestrator::new(); + let shaper = nexty_text::ParleyTextShaper::with_registry(fonts.registry()); Self { proxy, window: None, gpu: None, renderer: None, fetcher: None, - shaper: nexty_text::ParleyTextShaper::new(), + fonts, + shaper, bar: AddressBar::new("about:blank"), history: History::new("about:blank"), + dom_loop: nexty_dom::EventLoop::new(), scrollbar: Scrollbar::new(), alt_down: false, ctrl_down: false, @@ -230,9 +267,11 @@ impl BrowserApp { // 启动路径用 fail-fast:TLS 后端不可用时浏览器本就无法工作, // 带着半初始化的状态继续跑不如立刻退出(渲染路径才需要降级)。 // 整请求超时 30s:真实站点挂起时不无限占住加载状态。 - self.fetcher = Some(Arc::new( + // 抓取栈接 HTTP 内存缓存(K3 T4/T5):主文档与子资源共用同一实例, + // 同 URL 二次导航 / 重复子资源直接命中缓存,不再打网络。 + self.fetcher = Some(Arc::new(CachedFetcher::new( ReqwestFetcher::with_timeout(Duration::from_secs(30)).expect("network fetcher"), - )); + ))); self.show_blank(); window.request_redraw(); } @@ -241,6 +280,11 @@ impl BrowserApp { fn show_blank(&mut self) { self.bar.set_url("about:blank"); self.set_page(pipeline::load_page("", ""), true); + // 内部页生命周期:主线程本地解析完成、零子资源编排 = 立即 settle + self.dispatch_page_lifecycle(pipeline::PendingLifecycle { + dom_content_loaded: true, + load: true, + }); } /// 当前视口与内容对应的滚动几何;窗口未创建时为 `None`。 @@ -395,10 +439,27 @@ impl BrowserApp { /// 开始一次页面点击/选择手势。 fn begin_page_gesture(&mut self, x: f32, y: f32) { + let page_y = y - BAR_HEIGHT + self.scroll_y; + // 单次命中测试同时供事件目标与链接解析(hit_test_ex 结果 → 事件节点) + let hit = self + .root + .as_ref() + .and_then(|root| pipeline::hit_test_ex(root, x, page_y)); + let node = hit.map(|hit| hit.node); + let link = hit + .and_then(|hit| { + self.page + .as_ref() + .and_then(|page| pipeline::link_target(page, hit.node)) + }) + .and_then(|href| nexty_network::resolve(self.history.current(), &href).ok()); + // mousedown 先派发后默认:默认动作 = 开始选择手势(含地址栏失焦, + // 同浏览器 preventDefault mousedown 阻止焦点转移)。取消则手势不开始。 + if !self.dispatch_page_mouse(node, "mousedown", x, y, 1) { + return; + } // 页面点击让地址栏失焦:之后 Ctrl+A / Ctrl+C 作用于页面。 self.bar.blur(); - let page_y = y - BAR_HEIGHT + self.scroll_y; - let link = self.link_at(x, page_y); let position = self.text_map.as_ref().and_then(|map| map.hit(x, page_y)); let now = Instant::now(); let double_click = self.last_click.is_some_and(|(time, last_x, last_y)| { @@ -422,30 +483,25 @@ impl BrowserApp { } None => self.selection.clear(), } - self.press = Some(Press { x, y, link }); + self.press = Some(Press { x, y, link, node }); if let Some(window) = &self.window { window.request_redraw(); } } - /// 页面点命中的链接绝对地址(无链接或解析失败返回 `None`)。 - fn link_at(&self, x: f32, page_y: f32) -> Option { - self.root - .as_ref() - .and_then(|root| pipeline::hit_test(root, x, page_y)) - .and_then(|node| { - self.page - .as_ref() - .and_then(|page| pipeline::link_target(page, node)) - }) - .and_then(|href| nexty_network::resolve(self.history.current(), &href).ok()) - } - /// 导航:入历史栈并加载。 + /// + /// 地址栏输入与页面链接共用入口。地址栏输入在这里做 URL 规范化:无 + /// scheme 补 `http://`(HTTP-first,决策见 + /// `docs/decisions/2026-10-31-addressbar-url.md` 与 + /// [`crate::resources::normalize_address_bar_input`]);链接 href 已由 + /// `resolve` 按文档 base 绝对化,规范化对其无操作。历史栈存规范化后 + /// 的 URL:后退/前进重放的即实际导航目标。 fn navigate(&mut self, url: &str) { - self.history.push(url.to_owned()); + let url = crate::resources::normalize_address_bar_input(url); + self.history.push(url.clone()); self.sync_history_flags(); - self.load(url); + self.load(&url); } /// 后退/前进(历史栈搬运后按目标 URL 加载,不再入栈)。 @@ -485,9 +541,10 @@ impl BrowserApp { self.bar.set_url(url.to_owned()); self.bar.set_loading(true); - // 内部 scheme(about:blank 等)不由网络抓取,直接生成本地空白页。 - // 交给 NetworkFetcher 会被协议白名单判为 InvalidUrl,白屏。 - if !url.starts_with("http://") && !url.starts_with("https://") { + // 内部 scheme(about:blank 等)不经网络,直接生成本地空白页。 + // 其余 URL(含补全 scheme 后仍非法的输入)交给抓取路径:协议白名单 + // 判 InvalidUrl → 错误页给出反馈,不再静默白屏。 + if url.starts_with("about:") { self.bar.set_loading(false); self.show_blank(); if let Some(window) = &self.window { @@ -503,70 +560,62 @@ impl BrowserApp { let Some(proxy) = Some(self.proxy.clone()) else { return; }; - let url = url.to_owned(); - let target = url.clone(); + let target = url.to_owned(); std::thread::Builder::new() .name("nexty-fetch".to_owned()) .spawn(move || { - let request = nexty_network::Request { - url: target.clone(), - method: Method::Get, - // 不少真实站点对无 UA 请求直接 403/429 - headers: vec![( - "User-Agent".to_owned(), - format!("Nexty/{}", env!("CARGO_PKG_VERSION")), - )], - }; - // 全部加载在后台线程完成:文档抓取 → 解析 → 子资源并发抓取 - // → 级联 → 页面就绪。主线程只做布局与呈现。 - // 错误串收敛为「错误类别 + 状态码」:不回显上游原始错误 - //(reqwest 的错误文本内含目标 URL),错误页只显示类别。 - let result = match fetcher.fetch(&request) { - Ok(response) if (200..300).contains(&response.status) => { - if response.body.len() > crate::resources::MAX_DOCUMENT_BODY_BYTES { - Err("响应体超出预算".to_owned()) - } else { - match String::from_utf8(response.body) { - Ok(html) => { - let document = nexty_html::parse_document( - &html, - nexty_html::ParseOptions::default(), - ); - let resources = crate::resources::fetch_subresources( - fetcher.as_ref(), - &url, - &document, - ); - Ok(pipeline::build_page( - document, - resources.stylesheets, - resources.images, - )) - } - Err(_) => Err("响应不是有效的文本".to_owned()), - } - } - } - Ok(response) => Err(format!("HTTP {}", response.status)), - Err(error) => Err(load_error_text(&error).to_owned()), + // 全部抓取在后台线程完成:文档抓取 → 解码 → 规划解析 → + // 子资源并发抓取与解码(resources::fetch_document 同步编排), + // 产出全 Send 数据面(K1 起 Document 含监听器注册表 !Send, + // 只能在主线程构建——主线程按同一 HTML 重建正式文档)。 + // 错误串收敛为「错误类别 + 状态码」(见 fetch_document)。 + let result = crate::resources::fetch_document(fetcher.as_ref(), &target); + let base_url = match &result { + Ok(fetched) => fetched.base_url.clone(), + Err(_) => target.clone(), }; let _ = proxy.send_event(BackgroundEvent::PageLoaded(Box::new(PageLoadedPayload { - url, + url: target, + base_url, result, }))); }) .expect("spawn fetch thread"); } - /// 抓取完成:重建页面与显示列表。 - fn page_loaded(&mut self, url: String, result: Result) { + /// 抓取完成:重建页面与显示列表,并派发生命周期事件。 + fn page_loaded(&mut self, payload: PageLoadedPayload) { self.bar.set_loading(false); - match result { - Ok(page) => { + // 生命周期门控:后台编排同步完成(解析 + settle)后事件才到达; + // 错误页在主线程本地合成解析——两条路径的 DOMContentLoaded 与 load + // 门控均已满足,经 EventLoop post_task 按 FIFO 顺序派发。 + let pending = pipeline::PendingLifecycle { + dom_content_loaded: true, + load: true, + }; + match payload.result { + Ok(fetched) => { + // 正式文档在主线程构建(Document 含监听器注册表 !Send): + // 按同一 HTML 重建,并装配后台线程抓取的子资源数据面。 + // 查表 base 与后台抓取一致:响应最终 URL(重定向落点)。 + let document = nexty_html::parse_document( + &fetched.data.html, + nexty_html::ParseOptions::default(), + ); + let resources = crate::resources::assemble_page_data( + &document, + &payload.base_url, + &fetched.data, + ); + // @font-face 字体源收集与后台抓取(K4 T3):不在 load 门控 + // 内,首帧先用系统字体渲染;字节就绪注册后经 FontsReady + // 触发恰好一轮重排(font-display swap 简化)。 + self.spawn_font_fetch(&resources.stylesheets, &payload.base_url, &payload.url); + let page = pipeline::build_page(document, resources.stylesheets, resources.images); let title = pipeline::document_title(&page.document); self.set_page(page, true); - self.bar.set_url(url); + self.bar.set_url(payload.url); if let Some(window) = &self.window { match title { Some(title) => window.set_title(&format!("{title} - Nexty")), @@ -575,16 +624,75 @@ impl BrowserApp { } } Err(error) => { - eprintln!("load {url} failed: {error}"); + eprintln!("load {} failed: {error}", payload.url); // 失败也要出错误页:只打日志会让画面停在上一帧或空白, // 用户看不到任何反馈。 - let html = error_page_html(&url, &error); + let html = error_page_html(&payload.url, &error); self.set_page(pipeline::load_page(&html, ""), true); if let Some(window) = &self.window { window.set_title("加载失败 - Nexty"); } } } + // 生命周期派发经 EventLoop post_task(DOMContentLoaded → load,FIFO) + self.dispatch_page_lifecycle(pending); + } + + /// 收集 @font-face 源并在后台线程抓取字体字节(K4 T3)。 + /// + /// 无待抓取源(无 @font-face / 全部会话已注册 / woff2 提示跳过)时 + /// 不起线程:已注册字体的重复导航零抓取、零重排。 + fn spawn_font_fetch( + &mut self, + stylesheets: &[nexty_css::Stylesheet], + base_url: &str, + url: &str, + ) { + let requests = self.fonts.collect(stylesheets, base_url); + if requests.is_empty() { + return; + } + let Some(fetcher) = self.fetcher.clone() else { + return; + }; + let proxy = self.proxy.clone(); + let url = url.to_owned(); + std::thread::Builder::new() + .name("nexty-fonts".to_owned()) + .spawn(move || { + // 抓取降级语义与主文档子资源一致(404 / 超预算 / 传输错误 + // 缺席);全空则无事可做,不回送事件。 + let fonts = crate::resources::fetch_fonts(fetcher.as_ref(), &requests); + if fonts.is_empty() { + return; + } + let _ = + proxy.send_event(BackgroundEvent::FontsReady(Box::new(FontsReadyPayload { + url, + fonts, + }))); + }) + .expect("spawn font fetch thread"); + } + + /// 字体字节就绪:注册进会话注册表;有新注册时重级联 + 重排 + 重绘 + /// **恰好一轮**(K4 T3)。已接线的整形器自动命中注册字体(nexty-text + /// T2);chunk 分析缓存随新片段树重建,场景缓存随代次推进失效。载荷 + /// 属于已离开的页面时只入库(会话缓存跨页有效),不重排。 + fn fonts_ready(&mut self, payload: FontsReadyPayload) { + let registration = self.fonts.register(payload.fonts); + if registration.rejected > 0 { + eprintln!( + "font registration rejected {} source(s); fallback to system fonts", + registration.rejected + ); + } + if registration.registered > 0 && payload.url == self.history.current() { + self.relayout(); + if let Some(window) = &self.window { + window.request_redraw(); + } + } } /// 一帧:合成显示列表并发给渲染线程(异步,不等待)。 @@ -636,17 +744,10 @@ impl BrowserApp { Some(map) if !self.selection.is_empty() => self.selection.rects(map), _ => Vec::new(), }; - // 画布底色:pipeline 的画布保持透明,直接 blit 会把透明像素交给 - // surface(alpha_mode Auto),在部分后端表现为黑屏/花屏。先铺不透明白底。 - let white_background = nexty_paint::Command::FillRect { - rect: nexty_paint::Rect { - x: 0.0, - y: 0.0, - width, - height, - }, - color: nexty_paint::Color::opaque(0xff, 0xff, 0xff), - }; + // 画布底色:CSS 2.2 §14.2 html/body 背景传播到画布——html 携带背景 + // 用 html,否则 body,都无回落白;视口坐标系,不随滚动平移。画布 + // 必须不透明:透明像素直接 blit 给 surface(alpha_mode Auto)在部分 + // 后端表现为黑屏/花屏。被传播元素的自身背景由 emit 抑制(搬移语义)。 let mut scene = match (&self.page, &self.root) { (Some(page), Some(root)) => { let page_scene = self.scene_cache.scene_for( @@ -657,12 +758,26 @@ impl BrowserApp { &highlights, ); let mut scene = page_scene.translated(0.0, BAR_HEIGHT - self.scroll_y); - scene.commands.insert(0, white_background); + for (index, command) in pipeline::canvas_background_commands(page, width, height) + .into_iter() + .enumerate() + { + scene.commands.insert(index, command); + } scene } _ => { + // 无页面(启动空窗):无从传播,固定白底。 let mut scene = Scene::default(); - scene.commands.push(white_background); + scene.commands.push(nexty_paint::Command::FillRect { + rect: nexty_paint::Rect { + x: 0.0, + y: 0.0, + width, + height, + }, + color: nexty_paint::Color::opaque(0xff, 0xff, 0xff), + }); scene } }; @@ -763,7 +878,9 @@ impl ApplicationHandler for BrowserApp { fn user_event(&mut self, _event_loop: &ActiveEventLoop, event: BackgroundEvent) { match event { - BackgroundEvent::PageLoaded(payload) => self.page_loaded(payload.url, payload.result), + BackgroundEvent::PageLoaded(payload) => self.page_loaded(*payload), + // 字体字节就绪:注册 + 恰一轮重排(K4 T3) + BackgroundEvent::FontsReady(payload) => self.fonts_ready(*payload), // 渲染线程完成:上屏最新一帧,按需补排帧 BackgroundEvent::FrameReady => self.present_finished_frames(), } @@ -838,12 +955,23 @@ impl ApplicationHandler for BrowserApp { self.update_cursor_icon(); } WindowEvent::MouseWheel { delta, .. } => { - // 滚轮向上(y > 0)→ 减小滚动量 - let amount = match delta { - MouseScrollDelta::LineDelta(_, y) => y * WHEEL_LINE_PX, - MouseScrollDelta::PixelDelta(position) => position.y as f32, + // 滚轮先派发后默认:WheelEvent(正值 deltaY = 页面向下滚, + // 与 winit 相反号)未取消才滚动,滚动量换算沿用现语义。 + let (mode, amount, wheel_delta) = match delta { + MouseScrollDelta::LineDelta(x, y) => ( + DeltaMode::Line, + y * WHEEL_LINE_PX, + (-f64::from(x), -f64::from(y)), + ), + MouseScrollDelta::PixelDelta(position) => ( + DeltaMode::Pixel, + position.y as f32, + (-position.x, -position.y), + ), }; - self.scroll_by(-amount); + if self.dispatch_page_wheel(wheel_delta, mode) { + self.scroll_by(-amount); + } } WindowEvent::MouseInput { state: ElementState::Pressed, @@ -875,10 +1003,18 @@ impl ApplicationHandler for BrowserApp { } => { self.scrollbar.on_release(); if let Some(press) = self.press.take() { - self.selection.finish(); let dragged = !selection::is_click((press.x, press.y), self.cursor); - // 释放且未拖动才算点击:链接此时导航,拖过链接文字只选择。 - if !dragged && let Some(url) = press.link { + // mouseup 先派发后默认;selection.finish 与滚动条 + // on_release 一样是 chrome 侧手势状态卫生(无论取消都 + // 执行,避免状态机卡在拖拽态)。 + let _ = self.dispatch_page_mouse(press.node, "mouseup", press.x, press.y, 0); + self.selection.finish(); + // 释放且未拖动才算点击:click 仅此时派发(现语义), + // 默认动作 = 链接导航,被取消则跳过(先派发后默认)。 + if !dragged + && self.dispatch_page_mouse(press.node, "click", press.x, press.y, 0) + && let Some(url) = press.link + { self.navigate(&url); } } @@ -893,21 +1029,28 @@ impl ApplicationHandler for BrowserApp { self.shift_down = state.shift_key(); } WindowEvent::KeyboardInput { event, .. } if event.state == ElementState::Pressed => { - let modifiers = ui::Modifiers { - ctrl: self.ctrl_down, - shift: self.shift_down, - alt: self.alt_down, - }; + let modifiers = self.modifiers(); let key = ui_key(&event.logical_key); - // 浏览器级快捷键优先于一切(Alt+方向键、Ctrl+L/R/A、F5、Esc) + // 浏览器级快捷键优先于一切(Alt+方向键、Ctrl+L/R/A、F5、Esc)。 + // 「先派发后默认」:地址栏聚焦时键属 chrome UI(不进页面), + // 直接执行;未聚焦时先派发可取消 keydown,未取消才执行。 if let Some(key) = key && let Some(shortcut) = ui::shortcut(key, modifiers) { - self.apply_shortcut(shortcut); + let allowed = if self.bar.is_focused() { + true + } else { + let (key_name, code) = events::dom_key_names(key); + self.dispatch_page_key(&key_name, &code, event.repeat) + }; + if allowed { + self.apply_shortcut(shortcut); + } return; } if self.bar.is_focused() { // 地址栏聚焦:方向键/Home/End 作用于光标(Shift 扩选) + // —— chrome UI 键,不派发到页面 if let Some(direction) = key.and_then(caret_direction) { let _ = self.bar.handle(UiEvent::MoveCaret { direction, @@ -915,29 +1058,31 @@ impl ApplicationHandler for BrowserApp { }); } } else { - // 未聚焦:翻页/滚动键作用于页面 + // 未聚焦:翻页/滚动键作用于页面——先派发后默认 let page_step = self .geometry() .map_or(0.0, |geometry| geometry.page_step() * 0.9); match event.logical_key { Key::Named(NamedKey::PageDown) => { - self.scroll_by(page_step); + self.dispatch_key_scroll("PageDown", page_step); } Key::Named(NamedKey::PageUp) => { - self.scroll_by(-page_step); + self.dispatch_key_scroll("PageUp", -page_step); } Key::Named(NamedKey::ArrowDown) => { - self.scroll_by(WHEEL_LINE_PX); + self.dispatch_key_scroll("ArrowDown", WHEEL_LINE_PX); } Key::Named(NamedKey::ArrowUp) => { - self.scroll_by(-WHEEL_LINE_PX); + self.dispatch_key_scroll("ArrowUp", -WHEEL_LINE_PX); } Key::Named(NamedKey::Home) => { - self.scroll_by(-self.scroll_y); + let delta = -self.scroll_y; + self.dispatch_key_scroll("Home", delta); } Key::Named(NamedKey::End) => { if let Some(geometry) = self.geometry() { - self.scroll_by(geometry.max_scroll() - self.scroll_y); + let delta = geometry.max_scroll() - self.scroll_y; + self.dispatch_key_scroll("End", delta); } } _ => {} @@ -1395,18 +1540,6 @@ fn pad_rows_into(out: &mut Vec, data: &[u8], width: u32, height: u32, padded } } -/// 传输失败 → 错误类别文本。 -/// -/// 不回显上游原始错误串:reqwest 的错误文本内含目标 URL,而错误页是按 -/// 页面语义渲染的 HTML——错误信息只保留「类别」这一用户需要知道的内容。 -fn load_error_text(error: &NetworkError) -> &'static str { - match error { - NetworkError::InvalidUrl => "无效的地址", - NetworkError::Timeout => "请求超时", - NetworkError::Transport => "网络错误", - } -} - /// HTML 实体转义(`&` `<` `>` `"` `'`)。 /// /// 错误页把不可信文本(URL、错误类别)拼进 HTML:不转义的话,形如 diff --git a/crates/nexty-chrome/src/app/events.rs b/crates/nexty-chrome/src/app/events.rs new file mode 100644 index 0000000..9e3065d --- /dev/null +++ b/crates/nexty-chrome/src/app/events.rs @@ -0,0 +1,469 @@ +//! 交互事件接线与生命周期派发(K1 T3)——chrome 侧事件接线的集中点。 +//! +//! 从 `app` 的输入路由迁出的事件派发部分全在本模块: +//! +//! - **交互事件**:`hit_test_ex` 命中节点(无命中退回文档根)上构造数据面 +//! 事件(`MouseEvent` / `WheelEvent` / `KeyboardEvent`,bubbles=true、 +//! cancelable=true,字段由派发方填)并派发;`Document::dispatch` 返回 +//! 「未取消」(true)→ 调用方执行默认动作。链接导航、滚轮滚动、键盘 +//! 滚动与快捷键全部走「先派发后默认」——无监听器时行为与接线前一致。 +//! - **生命周期**:页面安装点按跨线程信号(HTML 解析完成 / 首轮子资源 +//! 编排 settle,见 [`PendingLifecycle`])经 pipeline 的单处钩子 +//! `Page::post_lifecycle_tasks` post 进 [`EventLoop`],`run_pending_tasks` +//! 排空派发(FIFO:DOMContentLoaded 先于 load;派发中 post 不重入)。 +//! +//! 数据面构造与派发是纯函数(可无头单测);winit → chrome UI 的路由 +//! (地址栏、滚动条、悬停)仍在 `app.rs`,不属于页面 DOM 事件。 +//! +//! 偏差(K1 简化档):监听器回调只见核心 [`Event`] 面,读不到类型化数据 +//! 字段(K5 扩回调签名);`screenX/Y` 未跟踪(置 0);无 mousemove/悬停 +//! 派发(悬停只更新光标);地址栏聚焦时按键属 chrome UI,不派发到页面。 + +use nexty_dom::{DeltaMode, KeyboardEvent, MouseEvent, NodeId, WheelEvent}; + +use super::BrowserApp; +use crate::pipeline::{self, Page, PendingLifecycle}; +use crate::ui::{self, BAR_HEIGHT, Modifiers}; + +/// 派发鼠标事件(mousedown / mouseup / click)到 `target`。 +/// +/// `client` 为页面视口坐标(UI Events clientX/Y:相对视口,不含滚动偏移); +/// button 固定主键 0,`buttons` 为按住位掩码(UI Events §5.2.2:按下主键 +/// 为 1,释放后为 0)。bubbles=true、cancelable=true。返回「未取消」: +/// false = 已被 [`prevent_default`](nexty_dom::Event::prevent_default), +/// 默认动作必须跳过。 +pub(super) fn dispatch_mouse( + page: &mut Page, + target: NodeId, + type_: &'static str, + client: (f32, f32), + buttons: u16, + modifiers: Modifiers, +) -> bool { + let mut event = MouseEvent::new(type_, true, true); + event.detail = 1; + event.client_x = client.0 as i32; + event.client_y = client.1 as i32; + event.button = 0; + event.buttons = buttons; + event.ctrl_key = modifiers.ctrl; + event.shift_key = modifiers.shift; + event.alt_key = modifiers.alt; + page.document.dispatch(target, &mut event.event) +} + +/// 派发滚轮事件(wheel)到 `target`。 +/// +/// `delta` 为 UI Events 语义(正值 deltaY = 页面向下滚),单位由 `mode` +/// 标注;简化档的 `WheelEvent` 数据面无坐标与修饰键字段。bubbles=true、 +/// cancelable=true。返回「未取消」。 +pub(super) fn dispatch_wheel( + page: &mut Page, + target: NodeId, + delta: (f64, f64), + mode: DeltaMode, +) -> bool { + let mut event = WheelEvent::new("wheel", true, true); + event.delta_x = delta.0; + event.delta_y = delta.1; + event.delta_mode = mode; + page.document.dispatch(target, &mut event.event) +} + +/// 派发键盘事件(keydown)到 `target`。 +/// +/// `key` / `code` 为 UI Events 键值与物理键位字符串;bubbles=true、 +/// cancelable=true。返回「未取消」。 +pub(super) fn dispatch_key( + page: &mut Page, + target: NodeId, + key: &str, + code: &str, + modifiers: Modifiers, + repeat: bool, +) -> bool { + let mut event = KeyboardEvent::new("keydown", true, true); + event.key = key.to_owned(); + event.code = code.to_owned(); + event.ctrl_key = modifiers.ctrl; + event.shift_key = modifiers.shift; + event.alt_key = modifiers.alt; + event.repeat = repeat; + page.document.dispatch(target, &mut event.event) +} + +/// chrome 抽象键 → DOM `key`/`code` 字符串(KeyboardEvent 数据面填充用)。 +/// +/// 字符键 `key` 取原文、`code` 按 `Key<大写>`;命名键两处同名——物理键位 +/// 的精确 `code` 面记入偏差清单(简化档不读 winit physical_key)。 +pub(super) fn dom_key_names(key: ui::Key) -> (String, String) { + match key { + ui::Key::Character(character) => { + let key = character.to_string(); + let code = format!("Key{}", character.to_ascii_uppercase()); + (key, code) + } + ui::Key::Left => ("ArrowLeft".to_owned(), "ArrowLeft".to_owned()), + ui::Key::Right => ("ArrowRight".to_owned(), "ArrowRight".to_owned()), + ui::Key::Home => ("Home".to_owned(), "Home".to_owned()), + ui::Key::End => ("End".to_owned(), "End".to_owned()), + ui::Key::F5 => ("F5".to_owned(), "F5".to_owned()), + ui::Key::Escape => ("Escape".to_owned(), "Escape".to_owned()), + } +} + +impl BrowserApp { + /// 当前修饰键快照(winit ModifiersChanged 维护的三个布尔)。 + pub(super) fn modifiers(&self) -> Modifiers { + Modifiers { + ctrl: self.ctrl_down, + shift: self.shift_down, + alt: self.alt_down, + } + } + + /// 窗口点 `(x, y)` 在页面里的命中节点(工具带高度已扣除并叠加滚动)。 + pub(super) fn hit_node_at(&self, x: f32, y: f32) -> Option { + let page_y = y - BAR_HEIGHT + self.scroll_y; + self.root + .as_ref() + .and_then(|root| pipeline::hit_test_ex(root, x, page_y)) + .map(|hit| hit.node) + } + + /// 在命中节点(`node` 为 None 时退回文档根)派发页面鼠标事件。 + /// + /// `x`/`y` 为窗口坐标;client 取页面视口坐标(扣工具带高度,不含滚动 + /// 偏移)。无页面时视为未取消(默认动作照常——与无监听器时一致)。 + pub(super) fn dispatch_page_mouse( + &mut self, + node: Option, + type_: &'static str, + x: f32, + y: f32, + buttons: u16, + ) -> bool { + let modifiers = self.modifiers(); + let Some(page) = self.page.as_mut() else { + return true; + }; + let target = match node { + Some(node) => node, + None => page.document.root(), + }; + dispatch_mouse(page, target, type_, (x, y - BAR_HEIGHT), buttons, modifiers) + } + + /// 派发滚轮事件(光标命中节点或文档根)。返回「未取消」。 + pub(super) fn dispatch_page_wheel(&mut self, delta: (f64, f64), mode: DeltaMode) -> bool { + let (x, y) = self.cursor; + let node = self.hit_node_at(x, y); + let Some(page) = self.page.as_mut() else { + return true; + }; + let target = match node { + Some(node) => node, + None => page.document.root(), + }; + dispatch_wheel(page, target, delta, mode) + } + + /// 派发页面键盘事件(keydown,文档根上)。返回「未取消」。 + /// + /// 调用边界:地址栏聚焦时键属 chrome UI,不派发到页面(调用方保证); + /// 无页面时视为未取消。 + pub(super) fn dispatch_page_key(&mut self, key: &str, code: &str, repeat: bool) -> bool { + let modifiers = self.modifiers(); + let Some(page) = self.page.as_mut() else { + return true; + }; + let target = page.document.root(); + dispatch_key(page, target, key, code, modifiers, repeat) + } + + /// 滚动键的「先派发后默认」:keydown 未取消才执行滚动。 + pub(super) fn dispatch_key_scroll(&mut self, key: &'static str, delta: f32) { + if self.dispatch_page_key(key, key, false) { + self.scroll_by(delta); + } + } + + /// 页面安装点的生命周期派发:按跨线程信号 post DOMContentLoaded / load + /// 任务(pipeline 单处钩子构造,FIFO 保序),随即排空——事件在当前 + /// 页面文档根上派发。信号未到的事件不 post(K3/K4 异步 settle 的接缝)。 + pub(super) fn dispatch_page_lifecycle(&mut self, pending: PendingLifecycle) { + if pending.is_empty() { + return; + } + if let Some(page) = self.page.as_mut() { + page.post_lifecycle_tasks(&mut self.dom_loop, pending); + } + self.run_dom_tasks(); + } + + /// 排空 DOM 宏任务队列(任务在当前页面文档上执行)。 + pub(super) fn run_dom_tasks(&mut self) { + if let Some(page) = self.page.as_mut() { + self.dom_loop.run_pending_tasks(&mut page.document); + } + } +} + +#[cfg(test)] +mod tests { + use super::*; + use crate::pipeline; + use nexty_dom::{Event, EventListener}; + use std::cell::RefCell; + use std::rc::Rc; + + type Log = Rc>>; + + /// 鼠标事件记录器:按事件类型记入日志;`prevent_click` 为真时对 click + /// 调 [`Event::prevent_default`](模拟页面监听器取消默认动作)。 + struct ClickLogger { + log: Log, + prevent_click: bool, + } + + impl EventListener for ClickLogger { + fn handle_event(&mut self, event: &mut Event) { + let label = match event.type_() { + "mousedown" => "mousedown", + "mouseup" => "mouseup", + "click" => "click", + _ => "other", + }; + self.log.borrow_mut().push(label); + if self.prevent_click && event.type_() == "click" { + event.prevent_default(); + } + } + } + + /// 块级链接页 + 命中节点(布局 200px 视口,点 (10, 5) 命中 `` 盒)。 + fn link_page(log: &Log, prevent_click: bool) -> (Page, NodeId) { + let mut page = pipeline::load_page( + "block link", + "body { margin: 0 }", + ); + let shaper = nexty_text::ParleyTextShaper::new(); + let root = pipeline::layout_page(&page, &shaper, 200.0).expect("root"); + let node = pipeline::hit_test(&root, 10.0, 5.0).expect("命中链接"); + page.document.add_listener( + node, + "mousedown", + false, + Box::new(ClickLogger { + log: Rc::clone(log), + prevent_click: false, + }), + ); + page.document.add_listener( + node, + "mouseup", + false, + Box::new(ClickLogger { + log: Rc::clone(log), + prevent_click: false, + }), + ); + page.document.add_listener( + node, + "click", + false, + Box::new(ClickLogger { + log: Rc::clone(log), + prevent_click, + }), + ); + (page, node) + } + + /// ① click 派发且默认导航仍发生:三事件按序派发、click 未取消—— + /// app 侧据此执行链接导航(默认动作)。 + #[test] + fn click_sequence_dispatches_and_default_navigation_runs() { + let log: Log = Rc::new(RefCell::new(Vec::new())); + let (mut page, target) = link_page(&log, false); + let modifiers = Modifiers::default(); + + // app.rs 的点击序列:mousedown(主键按住 buttons=1)→ mouseup → + // click(释放且未拖动才派发,现语义)。 + assert!(dispatch_mouse( + &mut page, + target, + "mousedown", + (10.0, 5.0), + 1, + modifiers + )); + assert!(dispatch_mouse( + &mut page, + target, + "mouseup", + (10.0, 5.0), + 0, + modifiers + )); + assert!( + dispatch_mouse(&mut page, target, "click", (10.0, 5.0), 0, modifiers), + "无取消监听器:click 未取消 → 默认导航执行" + ); + assert_eq!( + *log.borrow(), + ["mousedown", "mouseup", "click"], + "点击序列 mousedown → mouseup → click 完整派发" + ); + } + + /// ② 注入测试监听器 preventDefault 后默认导航被跳过——「先派发后默认」 + /// 顺序的证据:监听器在 click 派发中置 defaultPrevented,导航判定 + /// (dispatch 返回值)在其后读到 false。mousedown/mouseup 不受影响。 + #[test] + fn prevent_default_click_skips_default_navigation() { + let log: Log = Rc::new(RefCell::new(Vec::new())); + let (mut page, target) = link_page(&log, true); + let modifiers = Modifiers::default(); + + assert!(dispatch_mouse( + &mut page, + target, + "mousedown", + (10.0, 5.0), + 1, + modifiers + )); + assert!(dispatch_mouse( + &mut page, + target, + "mouseup", + (10.0, 5.0), + 0, + modifiers + )); + assert!( + !dispatch_mouse(&mut page, target, "click", (10.0, 5.0), 0, modifiers), + "preventDefault 后 dispatch 返回已取消 → 默认导航被跳过" + ); + assert_eq!( + *log.borrow(), + ["mousedown", "mouseup", "click"], + "事件照常派发,被取消的只是默认动作" + ); + } + + /// ③ 生命周期(pipeline 单处钩子):按信号 post、排空派发—— + /// DOMContentLoaded 在解析后、load 在子资源 settle 后,各恰一次、FIFO + /// 保序。与 tests/chrome.rs 的集成测试互补(那里走完整抓取编排)。 + #[test] + fn lifecycle_posts_dispatch_exactly_once_per_signal_in_fifo_order() { + let mut page = pipeline::load_page("hi", ""); + let log: Log = Rc::new(RefCell::new(Vec::new())); + let root = page.document.root(); + let recorder = |log: &Log, label: &'static str| { + let log = Rc::clone(log); + Box::new(move |_event: &mut Event| log.borrow_mut().push(label)) + as Box + }; + page.document.add_listener( + root, + nexty_dom::DOM_CONTENT_LOADED, + false, + recorder(&log, "dcl"), + ); + page.document + .add_listener(root, nexty_dom::LOAD, false, recorder(&log, "load")); + + // 无信号:不 post、不派发 + let mut event_loop = nexty_dom::EventLoop::new(); + page.post_lifecycle_tasks(&mut event_loop, PendingLifecycle::default()); + event_loop.run_pending_tasks(&mut page.document); + assert!(log.borrow().is_empty(), "信号未到不派发"); + + // 只到解析信号:仅 DOMContentLoaded + page.post_lifecycle_tasks( + &mut event_loop, + PendingLifecycle { + dom_content_loaded: true, + load: false, + }, + ); + event_loop.run_pending_tasks(&mut page.document); + assert_eq!(*log.borrow(), ["dcl"], "仅 DOMContentLoaded 派发"); + + // settle 信号到:load 恰一次 + page.post_lifecycle_tasks( + &mut event_loop, + PendingLifecycle { + dom_content_loaded: false, + load: true, + }, + ); + event_loop.run_pending_tasks(&mut page.document); + assert_eq!( + *log.borrow(), + ["dcl", "load"], + "DOMContentLoaded 先于 load,各恰一次" + ); + + // 队列已空:重复排空不重复派发 + event_loop.run_pending_tasks(&mut page.document); + assert_eq!(log.borrow().len(), 2, "排空后无重复派发"); + } + + /// 滚轮/键盘事件在命中节点与文档根上的派发与取消语义(字段填充对 + /// 监听器不可见是 K1 登记偏差,字段面由检视覆盖)。 + #[test] + fn wheel_and_key_dispatch_gating() { + let mut page = pipeline::load_page("x", ""); + let root_node = page.document.root(); + let hits = Rc::new(RefCell::new(Vec::new())); + let wheel_hits = Rc::clone(&hits); + page.document.add_listener( + root_node, + "wheel", + false, + Box::new(move |event: &mut Event| { + wheel_hits.borrow_mut().push(event.type_().to_owned()); + event.prevent_default(); + }), + ); + assert!( + !dispatch_wheel(&mut page, root_node, (0.0, -40.0), DeltaMode::Line), + "wheel 被 preventDefault → 默认滚动跳过" + ); + assert_eq!(*hits.borrow(), ["wheel"]); + + let key_hits = Rc::new(RefCell::new(Vec::new())); + page.document.add_listener( + root_node, + "keydown", + false, + Box::new(move |_event: &mut Event| key_hits.borrow_mut().push("keydown")), + ); + assert!( + dispatch_key( + &mut page, + root_node, + "PageDown", + "PageDown", + Modifiers::default(), + false + ), + "keydown 未取消 → 默认滚动执行" + ); + assert_eq!(*hits.borrow(), ["wheel"], "wheel 监听器不收 keydown"); + } + + /// chrome 抽象键 → DOM key/code 映射(字符键大写进 code)。 + #[test] + fn dom_key_names_map_characters_and_named_keys() { + let (key, code) = dom_key_names(ui::Key::Character('a')); + assert_eq!((key.as_str(), code.as_str()), ("a", "KeyA")); + let (key, code) = dom_key_names(ui::Key::F5); + assert_eq!((key.as_str(), code.as_str()), ("F5", "F5")); + let (key, _) = dom_key_names(ui::Key::Left); + assert_eq!(key.as_str(), "ArrowLeft"); + } +} diff --git a/crates/nexty-chrome/src/lib.rs b/crates/nexty-chrome/src/lib.rs index bc36425..aba6886 100644 --- a/crates/nexty-chrome/src/lib.rs +++ b/crates/nexty-chrome/src/lib.rs @@ -8,14 +8,16 @@ //! (见 AGENTS.md 硬规则「渲染隔离」)。模块分工: //! //! - [`pipeline`]:HTML 字符串 → 级联 → 布局 → 片段树 → paint 显示列表; -//! - [`resources`]:子资源(外链 CSS + 图片)清单解析、并发抓取与解码编排; +//! - [`resources`]:子资源(外链 CSS + 图片 + @font-face 字体)清单解析、并发抓取与解码编排; //! - [`render`]:渲染隔离线程(panic 兜底,线程存活可继续服务); //! - [`ui`]:自绘工具带状态机(纯逻辑,可测试); //! - [`scrollbar`]:滚动几何与拖拽状态机(纯逻辑,可测试); //! - [`selection`]:页面文本选区状态机(纯逻辑,可测试); //! - [`history`]:会话历史栈(纯逻辑,可测试); -//! - `app`(私有):winit 事件循环 + wgpu 呈现胶水——**无法在无头环境 -//! 自动化测试**,实机运行验证(`cargo run -p nexty-chrome --bin nexty`)。 +//! - `app`(私有):winit 事件循环 + wgpu 呈现胶水——winit/GPU 部分无法 +//! 在无头环境自动化测试,实机运行验证(`cargo run -p nexty-chrome --bin +//! nexty`);交互事件接线与生命周期派发在 `app::events` 子模块(纯函数 +//! 部分有单测,K1 T3)。 //! //! 上游类型一律不得出现在本 crate 的 pub 导出中(AGENTS.md 硬规则)。 //! diff --git a/crates/nexty-chrome/src/pipeline.rs b/crates/nexty-chrome/src/pipeline.rs index 122ba05..35049a3 100644 --- a/crates/nexty-chrome/src/pipeline.rs +++ b/crates/nexty-chrome/src/pipeline.rs @@ -2,21 +2,38 @@ //! //! 行为分工:解析归 nexty-html,级联归 nexty-css(UA + author 双 origin), //! 布局归 nexty-layout,本模块负责把片段树转译为 [`nexty_paint::Scene`]: -//! 背景与 CSS 边框(四条填充带,宽 0 的边跳过)、行内文本 run +//! 背景与渐变(css-images-3 渐变线端点在 emit 前换算)、CSS 边框(四边等宽 +//! 有圆角时一条圆角描边,否则四条填充带)、行内文本 run 与装饰带 //! (坐标换算到绝对坐标系)、行内/块级图片(`DrawImage`,像素从页面图片池 -//! 按节点索引)。匿名片段不产生背景与边框。 +//! 按节点索引)。匿名片段不产生背景与边框;背景绘制次序遵循 +//! z-index 基础定序(普通流先、定位元素后,定位兄弟按整数排序)。 //! -//! 已知偏差:``/`` 背景不向画布传播(画布保持透明,由呈现层 -//! 决定底色);片段树不做滚动裁剪。 +//! 画布底色(CSS 2.2 §14.2):html/body 背景传播到画布——html 携带背景 +//! 用 html,否则用 body,都无回落白([`canvas_background_commands`]); +//! 传播是搬移语义,被传播的元素不再自绘背景。 +//! +//! 已知偏差:z-index 为基础定序档,不做完整 stacking context——定位元素 +//! 统一画在普通流之上(负 z-index 不回落普通流之下),命中测试也不镜像 +//! 定位层序(K7 补);border-radius 百分比按边框盒对应轴折算后取两轴 +//! 较小分量(paint 只有圆形角,椭圆 `/` 语法 css 层已整条拒收);四边 +//! border-width 不等时圆角边框降级直角填充带;text-decoration 按文本 run +//! 自身元素的 computed style 绘制(规范的祖先「传播」未实现,css 层偏差; +//! 跨行内元素边界按 run 分段断线)、非 solid 不画、度量用经验值 +//! (0.06em 厚 / underline 基线下 0.08em,无字体 underline 数据); +//! 片段树不做滚动裁剪。 use std::collections::HashMap; use std::sync::Arc; -use nexty_css::{ComputedStyle, MediaViewport, Rgba, Stylesheet, html_ua_stylesheet}; -use nexty_dom::{Document, NodeId}; +use nexty_css::{ + BackgroundImageValue, BorderRadiusValue, ComputedStyle, GradientColorStop, MediaViewport, + PositionValue, Rgba, Stylesheet, TextDecorationLineValue, TextDecorationStyleValue, + ZIndexValue, html_ua_stylesheet, +}; +use nexty_dom::{Document, Event, EventLoop, NodeId, Task, TaskContext}; use nexty_html::ParseOptions; -use nexty_layout::{Fragment, Rect as LayoutRect}; -use nexty_paint::{Color, Command, Image, Rect as PaintRect, Scene, Size, TextGlyph}; +use nexty_layout::{Fragment, Rect as LayoutRect, TextRun}; +use nexty_paint::{Color, Command, GradientStop, Image, Rect as PaintRect, Scene, Size, TextGlyph}; use nexty_text::TextShaper; /// 一个已解析、已级联的页面。 @@ -87,6 +104,57 @@ pub fn load_page(html: &str, author_css: &str) -> Page { build_page(document, vec![sheet], HashMap::new()) } +/// 页面待派发的生命周期事件信号集(K1 T3)。 +/// +/// 信号在后台线程于真实完成点捕获(HTML 解析返回 / 首轮子资源编排 +/// settle——含失败/超时/预算降级路径),随页面载荷送回主线程;主线程经 +/// [`Page::post_lifecycle_tasks`] post 进 EventLoop 再排空派发。后台线程 +/// 只投信号,不得跨线程触碰 [`Document`]。 +#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)] +pub struct PendingLifecycle { + /// HTML 解析完成 → `DOMContentLoaded`(bubbles=true、cancelable=false, + /// 文档根上派发)。 + pub dom_content_loaded: bool, + /// 首轮子资源编排 settle(含失败/超时/预算降级)→ `load`(bubbles=false)。 + pub load: bool, +} + +impl PendingLifecycle { + /// 两个信号都未到。 + #[must_use] + pub fn is_empty(&self) -> bool { + !self.dom_content_loaded && !self.load + } +} + +impl Page { + /// 导航/解析完成点的**单处** EventLoop 钩子(K1 T3):把信号了的生命 + /// 周期事件按 `DOMContentLoaded` → `load` 顺序 post 进 EventLoop + /// (FIFO 保序);任务执行时在文档根上派发(根无祖先链 → 仅 target + /// 阶段,恰好一次)。 + /// + /// 本方法不存状态:同一信号重复 post 会重复派发——每页只 post 一次 + /// 由调用方(页面安装点)保证。 + pub fn post_lifecycle_tasks(&mut self, event_loop: &mut EventLoop, pending: PendingLifecycle) { + if pending.dom_content_loaded { + event_loop.post_task(Task::new(|ctx: &mut TaskContext| { + let document = ctx.document(); + let root = document.root(); + let mut event = Event::dom_content_loaded(); + document.dispatch(root, &mut event); + })); + } + if pending.load { + event_loop.post_task(Task::new(|ctx: &mut TaskContext| { + let document = ctx.document(); + let root = document.root(); + let mut event = Event::load(); + document.dispatch(root, &mut event); + })); + } + } +} + /// 对页面做布局,返回根元素片段。 #[must_use] pub fn layout_page(page: &Page, shaper: &dyn TextShaper, viewport_width: f32) -> Option { @@ -143,6 +211,9 @@ pub fn build_scene_at_with_highlights( ) -> Scene { let mut scene = Scene::default(); let mut pool: HashMap = HashMap::new(); + // §14.2 传播源(html 优先、body 回落):emit 内被传播的元素不再自绘 + // 背景(搬移语义);全树只查一次,递归透传。 + let canvas_source = canvas_background_source(page); // 高亮矩形相对根片段;先平移到场景坐标,递归 emit 里不再叠加 origin //(emit 的 origin 是父链累积位置,不是场景原点)。 let highlights: Vec = highlights @@ -161,10 +232,22 @@ pub fn build_scene_at_with_highlights( &mut scene, &mut pool, &highlights, + canvas_source, ); scene } +/// 文本装饰带的经验度量(em 单位;无字体 underline 度量可用——T0 报告 +/// F11,记偏差):厚度一律 `0.06em`;underline 带顶在基线下 `0.08em`; +/// overline 近似 em 盒顶(基线上方 `0.88em` ≈ 0.8em ascent + 0.08em); +/// line-through 穿过 x 高中部近似(基线上方 `0.30em`)。 +const DECORATION_THICKNESS_EM: f32 = 0.06; +const UNDERLINE_OFFSET_EM: f32 = 0.08; +const OVERLINE_OFFSET_EM: f32 = 0.88; +const LINE_THROUGH_OFFSET_EM: f32 = 0.30; + +/// 递归 emit 的固定形态参数较多;八参均在用,重签名不值当(针对性抑制)。 +#[allow(clippy::too_many_arguments)] fn emit( page: &Page, fragment: &Fragment, @@ -173,61 +256,114 @@ fn emit( scene: &mut Scene, pool: &mut HashMap, highlights: &[LayoutRect], + canvas_source: Option, ) { let x = origin_x + fragment.border_box.x; let y = origin_y + fragment.border_box.y; let width = fragment.border_box.width; let height = fragment.border_box.height; let style = &fragment.style; + // 四角圆角解析为 px(CSS Backgrounds §5.5;全 0 保持直角旧路径) + let radii = resolve_corner_radii(style, width, height); + let rounded = radii != [0.0; 4]; + // §14.2 传播是搬移:被传播的元素不再自绘背景(颜色与渐变) + let background_propagated = !fragment.anonymous && Some(fragment.node) == canvas_source; if !fragment.anonymous { - // 背景(透明跳过) - if style.background_color.a > 0 { - scene.commands.push(Command::FillRect { + // 背景色(透明跳过;有圆角走 FillRoundedRect,全 0 保持 FillRect) + if style.background_color.a > 0 && !background_propagated { + let rect = PaintRect { + x, + y, + width, + height, + }; + let color = to_color(style.background_color); + if rounded { + scene + .commands + .push(Command::FillRoundedRect { rect, radii, color }); + } else { + scene.commands.push(Command::FillRect { rect, color }); + } + } + // 渐变背景(CSS Images §3.4,画在背景色之上):渐变线端点按 + // css-images-3 公式在 emit 前换算,radii 随 border_radius——单条 + // 指令完成渐变 × 圆角。 + if !background_propagated + && let BackgroundImageValue::LinearGradient(gradient) = &style.background_image + { + let (start, end) = linear_gradient_endpoints(gradient.angle, x, y, width, height); + let stops = gradient_stops(&gradient.stops); + if !stops.is_empty() { + scene.commands.push(Command::FillGradient { + rect: PaintRect { + x, + y, + width, + height, + }, + radii, + start, + end, + stops, + }); + } + } + // CSS 边框:画在边框盒内侧。四边宽度相等且有圆角 → 一条圆角描边 + //(facade 内缩 `width/2`,带恰落在 [0, width],颜色取 top——四边 + // 异色记偏差);否则四条填充带精确表达(宽 0 跳过;宽不等时圆角 + // 降级直角——偏差)。 + let border = fragment.border; + let colors = &style.border_color; + let uniform_border = + border.top == border.bottom && border.left == border.right && border.top == border.left; + if border.top > 0.0 && rounded && uniform_border { + scene.commands.push(Command::StrokeRoundedRect { rect: PaintRect { x, y, width, height, }, - color: to_color(style.background_color), + radii, + color: to_color(colors.top), + width: border.top, }); - } - // CSS 边框:画在边框盒内侧,用四条填充带精确表达(宽 0 跳过) - let border = fragment.border; - let colors = &style.border_color; - if border.top > 0.0 { - push_strip(scene, x, y, width, border.top, colors.top); - } - if border.bottom > 0.0 { - push_strip( - scene, - x, - y + height - border.bottom, - width, - border.bottom, - colors.bottom, - ); - } - if border.left > 0.0 { - push_strip( - scene, - x, - y + border.top, - border.left, - height - border.top - border.bottom, - colors.left, - ); - } - if border.right > 0.0 { - push_strip( - scene, - x + width - border.right, - y + border.top, - border.right, - height - border.top - border.bottom, - colors.right, - ); + } else { + if border.top > 0.0 { + push_strip(scene, x, y, width, border.top, colors.top); + } + if border.bottom > 0.0 { + push_strip( + scene, + x, + y + height - border.bottom, + width, + border.bottom, + colors.bottom, + ); + } + if border.left > 0.0 { + push_strip( + scene, + x, + y + border.top, + border.left, + height - border.top - border.bottom, + colors.left, + ); + } + if border.right > 0.0 { + push_strip( + scene, + x + width - border.right, + y + border.top, + border.right, + height - border.top - border.bottom, + colors.right, + ); + } } } @@ -293,6 +429,10 @@ fn emit( if run.glyphs.is_empty() { continue; } + // 文本装饰带(CSS Text Decor 3):按 run 自身元素的 computed + // style(装饰不继承、规范的祖先「传播」未实现——css 层偏差; + // 跨行内元素边界按 run 分段断线),垫在本 run 文字之下。 + push_text_decoration(page, run, content_x, baseline, scene); scene.commands.push(Command::DrawText { glyphs: run .glyphs @@ -326,16 +466,321 @@ fn emit( ); } // 行内原子盒(inline-block 等):完整子片段树,x/y 已相对行顶定位, - // 按子片段递归(原点 = 本行顶) - for atomic in &line.boxes { - emit(page, atomic, content_x, line_y, scene, pool, highlights); + // 按子片段递归(原点 = 本行顶);定位原子盒后画并按 z-index 排序 + //(基础定序,同块级子盒)。 + let (normal_atomic, positioned_atomic) = split_positioned(&line.boxes); + for atomic in normal_atomic { + emit( + page, + atomic, + content_x, + line_y, + scene, + pool, + highlights, + canvas_source, + ); + } + for atomic in positioned_atomic { + emit( + page, + atomic, + content_x, + line_y, + scene, + pool, + highlights, + canvas_source, + ); } line_offset += line.height; } - for child in &fragment.children { - emit(page, child, content_x, content_y, scene, pool, highlights); + // z-index 基础定序(CSS Position 3 §5 简化档):普通流子片段先按文档 + // 序 emit,定位子片段(position ≠ static)后按 z-index 整数升序 emit + //(auto 视作 0、相等保持文档序;完整 stacking context 留 K7)。 + let (normal, positioned) = split_positioned(&fragment.children); + for child in normal { + emit( + page, + child, + content_x, + content_y, + scene, + pool, + highlights, + canvas_source, + ); } + for child in positioned { + emit( + page, + child, + content_x, + content_y, + scene, + pool, + highlights, + canvas_source, + ); + } +} + +/// 把子片段分拣为(普通流,定位):普通流保持文档序;定位元素(position +/// ≠ static)按 `z-index` 整数升序**稳定**排序(auto 视作 0,相等保持 +/// 文档序)。 +fn split_positioned(children: &[Fragment]) -> (Vec<&Fragment>, Vec<&Fragment>) { + let mut normal = Vec::new(); + let mut positioned: Vec<(&Fragment, i32)> = Vec::new(); + for child in children { + if child.style.position == PositionValue::Static { + normal.push(child); + } else { + positioned.push((child, z_index_key(&child.style))); + } + } + positioned.sort_by_key(|&(_, z)| z); + let positioned = positioned + .into_iter() + .map(|(fragment, _)| fragment) + .collect(); + (normal, positioned) +} + +/// `z-index` 的定序键:`auto` 与 `0` 同序(基础定序档,无 stacking context)。 +fn z_index_key(style: &ComputedStyle) -> i32 { + match style.z_index { + ZIndexValue::Auto => 0, + ZIndexValue::Integer(z) => z, + } +} + +/// 为一个文本 run 下发装饰带(`FillRect`,垫在文字下)。 +/// +/// 装饰属性取 run 自身元素的 computed style:非 solid 不画(偏差);颜色 +/// 透明不画;带顶相对基线按 [`UNDERLINE_OFFSET_EM`] 等经验度量;带 x 范围 +/// 为该 run 字形的实际横向覆盖(与命中测试同一口径)。度量为经验值、无 +/// 字体 underline 数据(T0 报告 F11,记偏差)。 +fn push_text_decoration( + page: &Page, + run: &TextRun, + content_x: f32, + baseline: f32, + scene: &mut Scene, +) { + let Some(style) = page.styles.get(&run.node) else { + return; + }; + if style.text_decoration_style != TextDecorationStyleValue::Solid { + return; + } + let offset_em = match style.text_decoration_line { + TextDecorationLineValue::None => return, + TextDecorationLineValue::Underline => UNDERLINE_OFFSET_EM, + TextDecorationLineValue::Overline => -OVERLINE_OFFSET_EM, + TextDecorationLineValue::LineThrough => -LINE_THROUGH_OFFSET_EM, + }; + if style.text_decoration_color.a == 0 { + return; + } + let size = run.style.size; + let thickness = size * DECORATION_THICKNESS_EM; + if !(thickness.is_finite() && thickness > 0.0) { + return; + } + let Some(first) = run.glyphs.first() else { + return; + }; + let Some(last) = run.glyphs.last() else { + return; + }; + let start = content_x + first.x; + let width = (last.x + last.advance) - first.x; + if !(width.is_finite() && width > 0.0) { + return; + } + scene.commands.push(Command::FillRect { + rect: PaintRect { + x: start, + y: baseline + size * offset_em, + width, + height: thickness, + }, + color: to_color(style.text_decoration_color), + }); +} + +/// 把 computed 的四角圆角解析为 px 半径 `[左上, 右上, 右下, 左下]`。 +/// +/// - `Length(px)` 直取;`Percent` 按边框盒对应轴折算(水平÷宽、垂直÷高)后 +/// 取两轴**较小**分量——paint 只有圆形角,取较小分量保证角不出盒 +/// (50% 在任意盒上退化为药丸半高;椭圆角记偏差); +/// - `Viewport` 仅在调用方未以视口 recascade 时残留,按 0 降级(直角); +/// - 负值与非有限按 0 处理(渲染为直角,与 paint 层防御一致)。 +fn resolve_corner_radii(style: &ComputedStyle, width: f32, height: f32) -> [f32; 4] { + fn one(value: BorderRadiusValue, width: f32, height: f32) -> f32 { + let radius = match value { + BorderRadiusValue::Length(px) => px, + BorderRadiusValue::Percent(p) => (p * width).min(p * height), + BorderRadiusValue::Viewport(..) => 0.0, + }; + if radius.is_finite() && radius > 0.0 { + radius + } else { + 0.0 + } + } + let corners = &style.border_radius; + [ + one(corners.top_left, width, height), + one(corners.top_right, width, height), + one(corners.bottom_right, width, height), + one(corners.bottom_left, width, height), + ] +} + +/// css-images-3 线性渐变线端点:角度自北顺时针(0 = to top),渐变线过盒 +/// 中心、长度 `|W·sinα| + |H·cosα|`(CSS Images 3 §3.3.4 图式),两端关于 +/// 中心对称。返回 `(start, end)` 场景坐标;`angle_deg` 非有限按 180 +///(to bottom)降级。 +fn linear_gradient_endpoints( + angle_deg: f32, + x: f32, + y: f32, + width: f32, + height: f32, +) -> ([f32; 2], [f32; 2]) { + let angle = if angle_deg.is_finite() { + angle_deg + } else { + 180.0 + }; + let center_x = x + width / 2.0; + let center_y = y + height / 2.0; + // 渐变方向单位向量:0° 向上(y 轴向下为正的屏幕坐标系)。四正向 + // (rem_euclid 后恰为 0/90/180/270)走精确轴向量与精确线长——f32 + // 三角函数在 90° 带 ~4e-6 噪声,最常用方向的渐变线必须严格水平 + // /垂直,端点才确定。 + let (dx, dy, length) = match angle.rem_euclid(360.0) { + 0.0 => (0.0, -1.0, height.abs()), + 90.0 => (1.0, 0.0, width.abs()), + 180.0 => (0.0, 1.0, height.abs()), + 270.0 => (-1.0, 0.0, width.abs()), + _ => { + let alpha = angle.to_radians(); + let (sin, cos) = alpha.sin_cos(); + (sin, -cos, (width * sin).abs() + (height * cos).abs()) + } + }; + ( + [center_x - dx * length / 2.0, center_y - dy * length / 2.0], + [center_x + dx * length / 2.0, center_y + dy * length / 2.0], + ) +} + +/// css 色标 → paint 色标(offset 透传,颜色经非预乘 RGBA 转换)。 +fn gradient_stops(stops: &[GradientColorStop]) -> Vec { + stops + .iter() + .map(|stop| GradientStop { + offset: stop.position, + color: to_color(stop.color), + }) + .collect() +} + +/// 元素是否携带可见背景(颜色不透明度 > 0 或渐变)——§14.2 传播判定用。 +fn has_background(style: &ComputedStyle) -> bool { + style.background_color.a > 0 + || matches!( + style.background_image, + BackgroundImageValue::LinearGradient(_) + ) +} + +/// 按 HTML 命名空间的标签名找文档中首个元素(html5ever 强制存在 html/body)。 +fn find_html_element(page: &Page, name: &str) -> Option { + use nexty_dom::{Namespace, NodeKind}; + fn walk(page: &Page, node: NodeId, name: &str) -> Option { + if let Some(NodeKind::Element(data)) = page.document.node(node) + && data.namespace == Namespace::Html + && data.name == name + { + return Some(node); + } + page.document + .children(node) + .find_map(|child| walk(page, child, name)) + } + walk(page, page.document.root(), name) +} + +/// CSS 2.2 §14.2 的画布背景传播源:html 携带背景用 html,否则 body, +/// 都无返回 `None`(画布回落白)。 +#[must_use] +pub fn canvas_background_source(page: &Page) -> Option { + if let Some(html) = find_html_element(page, "html") + && page.styles.get(&html).is_some_and(has_background) + { + return Some(html); + } + if let Some(body) = find_html_element(page, "body") + && page.styles.get(&body).is_some_and(has_background) + { + return Some(body); + } + None +} + +/// 画布底色指令(CSS 2.2 §14.2 背景传播),供呈现层插到场景**底部**。 +/// +/// - html/body 均无背景 → 一条白色 `FillRect`(画布必须不透明:透明像素 +/// 直接 blit 给 surface 在部分后端表现为黑屏/花屏); +/// - 传播源只有纯色 → 一条该色 `FillRect`; +/// - 传播源带渐变 → 先垫一条底色(传播色不透明时用它,否则白——保证 +/// 渐变透明色标不露出未初始化画布),再一条铺满视口的 `FillGradient` +/// (渐变线按**视口矩形**解析:传播到画布的背景按画布尺寸取值)。 +/// +/// 被传播元素的自身背景由 emit 抑制(搬移语义,见 [`emit`])。 +#[must_use] +pub fn canvas_background_commands( + page: &Page, + viewport_width: f32, + viewport_height: f32, +) -> Vec { + let rect = PaintRect { + x: 0.0, + y: 0.0, + width: viewport_width, + height: viewport_height, + }; + let white = Color::opaque(0xff, 0xff, 0xff); + let Some(source) = canvas_background_source(page) else { + return vec![Command::FillRect { rect, color: white }]; + }; + // 传播源必有 computed style(级联覆盖全部元素) + let style = &page.styles[&source]; + let base = if style.background_color.a > 0 { + to_color(style.background_color) + } else { + white + }; + let mut commands = vec![Command::FillRect { rect, color: base }]; + if let BackgroundImageValue::LinearGradient(gradient) = &style.background_image { + let (start, end) = + linear_gradient_endpoints(gradient.angle, 0.0, 0.0, viewport_width, viewport_height); + let stops = gradient_stops(&gradient.stops); + if !stops.is_empty() { + commands.push(Command::FillGradient { + rect, + radii: [0.0; 4], + start, + end, + stops, + }); + } + } + commands } /// `node` 是否为 HTML 命名空间的 ``(块级替换路径的判定)。 @@ -797,4 +1242,455 @@ mod tests { coalescer.on_resized(); assert!(coalescer.take()); } + + // ---- K2 T3:圆角 / 渐变 / 装饰带 / z-index / 背景传播 ---- + + use nexty_css::{Corners, ViewportUnit}; + + /// 渐变线端点:css-images-3 公式 `|W·sinα| + |H·cosα|`,四正向端点 + /// 方向、对角 45° 线长与非有限角度降级。 + #[test] + fn linear_gradient_endpoints_follow_css_images_formula() { + // 0°(to top):线长 = H,起点在下、终点在上 + let (start, end) = linear_gradient_endpoints(0.0, 10.0, 20.0, 100.0, 50.0); + assert_eq!(start, [60.0, 70.0]); + assert_eq!(end, [60.0, 20.0]); + // 90°(to right):线长 = W,起点在左、终点在右 + let (start, end) = linear_gradient_endpoints(90.0, 10.0, 20.0, 100.0, 50.0); + assert_eq!(start, [10.0, 45.0]); + assert_eq!(end, [110.0, 45.0]); + // 180°(to bottom,缺省角):起点在上、终点在下 + let (start, end) = linear_gradient_endpoints(180.0, 10.0, 20.0, 100.0, 50.0); + assert_eq!(start, [60.0, 20.0]); + assert_eq!(end, [60.0, 70.0]); + // 270°(to left):起点在右、终点在左 + let (start, end) = linear_gradient_endpoints(270.0, 10.0, 20.0, 100.0, 50.0); + assert_eq!(start, [110.0, 45.0]); + assert_eq!(end, [10.0, 45.0]); + // 45°:L = W·sin45 + H·cos45;方形盒端点落在对角上 + let (start, end) = linear_gradient_endpoints(45.0, 0.0, 0.0, 100.0, 100.0); + assert!((start[0] - 0.0).abs() < 1e-4 && (start[1] - 100.0).abs() < 1e-4); + assert!((end[0] - 100.0).abs() < 1e-4 && (end[1] - 0.0).abs() < 1e-4); + // 非有限角度降级 180(to bottom) + let (start, end) = linear_gradient_endpoints(f32::NAN, 0.0, 0.0, 100.0, 50.0); + assert_eq!(start, [50.0, 0.0]); + assert_eq!(end, [50.0, 50.0]); + } + + /// 圆角解析:Length 直取、Percent 两轴取小、Viewport 残留降级 0、 + /// 负值与非有限钳 0。 + #[test] + fn corner_radii_resolve_length_percent_and_viewport_fallback() { + let mut style = ComputedStyle::initial(); + style.border_radius = Corners::splat(BorderRadiusValue::Length(10.0)); + assert_eq!(resolve_corner_radii(&style, 800.0, 200.0), [10.0; 4]); + + // 50% @800×200:水平 400、垂直 100 → 取较小分量(药丸半高) + style.border_radius = Corners::splat(BorderRadiusValue::Percent(0.5)); + assert_eq!(resolve_corner_radii(&style, 800.0, 200.0), [100.0; 4]); + + // 视口单位残留(未 recascade)→ 0 降级直角 + style.border_radius = Corners::splat(BorderRadiusValue::Viewport(2.0, ViewportUnit::Vw)); + assert_eq!(resolve_corner_radii(&style, 800.0, 200.0), [0.0; 4]); + + style.border_radius = Corners::splat(BorderRadiusValue::Length(f32::NAN)); + assert_eq!(resolve_corner_radii(&style, 800.0, 200.0), [0.0; 4]); + style.border_radius = Corners::splat(BorderRadiusValue::Length(-5.0)); + assert_eq!(resolve_corner_radii(&style, 800.0, 200.0), [0.0; 4]); + } + + /// 布局一页并构建场景的测试辅助。 + fn scene_of(html: &str) -> Scene { + let page = load_page(html, ""); + let shaper = nexty_text::ParleyTextShaper::new(); + let root = layout_page(&page, &shaper, 400.0).expect("root"); + build_scene(&page, &root) + } + + /// 渐变背景发 FillGradient:to right 端点从左到右、色标映射正确、 + /// 渐变线过盒中心。 + #[test] + fn gradient_background_emits_fill_gradient_with_stops() { + let scene = scene_of( + "
", + ); + let gradients: Vec<_> = scene + .commands + .iter() + .filter_map(|command| match command { + Command::FillGradient { + rect, + start, + end, + stops, + .. + } => Some((*rect, *start, *end, stops.clone())), + _ => None, + }) + .collect(); + assert_eq!(gradients.len(), 1, "恰一条 FillGradient"); + let (rect, start, end, stops) = &gradients[0]; + assert!(start[0] < end[0], "to right 起点在左终点在右"); + assert_eq!(start[1], end[1], "to right 渐变线水平"); + assert_eq!(stops.len(), 2); + assert_eq!(stops[0].offset, 0.0); + assert_eq!(stops[0].color, Color::opaque(255, 0, 0)); + assert_eq!(stops[1].offset, 1.0); + assert_eq!(stops[1].color, Color::opaque(0, 0, 255)); + let center_x = rect.x + rect.width / 2.0; + assert_eq!((start[0] + end[0]) / 2.0, center_x, "渐变线过盒中心"); + } + + /// 渐变 × 圆角单指令:radii 随 border_radius,不另发圆角纯色背景。 + #[test] + fn gradient_with_radius_is_single_command() { + let scene = scene_of( + "
", + ); + assert!( + !scene + .commands + .iter() + .any(|command| matches!(command, Command::FillRoundedRect { .. })), + "背景色透明时不发纯色圆角指令" + ); + let gradients: Vec<_> = scene + .commands + .iter() + .filter_map(|command| match command { + Command::FillGradient { radii, .. } => Some(*radii), + _ => None, + }) + .collect(); + assert_eq!(gradients, vec![[12.0; 4]], "渐变 radii 随 border_radius"); + } + + /// 有圆角背景走 FillRoundedRect;全 0 半径保持 FillRect 旧路径。 + #[test] + fn rounded_background_uses_fill_rounded_rect_zero_radius_keeps_fill_rect() { + let scene = scene_of( + "\ +
\ +
\ + ", + ); + let rounded: Vec<_> = scene + .commands + .iter() + .filter_map(|command| match command { + Command::FillRoundedRect { radii, color, .. } => Some((*radii, *color)), + _ => None, + }) + .collect(); + assert_eq!(rounded, vec![([10.0; 4], Color::opaque(255, 0, 0))]); + assert!( + scene.commands.iter().any(|command| matches!( + command, + Command::FillRect { color, .. } if *color == Color::opaque(0, 0, 255) + )), + "无圆角 div 保持 FillRect 旧路径" + ); + } + + /// 四边等宽 + 圆角 → 一条圆角描边;宽不等维持四条填充带(直角降级)。 + #[test] + fn uniform_borders_use_stroke_rounded_rect_unequal_keep_strips() { + let scene = scene_of( + "\ +
\ +
\ + ", + ); + let strokes: Vec<_> = scene + .commands + .iter() + .filter_map(|command| match command { + Command::StrokeRoundedRect { radii, width, .. } => Some((*radii, *width)), + _ => None, + }) + .collect(); + assert_eq!(strokes, vec![([8.0; 4], 4.0)], "等宽圆角边框一条描边"); + let black_strips = scene + .commands + .iter() + .filter(|command| { + matches!( + command, + Command::FillRect { color, .. } if *color == Color::opaque(0, 0, 0) + ) + }) + .count(); + assert_eq!(black_strips, 4, "宽不等时四条直角填充带"); + } + + /// 场景中某色首个 `FillRect` 的下标。 + fn fill_index(scene: &Scene, color: Color) -> Option { + scene.commands.iter().position( + |command| matches!(command, Command::FillRect { color: c, .. } if *c == color), + ) + } + + /// z-index 基础定序:定位元素画在普通流之后、定位兄弟按整数升序。 + #[test] + fn z_index_orders_positioned_after_static_sorted_by_integer() { + let scene = scene_of( + "\ +
\ +
\ +
\ +
\ +
\ + ", + ); + let red = fill_index(&scene, Color::opaque(255, 0, 0)).expect("普通流红"); + let white = fill_index(&scene, Color::opaque(255, 255, 255)).expect("普通流白"); + let green = fill_index(&scene, Color::opaque(0, 128, 0)).expect("z=2 绿"); + let blue = fill_index(&scene, Color::opaque(0, 0, 255)).expect("z=1 蓝"); + let yellow = fill_index(&scene, Color::opaque(255, 255, 0)).expect("z=-1 黄"); + assert!(red < yellow && white < yellow, "定位元素画在普通流之后"); + assert!(yellow < blue && blue < green, "定位兄弟按 z-index 升序"); + } + + /// 选区高亮插入次序回归:高亮在背景之上、文字之下。 + #[test] + fn selection_highlight_stays_between_background_and_text() { + let page = load_page( + "

hello

", + "", + ); + let shaper = nexty_text::ParleyTextShaper::new(); + let root = layout_page(&page, &shaper, 400.0).expect("root"); + let highlights = [LayoutRect { + x: 0.0, + y: 0.0, + width: 400.0, + height: 300.0, + }]; + let scene = build_scene_at_with_highlights(&page, &root, 0.0, 0.0, &highlights); + let background = fill_index(&scene, Color::opaque(0, 0, 255)).expect("div 背景"); + let highlight = scene + .commands + .iter() + .position(|command| matches!(command, Command::FillRect { color, .. } if *color == SELECTION_COLOR)) + .expect("选区高亮"); + let text = scene + .commands + .iter() + .position(|command| matches!(command, Command::DrawText { .. })) + .expect("文本命令"); + assert!(background < highlight, "高亮在背景之上"); + assert!(highlight < text, "高亮在文字之下"); + } + + /// 画布背景传播源:html 优先、body 回落、都无回落白。 + #[test] + fn canvas_background_prefers_html_then_body_falls_back_to_white() { + let page = load_page( + "", + "", + ); + let canvas = canvas_background_commands(&page, 400.0, 300.0); + assert!( + matches!( + &canvas[..], + [Command::FillRect { color, .. }] if *color == Color::opaque(0, 0, 255) + ), + "html 背景优先传播" + ); + + let page = load_page("", ""); + let canvas = canvas_background_commands(&page, 400.0, 300.0); + assert!( + matches!( + &canvas[..], + [Command::FillRect { color, .. }] if *color == Color::opaque(0, 128, 0) + ), + "html 无背景时 body 回落" + ); + + let page = load_page("", ""); + let canvas = canvas_background_commands(&page, 400.0, 300.0); + assert!( + matches!( + &canvas[..], + [Command::FillRect { color, .. }] if *color == Color::opaque(255, 255, 255) + ), + "都无背景回落白" + ); + } + + /// 渐变背景传播:垫底色 + 铺满视口的 FillGradient(渐变线按视口矩形)。 + #[test] + fn canvas_gradient_propagates_as_viewport_fill_gradient() { + let page = load_page( + "", + "", + ); + let canvas = canvas_background_commands(&page, 400.0, 300.0); + assert_eq!(canvas.len(), 2, "垫底色 + 渐变两条指令"); + assert!( + matches!( + &canvas[0], + Command::FillRect { color, .. } if *color == Color::opaque(255, 255, 255) + ), + "传播色透明时垫白" + ); + let Command::FillGradient { + rect, + start, + end, + stops, + .. + } = &canvas[1] + else { + panic!("第二条应是渐变"); + }; + assert_eq!(rect.width, 400.0); + assert_eq!(rect.height, 300.0); + assert!(start[0] < end[0]); + assert_eq!(stops.len(), 2); + } + + /// 传播是搬移:body 背景被传播后场景中不再自绘;html 携带背景时 + /// body 背景不被传播、仍自绘。 + #[test] + fn propagated_background_is_suppressed_on_fragment() { + let page = load_page( + "

x

", + "", + ); + let shaper = nexty_text::ParleyTextShaper::new(); + let root = layout_page(&page, &shaper, 400.0).expect("root"); + let scene = build_scene(&page, &root); + assert!( + scene.commands.iter().all(|command| !matches!( + command, + Command::FillRect { color, .. } if *color == Color::opaque(0, 128, 0) + )), + "被传播的 body 背景不再自绘" + ); + + let page = load_page( + "

x

", + "", + ); + let root = layout_page(&page, &shaper, 400.0).expect("root"); + let scene = build_scene(&page, &root); + assert!( + scene.commands.iter().any(|command| matches!( + command, + Command::FillRect { color, .. } if *color == Color::opaque(0, 128, 0) + )), + "body 背景未被传播时仍自绘" + ); + assert!( + scene.commands.iter().all(|command| !matches!( + command, + Command::FillRect { color, .. } if *color == Color::opaque(0, 0, 255) + )), + "html 背景被传播后不再自绘" + ); + } + + /// 场景中某色首个非黑装饰带(带高 = 0.06em)的下标与几何。 + fn decoration_band(scene: &Scene) -> Option { + scene.commands.iter().find_map(|command| match command { + Command::FillRect { rect, color } + if *color == Color::opaque(0, 0, 0) && (rect.height - 0.96).abs() < 1e-3 => + { + Some(*rect) + } + _ => None, + }) + } + + /// 装饰带几何:厚度 0.06em、underline 带顶 = 基线 + 0.08em、x 覆盖 + /// run 字形横向范围;overline / line-through 按经验偏移。 + #[test] + fn decoration_band_geometry_follows_run_baseline() { + let scene = scene_of( + "

hello

", + ); + let band = decoration_band(&scene).expect("underline 装饰带"); + assert!( + (band.height - 16.0 * 0.06).abs() < 1e-3, + "厚度 0.06em @16px" + ); + let baseline = scene + .commands + .iter() + .find_map(|command| match command { + Command::DrawText { baseline, .. } => Some(*baseline), + _ => None, + }) + .expect("文本命令"); + assert!( + (band.y - (baseline + 16.0 * 0.08)).abs() < 1e-3, + "带顶 = 基线 + 0.08em" + ); + // 装饰带垫在文字下:带下标早于本 run 的 DrawText + let band_index = scene + .commands + .iter() + .position(|command| matches!(command, Command::FillRect { rect, .. } if *rect == band)) + .expect("带下标"); + let text_index = scene + .commands + .iter() + .position(|command| matches!(command, Command::DrawText { .. })) + .expect("文本下标"); + assert!(band_index < text_index, "装饰带垫在文字下"); + + for (decoration, offset_em) in [("overline", -0.88), ("line-through", -0.30)] { + let scene = scene_of(&format!( + "

hello

" + )); + let band = decoration_band(&scene).unwrap_or_else(|| panic!("{decoration} 装饰带")); + let baseline = scene + .commands + .iter() + .find_map(|command| match command { + Command::DrawText { baseline, .. } => Some(*baseline), + _ => None, + }) + .expect("文本命令"); + assert!( + (band.y - (baseline + 16.0 * offset_em)).abs() < 1e-3, + "{decoration} 带顶 = 基线 {offset_em}em" + ); + } + } + + /// 非 solid(wavy)与透明装饰色不画(渲染仅 solid——偏差)。 + #[test] + fn decoration_skipped_for_non_solid_and_transparent() { + let scene = scene_of( + "

hello

", + ); + assert!(decoration_band(&scene).is_none(), "wavy 不按 solid 画"); + let scene = scene_of( + "

hello

", + ); + assert!(decoration_band(&scene).is_none(), "透明装饰色不画"); + } + + /// M6 回归(新指令):缓存场景经 `translated` 与直接以该 origin 构建 + /// 的场景逐字节一致(渐变端点 / 圆角 / 装饰带全部随平移)。 + #[test] + fn translated_matches_direct_build_with_new_commands() { + let page = load_page( + "\ +
\ +

hello

\ +
", + "", + ); + let shaper = nexty_text::ParleyTextShaper::new(); + let root = layout_page(&page, &shaper, 400.0).expect("root"); + let mut cache = SceneCache::new(); + let page_scene = cache.scene_for(1, &page, &root, 400.0, &[]); + let translated = page_scene.translated(0.0, 48.0); + let direct = build_scene_at_with_highlights(&page, &root, 0.0, 48.0, &[]); + assert_eq!(format!("{translated:?}"), format!("{direct:?}")); + } } diff --git a/crates/nexty-chrome/src/resources.rs b/crates/nexty-chrome/src/resources.rs index 120cb21..efce89c 100644 --- a/crates/nexty-chrome/src/resources.rs +++ b/crates/nexty-chrome/src/resources.rs @@ -1,21 +1,41 @@ -//! 子资源抓取与解码:样式表/图片清单 → URL 解析 → 并发抓取 → 级联输入。 +//! 子资源与主文档抓取编排:清单 → URL 解析 → 并发抓取 → 级联输入。 //! //! 职责边界:解析归 nexty-html(清单收集)、传输归 nexty-network(字节)、 -//! 解码归 nexty-paint(RGBA8)、级联归 nexty-css(多表合并)。本模块只做 -//! 编排:把清单里的相对 URL 解析为绝对地址,并发抓取后按清单顺序交回。 +//! 解码归 nexty-paint(RGBA8)与 nexty-network(文本编码)、级联归 nexty-css +//! (多表合并)。本模块只做编排:把清单里的相对 URL 解析为绝对地址,并发 +//! 抓取后按清单顺序交回;主文档的「抓取 → 解码 → 规划解析 → 子资源编排」 +//! 序列收口在 [`fetch_document`](K3 T5),地址栏输入的 scheme 规范化在 +//! [`normalize_address_bar_input`](决策见 +//! `docs/decisions/2026-10-31-addressbar-url.md`)。 //! //! 降级语义(T5 退出条件):单个子资源失败(URL 非法 / 传输错误 / 非 2xx / //! 解码失败)只跳过该资源,不影响其余渲染——外链 CSS 失败 = 该表不参与级联; //! 图片失败 = 该节点不产生像素(布局回退默认对象尺寸 300×150)。 +//! +//! 字体子资源(K4 T3):`@font-face` 的 `url()` 源按文档 base 解析后由 +//! [`FontOrchestrator`] 编排——收集(主线程,页面装配后)→ [`fetch_fonts`] +//! (后台线程,预算 [`MAX_FONT_BODY_BYTES`])→ 注册进会话级 +//! `nexty_text::FontRegistry`(主线程,字节到达时)。字体不在首轮 settle / +//! load 门控内(CSS Fonts font-display 的 swap 简化,偏差同 nexty-css): +//! 首帧用系统字体照常渲染,字节就绪注册后由调用方触发恰好一轮重排 + 重绘 +//! (注册表已接线的整形器自动生效,无需重建)。 +//! +//! 字体编排偏差:woff/woff2 提示的源跳过抓取(harfrust 不消费该容器格式); +//! 无提示的源乐观抓取,非字体数据由注册期拒收兜底(双重防线);`local()` +//! 源不经抓取(已安装字体的命中交给系统回退,不按 local 名单显式解析); +//! 会话去重按 URL 键控(与既有子资源同一键控语义)——同 URL 注册成功后, +//! 后续导航对同 URL 的不同描述符不再抓取(罕见边角,接受降级);负结果 +//! (404 / 非字体数据)不入会话集,再次导航时重试。 -use std::collections::HashMap; +use std::collections::{HashMap, HashSet}; use std::sync::Arc; -use nexty_css::Stylesheet; +use nexty_css::{FontFaceSource, FontFaceStyle, Stylesheet}; use nexty_dom::{Document, NodeId}; use nexty_html::StyleResource; -use nexty_network::{Method, NetworkError, NetworkFetcher, Request, resolve}; +use nexty_network::{Method, NetworkError, NetworkFetcher, Request, decode_document, resolve}; use nexty_paint::{Image, decode}; +use nexty_text::{FontFaceDescriptor, FontRegistry, FontStyle}; /// 并发抓取的线程上限:清单可能很大(真实页面几十张图),逐资源开线程 /// 会撑爆调度器;分块处理后每块内并发、块间串行。 @@ -32,6 +52,11 @@ pub const MAX_DOCUMENT_BODY_BYTES: usize = 10 * 1024 * 1024; pub const MAX_STYLESHEET_BODY_BYTES: usize = 10 * 1024 * 1024; pub const MAX_IMAGE_BODY_BYTES: usize = 50 * 1024 * 1024; +/// 字体响应体字节预算(K4 T3):单个字体文件(TTF/OTF 静态字体)远小于 +/// 图片压缩体积,20 MB 已远超真实 Web 字体;超预算按既有降级语义跳过该源 +/// (分配失败是 abort,panic 兜底兜不住)。 +pub const MAX_FONT_BODY_BYTES: usize = 20 * 1024 * 1024; + /// 抓取完成的子资源。 pub struct Subresources { /// 作者样式表,按级联优先级排列(inline 与外链按文档出现顺序交错)。 @@ -41,60 +66,242 @@ pub struct Subresources { pub images: HashMap>, } +/// 后台线程抓取产物(K1 T3:全 `Send` 数据面)。 +/// +/// K1 起 `Document` 携带监听器注册表(`Box`,!Send), +/// 只能在主线程构建——后台抓取线程不再产出 `Page`,只产出本结构(HTML + +/// 样式表字节 + 已解码图片,按绝对 URL 键控),随事件代理送回主线程后由 +/// [`assemble_page_data`] 装配。 +pub struct FetchedPageData { + /// 主文档 HTML(已 UTF-8 校验)。 + pub html: String, + /// 外链样式表字节:绝对 URL → 字节。失败/超时/超预算/URL 解析失败的 + /// URL 不在表内(降级语义:该表不参与级联)。 + pub css: HashMap>, + /// 已解码图片:绝对 URL → 像素。同上缺席 = 该图所有节点无像素;同 + /// URL 一份像素,装配期按 `Arc` 共享(M1 零拷贝)。 + pub images: HashMap>, +} + /// 抓取文档的子资源(CSS + 图片)。 /// /// `base_url` 是文档 URL(相对 URL 的解析基准);`about:blank` 等无网络 -/// 内部页直接传空文档清单即可(本函数对空清单返回空结果)。 +/// 内部页直接传空文档清单即可(本函数对空清单返回空结果)。不需 settle +/// 信号时用本便捷封装,等价于 settle 回调为空。 #[must_use] pub fn fetch_subresources( fetcher: &dyn NetworkFetcher, base_url: &str, document: &Document, ) -> Subresources { + fetch_subresources_with_settle(fetcher, base_url, document, &mut || {}) +} + +/// 抓取文档的子资源,并在**首轮编排 settle** 时触发一次 `on_settle`(K1 T3)。 +/// +/// settle = 清单里的全部抓取/解码任务都已出结果——个别资源的失败/超时/ +/// 超预算按降级语义跳过、不阻塞编排,因此无论结果如何回调恰触发一次。 +/// 回调供后台抓取线程投递「子资源就绪」信号(load 生命周期事件的派发 +/// 门控):只做信号记录,不得在回调内触碰 `Document`(跨线程约束—— +/// Document 随页面载荷回主线程后才可派发)。 +#[must_use] +pub fn fetch_subresources_with_settle( + fetcher: &dyn NetworkFetcher, + base_url: &str, + document: &Document, + on_settle: &mut dyn FnMut(), +) -> Subresources { + let (css, images) = fetch_resolved(fetcher, base_url, document, on_settle); + assemble_from_maps(document, base_url, &css, &images) +} + +/// 抓取后台数据面(K1 T3):规划解析清单 → 并发抓取 → 解码,全部产出为 +/// `Send` 数据(无 `Document`/`NodeId`)。 +/// +/// `document` 是调用方在后台线程的规划解析(同一 HTML 稍后由主线程重建 +/// 正式文档);`html` 原样随产物回传。settle 回调语义同 +/// [`fetch_subresources_with_settle`]。 +#[must_use] +pub fn fetch_page_data( + fetcher: &dyn NetworkFetcher, + base_url: &str, + document: &Document, + html: String, + on_settle: &mut dyn FnMut(), +) -> FetchedPageData { + let (css, images) = fetch_resolved(fetcher, base_url, document, on_settle); + FetchedPageData { html, css, images } +} + +/// 主文档抓取编排的产物(K3 T5):[`fetch_document`] 的成功输出,全部为 +/// `Send` 数据面,供后台线程随事件载荷送回主线程装配。 +pub struct FetchedDocument { + /// 页面数据面(HTML + 子资源字节/像素)。 + pub data: FetchedPageData, + /// 文档 base:响应的最终 URL(重定向落点;无重定向即请求 URL—— + /// WHATWG fetch 的 final URL 语义)。子资源相对地址的解析与装配查表 + /// 都按它进行:重定向后相对子资源随落点而非原始请求 URL。 + pub base_url: String, +} + +/// 抓取并编排主文档(导航管线的后台数据面入口,K3 T5)。 +/// +/// 编排序列与降级语义(错误串一律收敛,供错误页按页面语义渲染): +/// - 抓取失败(URL 非法 / 传输 / 超时)→ `Err`,错误串收敛为「错误类别」—— +/// 不回显上游原始错误(reqwest 的错误文本内含目标 URL,防注入); +/// - 非 2xx → `Err("HTTP <状态码>")`; +/// - 响应体超 [`MAX_DOCUMENT_BODY_BYTES`] → `Err`(巨响应的分配失败是 +/// abort,panic 兜底兜不住); +/// - 文本解码按 [`decode_document`] 的四层优先级(HTTP charset > BOM > +/// meta 预扫 > UTF-8),替换语义兜底不失败——非 UTF-8 页面不再进错误页; +/// - 解析与子资源编排见 [`fetch_page_data`](settle 恰触发一次,含失败 / +/// 超时 / 预算降级路径)。 +/// +/// `fetcher` 通常是被 `nexty_network::CachedFetcher` 装饰的共享实例(K3 +/// T4/T5):主文档与子资源同栈,同 URL 二次导航直接命中内存缓存。 +/// +/// # Errors +/// +/// 抓取失败、非 2xx、响应体超预算时返回用户可读的错误类别串。 +pub fn fetch_document(fetcher: &dyn NetworkFetcher, url: &str) -> Result { + let request = Request { + url: url.to_owned(), + method: Method::Get, + // 不少真实站点对无 UA 请求直接 403/429 + headers: vec![( + "User-Agent".to_owned(), + format!("Nexty/{}", env!("CARGO_PKG_VERSION")), + )], + }; + let response = fetcher + .fetch(&request) + .map_err(|error| load_error_text(&error).to_owned())?; + if !(200..300).contains(&response.status) { + return Err(format!("HTTP {}", response.status)); + } + if response.body.len() > MAX_DOCUMENT_BODY_BYTES { + return Err("响应体超出预算".to_owned()); + } + let content_type = content_type_header(&response.headers); + let decoded = decode_document(content_type, &response.body); + let document = nexty_html::parse_document(&decoded.text, nexty_html::ParseOptions::default()); + // 子资源 base = 最终 URL(重定向落点);mock 后端无重定向时即请求 URL + let data = fetch_page_data( + fetcher, + &response.final_url, + &document, + decoded.text, + &mut || {}, + ); + Ok(FetchedDocument { + data, + base_url: response.final_url, + }) +} + +/// 传输失败 → 错误类别文本。 +/// +/// 不回显上游原始错误串:reqwest 的错误文本内含目标 URL,而错误页是按 +/// 页面语义渲染的 HTML——错误信息只保留「类别」这一用户需要知道的内容。 +fn load_error_text(error: &NetworkError) -> &'static str { + match error { + NetworkError::InvalidUrl => "无效的地址", + NetworkError::Timeout => "请求超时", + NetworkError::Transport => "网络错误", + } +} + +/// 取响应头里的 Content-Type 值(头名不区分大小写;reqwest 的头表不保序, +/// 条目完整但顺序与源报文无关)。 +fn content_type_header(headers: &[(String, String)]) -> Option<&str> { + headers + .iter() + .find(|(name, _)| name.eq_ignore_ascii_case("content-type")) + .map(|(_, value)| value.as_str()) +} + +/// 地址栏输入的 URL 规范化(K3 T5 决策,完整记录见 +/// `docs/decisions/2026-10-31-addressbar-url.md`)。 +/// +/// 输入缺 scheme 时补 `http://`(HTTP-first,与主流浏览器地址栏默认一致; +/// 不猜测 `www.` 前缀、不在 http/https 间猜测升级)。scheme 判定按 WHATWG +/// URL 的 scheme 语法前缀匹配(`ALPHA *( ALPHA / DIGIT / "+" / "-" / "." ) +/// ":"`)——带合法 scheme 的输入(`https://…`、`about:blank`、`mailto:…`) +/// 原样返回,各自走到其语义终点。合法性不在这里前置校验:非法输入交给 +/// 抓取路径,由协议白名单判 `InvalidUrl` 进既有错误页(单点错误路径)。 +#[must_use] +pub fn normalize_address_bar_input(input: &str) -> String { + if has_url_scheme(input) { + input.to_owned() + } else { + format!("http://{input}") + } +} + +/// 输入是否以 WHATWG URL 的 scheme 前缀开头 +/// (`ALPHA *( ALPHA / DIGIT / "+" / "-" / "." ) ":"`)。 +fn has_url_scheme(input: &str) -> bool { + let mut chars = input.chars(); + match chars.next() { + Some(first) if first.is_ascii_alphabetic() => {} + _ => return false, + } + for char in chars { + if char == ':' { + return true; + } + if !(char.is_ascii_alphanumeric() || char == '+' || char == '-' || char == '.') { + return false; + } + } + false +} + +/// 把后台数据面装配为子资源(主线程调用):按**本线程文档**的清单顺序 +/// 组装——inline 用原文、外链按绝对 URL 查表,失败/缺席的槽位跳过(降级 +/// 语义与 [`fetch_subresources`] 一致);图片按绝对 URL 查表映射到节点, +/// 同 URL 共享一份像素(M1)。 +#[must_use] +pub fn assemble_page_data( + document: &Document, + base_url: &str, + fetched: &FetchedPageData, +) -> Subresources { + assemble_from_maps(document, base_url, &fetched.css, &fetched.images) +} + +/// 共享抓取核心:收集清单 → URL 解析/去重 → 并发抓取(按类别带预算)→ +/// 解码,成功者按绝对 URL 打包。settle(含失败/超时/预算降级路径)在 +/// 返回前恰触发一次回调。 +fn fetch_resolved( + fetcher: &dyn NetworkFetcher, + base_url: &str, + document: &Document, + on_settle: &mut dyn FnMut(), +) -> (HashMap>, HashMap>) { let style_resources = nexty_html::collect_style_resources(document); let image_resources = nexty_html::collect_image_resources(document); - // ---- 阶段一:解析 URL,编出抓取任务 ---- - /// 清单顺序的样式表槽位:inline 有文本,外链等抓取,解析失败的丢弃。 - enum SheetSlot { - Inline(String), - External { url: String }, - Unresolved, - } - let mut css_urls: HashMap = HashMap::new(); // 绝对 URL → 任务序号 + // ---- 阶段一:解析 URL,编出抓取任务(同 URL 只抓一次)---- + let mut css_seen: HashSet = HashSet::new(); let mut css_tasks: Vec = Vec::new(); - let mut sheet_slots: Vec = Vec::new(); - let mut image_urls: HashMap> = HashMap::new(); // 绝对 URL → 节点 + let mut image_seen: HashSet = HashSet::new(); let mut image_tasks: Vec = Vec::new(); for resource in &style_resources { - match resource { - StyleResource::Inline { css } => { - sheet_slots.push(SheetSlot::Inline(css.clone())); - } - StyleResource::External { href } => match resolve(base_url, href) { - Ok(url) => { - // 同一 URL 只抓一次,级联里按首现位置参与 - if css_urls.insert(url.clone(), css_tasks.len()).is_none() { - css_tasks.push(url.clone()); - } - sheet_slots.push(SheetSlot::External { url }); - } - // URL 解析失败 = 该表不参与级联(降级) - Err(_) => sheet_slots.push(SheetSlot::Unresolved), - }, + if let StyleResource::External { href } = resource + && let Ok(url) = resolve(base_url, href) + && css_seen.insert(url.clone()) + { + css_tasks.push(url); } } for resource in &image_resources { - if let Ok(url) = resolve(base_url, &resource.src) { - image_urls - .entry(url.clone()) - .or_insert_with(|| { - image_tasks.push(url.clone()); - Vec::new() - }) - .push(resource.node); + if let Ok(url) = resolve(base_url, &resource.src) + && image_seen.insert(url.clone()) + { + image_tasks.push(url); } } @@ -102,49 +309,253 @@ pub fn fetch_subresources( let css_bytes = fetch_many(fetcher, &css_tasks, MAX_STYLESHEET_BODY_BYTES); let image_bytes = fetch_many(fetcher, &image_tasks, MAX_IMAGE_BODY_BYTES); - // ---- 阶段三:按清单顺序重组 ---- - // inline 与抓到的外链按文档出现顺序交错产出(顺序即级联优先级); - // 抓取失败的外链槽位跳过 + // ---- 阶段三:成功者按绝对 URL 打包(图片解码在本线程完成)---- + let mut css = HashMap::new(); + for (task, url) in css_tasks.iter().enumerate() { + if let Some(bytes) = &css_bytes[task] { + css.insert(url.clone(), bytes.clone()); + } + } + let mut images: HashMap> = HashMap::new(); + for (task, url) in image_tasks.iter().enumerate() { + let Some(bytes) = &image_bytes[task] else { + continue; // 抓取失败:该图所有节点都无像素(降级) + }; + if let Ok(image) = decode(bytes) { + images.insert(url.clone(), Arc::new(image)); + } // 解码失败:同样降级 + } + + // ---- 首轮编排 settle:全部抓取/解码任务已出结果(含降级路径), + // 恰触发一次回调 ---- + on_settle(); + + (css, images) +} + +/// 按**本线程文档**的清单顺序装配(inline 用原文、外链按绝对 URL 查表、 +/// 图片按 URL 映射到节点):顺序即级联优先级,失败/缺席槽位跳过。 +fn assemble_from_maps( + document: &Document, + base_url: &str, + css: &HashMap>, + images: &HashMap>, +) -> Subresources { let mut stylesheets = Vec::new(); - for slot in &sheet_slots { - match slot { - SheetSlot::Inline(css) => stylesheets.push(Stylesheet::parse(css)), - SheetSlot::External { url } => { - let task = css_urls[url]; - if let Some(bytes) = &css_bytes[task] { + for resource in nexty_html::collect_style_resources(document) { + match resource { + StyleResource::Inline { css } => stylesheets.push(Stylesheet::parse(&css)), + StyleResource::External { href } => { + if let Ok(url) = resolve(base_url, &href) + && let Some(bytes) = css.get(&url) + { let css = String::from_utf8_lossy(bytes); stylesheets.push(Stylesheet::parse(&css)); } } - SheetSlot::Unresolved => {} } } - let mut images: HashMap> = HashMap::new(); - for (task, url) in image_tasks.iter().enumerate() { - let Some(bytes) = &image_bytes[task] else { - continue; // 抓取失败:该图所有节点都无像素(降级) - }; - match decode(bytes) { - Ok(image) => { - if let Some(nodes) = image_urls.get(url) { - // 一份像素按 Arc 共享给该 URL 的全部节点(M1 零拷贝) - let shared = Arc::new(image); - for node in nodes { - images.insert(*node, Arc::clone(&shared)); + let mut images_by_node: HashMap> = HashMap::new(); + for resource in nexty_html::collect_image_resources(document) { + if let Ok(url) = resolve(base_url, &resource.src) + && let Some(image) = images.get(&url) + { + // 一份像素按 Arc 共享给该 URL 的全部节点(M1 零拷贝) + images_by_node.insert(resource.node, Arc::clone(image)); + } + } + + Subresources { + stylesheets, + images: images_by_node, + } +} + +/// @font-face 待抓取源(K4 T3):绝对 URL + 注册用描述符。 +/// +/// 同一 URL 可携带不同描述符出现多次(同一文件按多条 `@font-face` 声明为 +/// 不同 weight/style face);抓取按 URL 去重,注册按描述符逐条进行。 +#[derive(Debug, Clone, PartialEq, Eq)] +pub struct FontRequest { + /// 字体文件的绝对地址(已按文档 base 解析,`FetchedDocument.base_url` + /// 语义——重定向落点)。 + pub url: String, + /// 注册描述符:css `FontFaceRule` → text `FontFaceDescriptor` 映射 + /// (weight 缺省 400、style 缺省 normal——CSS Fonts 描述符 initial)。 + pub descriptor: FontFaceDescriptor, +} + +/// 抓取成功的字体字节(后台线程 → 主线程注册,全 `Send` 数据面)。 +#[derive(Debug, Clone, PartialEq, Eq)] +pub struct FetchedFont { + /// 来源绝对 URL(会话去重键)。 + pub url: String, + /// 注册描述符(与请求一致)。 + pub descriptor: FontFaceDescriptor, + /// 字体文件字节。 + pub bytes: Vec, +} + +/// 一批字体字节的注册结果(K4 T3)。 +#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)] +pub struct FontRegistration { + /// 新注册成功的 face 数:> 0 时调用方触发恰好一轮重排 + 重绘。 + pub registered: usize, + /// 注册失败(非字体数据 / 空族名)跳过的源数:页面回退系统字体照常 + /// 渲染(降级语义)。 + pub rejected: usize, +} + +/// 字体子资源编排会话(K4 T3):会话级注册表 + 已注册 URL 集。 +/// +/// 会话级 = 浏览器生命周期内持续有效:跨导航共享已注册字体(同 URL 重复 +/// 导航不再抓取)。三段编排与主文档抓取同构,全部为纯逻辑、可无头测试: +/// ① [`FontOrchestrator::collect`](主线程,页面装配后)收集待抓取源; +/// ② [`fetch_fonts`](后台线程)并发抓取; +/// ③ [`FontOrchestrator::register`](主线程,字节到达)注册进注册表。 +/// +/// 注册表经 [`FontOrchestrator::registry`] 交给 `ParleyTextShaper::with_registry` +/// 接线(构造点一次完成);此后每次 `register` 即生效,无需重建整形器 +/// (nexty-text T2 语义)。本类型不持 `Document`,跨线程边界只传 +/// [`FontRequest`] / [`FetchedFont`] 数据面。 +#[derive(Default)] +pub struct FontOrchestrator { + /// 会话级 @font-face 注册表(`Clone` = 廉价共享句柄)。 + registry: FontRegistry, + /// 已成功注册的字体 URL 集(会话去重;只记成功——负结果允许重试)。 + fetched: HashSet, +} + +impl FontOrchestrator { + /// 空会话(空注册表)。 + #[must_use] + pub fn new() -> Self { + Self::default() + } + + /// 会话级注册表句柄(供 `ParleyTextShaper::with_registry` 接线)。 + #[must_use] + pub fn registry(&self) -> &FontRegistry { + &self.registry + } + + /// 收集阶段(主线程,页面装配后):从解析后的作者样式表收集 `@font-face` + /// 的 `url()` 源([CSS Fonts 4 §4](https://drafts.csswg.org/css-fonts-4/#font-face-rule) + /// 简化档)。 + /// + /// 过滤规则:`local()` 源不抓取;format 提示含 woff/woff2 的源跳过 + /// (harfrust 不消费,偏差);URL 非法跳过;会话内已注册 URL 跳过; + /// 同页内同(URL, 描述符)去重。描述符映射按 css 层映射表:weight + /// `unwrap_or(400)`、style `None→Normal` / `Italic→Italic`。 + #[must_use] + pub fn collect(&self, stylesheets: &[Stylesheet], base_url: &str) -> Vec { + let mut requests: Vec = Vec::new(); + // 页内去重键(URL, family, weight, style):同 URL 同描述符只出一项 + let mut seen: HashSet<(String, String, u16, FontStyle)> = HashSet::new(); + for sheet in stylesheets { + for face in sheet.font_faces() { + let descriptor = FontFaceDescriptor { + family: face.family.clone(), + weight: face.weight.unwrap_or(400), + style: match face.style { + Some(FontFaceStyle::Italic) => FontStyle::Italic, + Some(FontFaceStyle::Normal) | None => FontStyle::Normal, + }, + }; + for source in &face.sources { + let FontFaceSource::Url { url, format_hints } = source else { + continue; // local():已安装字体,不经网络 + }; + if format_hints.iter().any(|hint| is_skipped_font_format(hint)) { + continue; // woff/woff2:harfrust 不消费(偏差),跳过 + } + let Ok(absolute) = resolve(base_url, url) else { + continue; // URL 非法:降级跳过(回退系统字体) + }; + if self.fetched.contains(&absolute) { + continue; // 会话去重:同 URL 已注册,不重复抓取 + } + let key = ( + absolute.clone(), + descriptor.family.clone(), + descriptor.weight, + descriptor.style, + ); + if seen.insert(key) { + requests.push(FontRequest { + url: absolute, + descriptor: descriptor.clone(), + }); } } } - Err(_) => continue, // 解码失败:同样降级 } + requests } - Subresources { - stylesheets, - images, + /// 注册阶段(主线程,字节到达):逐条注册进注册表。 + /// + /// `InvalidFontData` / `EmptyFamily` 跳过并记入 [`FontRegistration::rejected`], + /// 页面回退系统字体照常渲染(降级语义);注册成功的 URL 记入会话集 + /// (跨导航去重)。调用方按 [`FontRegistration::registered`] > 0 触发 + /// **恰好一轮**重排 + 重绘——重复/迟到载荷注册数为 0,不产生额外重排。 + pub fn register(&mut self, fonts: Vec) -> FontRegistration { + let mut result = FontRegistration::default(); + for font in fonts { + // 会话去重:同 URL 已注册的载荷(迟到 / 竞态重复抓取)跳过—— + // 这是「registered > 0 恰好出现一次 → 重排恰一轮」的保证。 + if self.fetched.contains(&font.url) { + continue; + } + match self.registry.register(font.bytes, font.descriptor) { + Ok(()) => { + // 只记成功:失败的源(404 / 非字体数据)再次导航时重试 + self.fetched.insert(font.url); + result.registered += 1; + } + Err(_) => result.rejected += 1, + } + } + result } } +/// 抓取阶段(后台线程):并发抓取一批字体源,成功者逐请求打包。 +/// +/// 同 URL 只抓一次(复用既有子资源 URL 键控语义,多个描述符共享一份字节); +/// 预算 [`MAX_FONT_BODY_BYTES`],超预算 / 非 2xx / 传输错误按降级语义缺席 +/// (该源回退系统字体)。空请求列表返回空结果,不起任何抓取。 +#[must_use] +pub fn fetch_fonts(fetcher: &dyn NetworkFetcher, requests: &[FontRequest]) -> Vec { + // URL 去重(保序):同 URL 只抓一次 + let mut urls: Vec = Vec::new(); + for request in requests { + if !urls.contains(&request.url) { + urls.push(request.url.clone()); + } + } + let bodies = fetch_many(fetcher, &urls, MAX_FONT_BODY_BYTES); + requests + .iter() + .filter_map(|request| { + let index = urls.iter().position(|url| *url == request.url)?; + let bytes = bodies[index].clone()?; + Some(FetchedFont { + url: request.url.clone(), + descriptor: request.descriptor.clone(), + bytes, + }) + }) + .collect() +} + +/// harfrust 不消费的容器格式提示(woff / woff2,K4 记偏差):带这些提示的 +/// 源跳过抓取。比较不区分 ASCII 大小写(format 串规范未约束大小写)。 +fn is_skipped_font_format(hint: &str) -> bool { + hint.eq_ignore_ascii_case("woff") || hint.eq_ignore_ascii_case("woff2") +} + /// 并发抓取一组 URL,返回与 `urls` 等长的结果槽(失败或超预算为 `None`)。 fn fetch_many( fetcher: &dyn NetworkFetcher, @@ -240,16 +651,19 @@ mod tests { status: 200, headers: Vec::new(), body: body.clone(), + final_url: request.url.clone(), }), Some(Err(status)) => Ok(nexty_network::Response { status: *status, headers: Vec::new(), body: Vec::new(), + final_url: request.url.clone(), }), None => Ok(nexty_network::Response { status: 404, headers: Vec::new(), body: Vec::new(), + final_url: request.url.clone(), }), } } @@ -403,4 +817,237 @@ mod tests { ); assert_eq!(resources.images.len(), 1, "超预算图片跳过,预算内的保留"); } + + // ---- 地址栏输入规范化(K3 T5)---- + + #[test] + fn address_bar_input_without_scheme_gets_http_prefix() { + assert_eq!( + normalize_address_bar_input("example.com"), + "http://example.com" + ); + assert_eq!( + normalize_address_bar_input("example.com/path?q=1"), + "http://example.com/path?q=1" + ); + // 空输入同样补全:交给抓取路径进错误页(不白屏、不 panic) + assert_eq!(normalize_address_bar_input(""), "http://"); + } + + #[test] + fn address_bar_input_with_scheme_is_untouched() { + assert_eq!( + normalize_address_bar_input("https://example.com"), + "https://example.com" + ); + assert_eq!( + normalize_address_bar_input("http://example.com"), + "http://example.com" + ); + // 内部 scheme 与非网络 scheme 原样返回,各自走到其语义终点 + assert_eq!(normalize_address_bar_input("about:blank"), "about:blank"); + assert_eq!( + normalize_address_bar_input("mailto:a@b.test"), + "mailto:a@b.test" + ); + } + + #[test] + fn address_bar_scheme_prefix_follows_whatwg_syntax() { + // scheme 首字符必须是字母,否则视为无 scheme + assert_eq!(normalize_address_bar_input("1http://x"), "http://1http://x"); + // scheme 字符集外(空格)截断判定 → 无 scheme + assert_eq!(normalize_address_bar_input("ht tp://x"), "http://ht tp://x"); + // scheme 允许字母/数字/+-. + assert_eq!(normalize_address_bar_input("a-b.c+x:rest"), "a-b.c+x:rest"); + } + + // ---- @font-face 字体子资源编排(K4 T3)---- + + /// 测试字体字节:nexty-text T2 入库的 OFL 字体资产(工作区内复用同一 + /// 份,不另入库副本)。 + fn test_font_bytes() -> Vec { + std::fs::read(concat!( + env!("CARGO_MANIFEST_DIR"), + "/../nexty-text/tests/data/SpaceMono-Regular.ttf" + )) + .expect("test font asset (nexty-text tests/data)") + } + + /// 构造一个字体抓取请求。 + fn font_request(url: &str, family: &str, weight: u16, style: FontStyle) -> FontRequest { + FontRequest { + url: url.to_owned(), + descriptor: FontFaceDescriptor { + family: family.to_owned(), + weight, + style, + }, + } + } + + /// 描述符映射(weight 缺省 400、style 缺省 normal/italic)+ 过滤 + /// (woff/woff2 提示、local())+ 页内去重。 + #[test] + fn font_requests_map_descriptors_and_filter_sources() { + let sheet = Stylesheet::parse( + "@font-face { font-family: A; src: url(a.ttf); } \ + @font-face { font-family: W; src: url(w.woff2) format(\"woff2\"); } \ + @font-face { font-family: W2; src: url(w2.woff) format(\"woff\"); } \ + @font-face { font-family: L; src: local(\"Sys X\"), url(l.ttf); font-weight: 700; font-style: italic; } \ + @font-face { font-family: OnlyLocal; src: local(\"Sys Y\"); } \ + @font-face { font-family: A; src: url(a.ttf); }", + ); + let fonts = FontOrchestrator::new(); + let requests = fonts.collect(std::slice::from_ref(&sheet), BASE); + assert_eq!( + requests, + vec![ + font_request("https://page.test/a.ttf", "A", 400, FontStyle::Normal), + font_request("https://page.test/l.ttf", "L", 700, FontStyle::Italic), + ], + "woff/woff2 提示与 local() 跳过;描述符按映射表(缺省 400/normal,italic 映射);页内同 URL 同描述符去重" + ); + } + + /// 相对 URL 按文档 base 解析、非法 URL 跳过、会话去重(注册成功后 + /// 同 URL 再收集为空——同 URL 重复导航不重复抓取的收集侧语义)。 + #[test] + fn font_requests_resolve_base_skip_invalid_and_dedupe_by_session() { + let sheet = Stylesheet::parse( + "@font-face { font-family: A; src: url(../fonts/a.ttf); } \ + @font-face { font-family: Bad; src: url(\"http://bad host/x.ttf\"); }", + ); + let fonts = FontOrchestrator::new(); + let requests = fonts.collect( + std::slice::from_ref(&sheet), + "https://page.test/dir/page.html", + ); + assert_eq!( + requests, + vec![font_request( + "https://page.test/fonts/a.ttf", + "A", + 400, + FontStyle::Normal + )], + "相对 URL 按 base 解析,非法 URL 跳过" + ); + + let mut fonts = FontOrchestrator::new(); + let sheet = Stylesheet::parse("@font-face { font-family: A; src: url(a.ttf) }"); + assert_eq!(fonts.collect(std::slice::from_ref(&sheet), BASE).len(), 1); + let registered = fonts.register(vec![FetchedFont { + url: "https://page.test/a.ttf".to_owned(), + descriptor: font_request("x", "A", 400, FontStyle::Normal).descriptor, + bytes: test_font_bytes(), + }]); + assert_eq!(registered.registered, 1); + assert!( + fonts.collect(std::slice::from_ref(&sheet), BASE).is_empty(), + "注册成功后同 URL 不再收集(跨导航会话去重)" + ); + } + + /// 抓取:同 URL 只抓一次(多描述符共享一份字节);404 / 超预算按 + /// 降级语义缺席。 + #[test] + fn fetch_fonts_dedupes_urls_and_degrades_failures_and_budget() { + let fetcher = MockFetcher::new(); + fetcher.serve("https://page.test/a.ttf", b"font-a"); + fetcher.fail("https://page.test/lost.ttf", 404); + fetcher.serve( + "https://page.test/huge.ttf", + &vec![0u8; MAX_FONT_BODY_BYTES + 1], + ); + let requests = vec![ + font_request("https://page.test/a.ttf", "A", 400, FontStyle::Normal), + font_request("https://page.test/a.ttf", "A", 700, FontStyle::Normal), + font_request("https://page.test/lost.ttf", "B", 400, FontStyle::Normal), + font_request("https://page.test/huge.ttf", "C", 400, FontStyle::Normal), + ]; + + let fonts = fetch_fonts(&fetcher, &requests); + assert_eq!( + fetcher + .hits + .lock() + .unwrap() + .iter() + .filter(|url| **url == "https://page.test/a.ttf") + .count(), + 1, + "同 URL 只抓一次" + ); + assert_eq!( + fonts.len(), + 2, + "404 与超预算缺席,成功 URL 的两个描述符都在" + ); + assert_eq!(fonts[0].bytes, b"font-a"); + assert_eq!(fonts[0].descriptor.weight, 400); + assert_eq!( + fonts[1].descriptor.weight, 700, + "同 URL 不同描述符共享一次抓取" + ); + } + + /// 注册:非字体数据拒收记数且不入会话集(可重试);成功注册记入 + /// 会话集;重复/迟到载荷(同 URL 已注册)跳过——恰一轮重排的保证。 + #[test] + fn register_rejects_invalid_data_marks_success_and_skips_duplicates() { + let mut fonts = FontOrchestrator::new(); + let junk_sheet = Stylesheet::parse("@font-face { font-family: Junk; src: url(junk.ttf) }"); + let a_sheet = Stylesheet::parse("@font-face { font-family: A; src: url(a.ttf) }"); + + let rejected = fonts.register(vec![FetchedFont { + url: "https://page.test/junk.ttf".to_owned(), + descriptor: font_request("x", "Junk", 400, FontStyle::Normal).descriptor, + bytes: b"not a font".to_vec(), + }]); + assert_eq!( + rejected, + FontRegistration { + registered: 0, + rejected: 1 + }, + "非字体数据拒收记数" + ); + assert_eq!( + fonts.collect(std::slice::from_ref(&junk_sheet), BASE).len(), + 1, + "负结果不入会话集,再次导航可重试" + ); + + let font_bytes = test_font_bytes(); + let payload = FetchedFont { + url: "https://page.test/a.ttf".to_owned(), + descriptor: font_request("x", "A", 400, FontStyle::Normal).descriptor, + bytes: font_bytes.clone(), + }; + let ok = fonts.register(vec![payload.clone()]); + assert_eq!( + ok, + FontRegistration { + registered: 1, + rejected: 0 + } + ); + assert!( + fonts + .collect(std::slice::from_ref(&a_sheet), BASE) + .is_empty(), + "成功注册后同 URL 不再收集" + ); + // 重复/迟到载荷:同 URL 已注册 → 跳过(registered == 0 → 不重排) + let duplicate = fonts.register(vec![payload]); + assert_eq!( + duplicate, + FontRegistration { + registered: 0, + rejected: 0 + }, + "同 URL 重复载荷不重复注册" + ); + } } diff --git a/crates/nexty-chrome/tests/chrome.rs b/crates/nexty-chrome/tests/chrome.rs index f06e3e1..2d17b9e 100644 --- a/crates/nexty-chrome/tests/chrome.rs +++ b/crates/nexty-chrome/tests/chrome.rs @@ -10,6 +10,8 @@ use nexty_text::ParleyTextShaper; use nexty_chrome::pipeline::{self, Viewport}; use nexty_chrome::render::{RenderError, RenderThread}; +use nexty_chrome::resources::{fetch_document, normalize_address_bar_input}; +use nexty_network::CachedFetcher; fn approx(a: f32, b: f32) -> bool { (a - b).abs() < 0.01 @@ -25,7 +27,18 @@ fn end_to_end_page_renders_background_and_border() { let root = pipeline::layout_page(&page, &shaper, 400.0).expect("root"); let scene = pipeline::build_scene(&page, &root); - // 显示列表应包含:body 白底、box 蓝底、四条红边、一条文本 + // body 白底按 CSS 2.2 §14.2 传播到画布(搬移语义:场景中不再发 body + // 白底,由呈现层把 canvas_background_commands 插到场景底部) + let canvas = pipeline::canvas_background_commands(&page, 400.0, 300.0); + assert!( + matches!( + &canvas[..], + [Command::FillRect { color, .. }] if *color == Color::opaque(255, 255, 255) + ), + "body 白底传播为画布白色底指令" + ); + + // 显示列表应包含:box 蓝底、四条红边、一条文本 let fills: Vec<_> = scene .commands .iter() @@ -40,9 +53,6 @@ fn end_to_end_page_renders_background_and_border() { .filter(|command| matches!(command, Command::DrawText { .. })) .collect(); - let has_white = fills.iter().any(|(rect, color)| { - color.r == 255 && color.g == 255 && color.b == 255 && rect.width > 300.0 - }); let has_blue = fills .iter() .any(|(_, color)| *color == Color::opaque(0, 128, 255)); @@ -50,7 +60,6 @@ fn end_to_end_page_renders_background_and_border() { .iter() .filter(|(_, color)| *color == Color::opaque(255, 0, 0)) .count(); - assert!(has_white, "body 白底"); assert!(has_blue, "box 蓝底"); assert_eq!(red_strips, 4, "四条红边"); assert_eq!(texts.len(), 1, "hello 一个文本 run"); @@ -503,17 +512,33 @@ use std::collections::BTreeMap; use std::sync::Mutex; /// 内存 mock fetcher:URL → body / 状态码;未登记的 URL 返回 404。 +/// K3 T5 起支持按 URL 的响应头与 final_url 覆盖(charset / 缓存头 / +/// 重定向落点模拟),并记录抓取计数供缓存命中断言。 struct MockFetcher { routes: Mutex, u16>>>, + /// 按 URL 的响应头(未登记 = 空头表)。 + headers: Mutex>>, + /// 按 URL 的 final_url 覆盖(重定向落点;未登记 = 请求 URL)。 + final_urls: Mutex>, + /// 抓取计数(共享句柄:CachedFetcher 包住 mock 后仍可读内部计数)。 + hits: Arc>>, } impl MockFetcher { fn new() -> Self { Self { routes: Mutex::new(BTreeMap::new()), + headers: Mutex::new(BTreeMap::new()), + final_urls: Mutex::new(BTreeMap::new()), + hits: Arc::new(Mutex::new(Vec::new())), } } + /// 抓取计数句柄:mock 被搬进 CachedFetcher 后从外部读计数用。 + fn hits(&self) -> Arc>> { + self.hits.clone() + } + fn serve(&self, url: &str, body: &[u8]) { self.routes .lock() @@ -527,26 +552,58 @@ impl MockFetcher { .unwrap() .insert(url.to_owned(), Err(status)); } + + /// 带响应头的登记(charset / cache-control 等用例)。 + fn serve_with_headers(&self, url: &str, headers: Vec<(String, String)>, body: &[u8]) { + self.serve(url, body); + self.headers.lock().unwrap().insert(url.to_owned(), headers); + } + + /// 模拟重定向落点:响应的 final_url 与请求 URL 不同。 + fn serve_final_url(&self, url: &str, final_url: &str, body: &[u8]) { + self.serve(url, body); + self.final_urls + .lock() + .unwrap() + .insert(url.to_owned(), final_url.to_owned()); + } } impl NetworkFetcher for MockFetcher { fn fetch(&self, request: &Request) -> Result { + self.hits.lock().unwrap().push(request.url.clone()); let routes = self.routes.lock().unwrap(); + let final_url = self + .final_urls + .lock() + .unwrap() + .get(&request.url) + .cloned() + .unwrap_or_else(|| request.url.clone()); match routes.get(&request.url) { Some(Ok(body)) => Ok(Response { status: 200, - headers: Vec::new(), + headers: self + .headers + .lock() + .unwrap() + .get(&request.url) + .cloned() + .unwrap_or_default(), body: body.clone(), + final_url, }), Some(Err(status)) => Ok(Response { status: *status, headers: Vec::new(), body: Vec::new(), + final_url, }), None => Ok(Response { status: 404, headers: Vec::new(), body: Vec::new(), + final_url, }), } } @@ -915,3 +972,464 @@ fn hardening_full_chain_body() { "巨图声明无像素、无 DrawImage" ); } + +// ---- K1 T3:事件模型接线——生命周期派发(先派发后默认、各恰一次) ---- + +use nexty_chrome::pipeline::PendingLifecycle; +use nexty_dom::{DOM_CONTENT_LOADED, Event, EventListener, EventLoop, LOAD}; +use std::cell::RefCell; +use std::rc::Rc; + +type LifecycleLog = Rc>>; + +/// 生命周期计数钩子:把派发的事件类型记入日志。 +fn lifecycle_recorder(log: &LifecycleLog, label: &'static str) -> Box { + let log = Rc::clone(log); + Box::new(move |_event: &mut Event| log.borrow_mut().push(label)) +} + +/// ③ DOMContentLoaded 在解析后、load 在子资源 settle 后各恰一次:走与 +/// app.rs 后台线程相同的编排序列(真实 parse → settle 回调信号 → +/// build_page → 信号 post → 排空),计数钩子挂在文档根上。 +#[test] +fn lifecycle_events_fire_once_each_in_order_after_signals() { + let fetcher = MockFetcher::new(); + fetcher.serve("https://page.test/ext.css", b"p { color: blue }"); + let html = "

hi

"; + + // 信号捕获点与 app.rs load 的后台线程一致 + let document = nexty_html::parse_document(html, ParseOptions::default()); + let parsed = true; // parse_document 返回 + let mut settled = false; + let sub = resources::fetch_subresources_with_settle( + &fetcher, + "https://page.test/index.html", + &document, + &mut || settled = true, + ); + assert!(settled, "首轮编排 settle(成功路径)恰触发一次回调"); + + let mut page = pipeline::build_page(document, sub.stylesheets, sub.images); + let log: LifecycleLog = Rc::new(RefCell::new(Vec::new())); + let root = page.document.root(); + page.document.add_listener( + root, + DOM_CONTENT_LOADED, + false, + lifecycle_recorder(&log, "dcl"), + ); + page.document + .add_listener(root, LOAD, false, lifecycle_recorder(&log, "load")); + + // 信号齐 → pipeline 单处钩子 post → EventLoop 排空派发 + let mut event_loop = EventLoop::new(); + page.post_lifecycle_tasks( + &mut event_loop, + PendingLifecycle { + dom_content_loaded: parsed, + load: settled, + }, + ); + event_loop.run_pending_tasks(&mut page.document); + assert_eq!( + *log.borrow(), + ["dcl", "load"], + "DOMContentLoaded 先于 load,各恰一次" + ); + + // 队列已空:重复排空不重复派发(每页各恰一次) + event_loop.run_pending_tasks(&mut page.document); + assert_eq!(log.borrow().len(), 2, "排空后无重复派发"); +} + +/// ③(降级路径):子资源全部失败/超时/超预算时 settle 回调仍恰触发一次, +/// load 照常派发(含失败/超时/预算降级的语义)。 +#[test] +fn lifecycle_load_fires_after_settled_degraded_subresources() { + let fetcher = MockFetcher::new(); + fetcher.fail("https://page.test/broken.css", 500); + fetcher.fail("https://page.test/lost.png", 404); + let html = "\ +

hi

"; + + let document = nexty_html::parse_document(html, ParseOptions::default()); + let mut settled = false; + let sub = resources::fetch_subresources_with_settle( + &fetcher, + "https://page.test/index.html", + &document, + &mut || settled = true, + ); + assert!(settled, "全失败路径 settle 回调仍触发"); + assert!(sub.stylesheets.is_empty() && sub.images.is_empty()); + + let mut page = pipeline::build_page(document, sub.stylesheets, sub.images); + let log: LifecycleLog = Rc::new(RefCell::new(Vec::new())); + let root = page.document.root(); + page.document + .add_listener(root, LOAD, false, lifecycle_recorder(&log, "load")); + + let mut event_loop = EventLoop::new(); + page.post_lifecycle_tasks( + &mut event_loop, + PendingLifecycle { + dom_content_loaded: true, + load: settled, + }, + ); + event_loop.run_pending_tasks(&mut page.document); + assert_eq!(*log.borrow(), ["load"], "降级 settle 后 load 恰一次"); +} + +/// ③(门控):信号未到不派发;只到解析信号只派发 DOMContentLoaded—— +/// K3/K4 异步 settle 的接缝。 +#[test] +fn lifecycle_events_wait_for_their_signals() { + let mut page = pipeline::load_page("hi", ""); + let log: LifecycleLog = Rc::new(RefCell::new(Vec::new())); + let root = page.document.root(); + page.document.add_listener( + root, + DOM_CONTENT_LOADED, + false, + lifecycle_recorder(&log, "dcl"), + ); + page.document + .add_listener(root, LOAD, false, lifecycle_recorder(&log, "load")); + + let mut event_loop = EventLoop::new(); + page.post_lifecycle_tasks(&mut event_loop, PendingLifecycle::default()); + event_loop.run_pending_tasks(&mut page.document); + assert!(log.borrow().is_empty(), "无信号不派发"); + + page.post_lifecycle_tasks( + &mut event_loop, + PendingLifecycle { + dom_content_loaded: true, + load: false, + }, + ); + event_loop.run_pending_tasks(&mut page.document); + assert_eq!(*log.borrow(), ["dcl"], "只到解析信号 → 仅 DOMContentLoaded"); +} + +// ---- K3 T5:导航编排接线(主文档解码 / 缓存接入 / 重定向落点) ---- + +/// 主文档解码:Content-Type charset=gbk → 按 GBK 解码,标题正确—— +/// 非 UTF-8 页面不再进错误页(错误页 = fetch_document 返回 Err)。 +#[test] +fn gbk_document_with_content_type_charset_decodes_title() { + let fetcher = MockFetcher::new(); + // 「中文」的 GBK 编码字节(0xD6 0xD0 0xCE 0xC4) + let mut body = b"".to_vec(); + body.extend_from_slice(&[0xD6, 0xD0, 0xCE, 0xC4]); + body.extend_from_slice(b""); + fetcher.serve_with_headers( + "https://page.test/gbk.html", + vec![( + "content-type".to_owned(), + "text/html; charset=gbk".to_owned(), + )], + &body, + ); + + let fetched = fetch_document(&fetcher, "https://page.test/gbk.html") + .expect("GBK 页面应成功返回而非错误页"); + let document = nexty_html::parse_document(&fetched.data.html, ParseOptions::default()); + assert_eq!( + pipeline::document_title(&document).as_deref(), + Some("中文"), + "GBK 字节按 charset 解码为可读标题" + ); +} + +/// 无 charset 提示的 GBK 字节:按默认 UTF-8 替换语义兑底,不 panic、 +/// 不进错误页(Err)。非法序列退化为 U+FFFD 可见。 +#[test] +fn gbk_bytes_without_charset_hint_degrade_without_panic() { + let fetcher = MockFetcher::new(); + fetcher.serve("https://page.test/raw.html", &[0xD6, 0xD0, 0xCE, 0xC4]); + + let fetched = + fetch_document(&fetcher, "https://page.test/raw.html").expect("解码兑底路径不失败"); + assert!( + fetched.data.html.contains('\u{FFFD}'), + "无提示的非法 UTF-8 序列替换为 U+FFFD" + ); +} + +/// 缓存接入:CachedFetcher 包裹后同 URL 二次导航命中内存缓存—— +/// mock 计数恰 1 次,两次产物一致。 +#[test] +fn cached_fetcher_serves_second_navigation_from_cache() { + let fetcher = MockFetcher::new(); + fetcher.serve_with_headers( + "https://page.test/doc.html", + vec![("cache-control".to_owned(), "max-age=60".to_owned())], + b"cachedx", + ); + let hits = fetcher.hits(); + let cached = CachedFetcher::new(fetcher); + + let first = fetch_document(&cached, "https://page.test/doc.html").expect("first"); + let second = fetch_document(&cached, "https://page.test/doc.html").expect("second"); + assert_eq!(first.data.html, second.data.html, "缓存体与首抓一致"); + assert_eq!( + hits.lock().unwrap().len(), + 1, + "同 URL 二次导航命中缓存,网络只打一次" + ); +} + +/// 重定向落点:响应 final_url 与请求 URL 不同时,子资源相对地址按落点 +/// (base_url)解析,不按原始请求 URL(WHATWG fetch final URL 语义)。 +#[test] +fn subresources_resolve_against_final_url_after_redirect() { + let fetcher = MockFetcher::new(); + fetcher.serve_final_url( + "https://page.test/r", + "https://page.test/final/page.html", + b"x", + ); + fetcher.serve("https://page.test/final/style.css", b"p { color: red }"); + let hits = fetcher.hits(); + + let fetched = fetch_document(&fetcher, "https://page.test/r").expect("ok"); + assert_eq!( + fetched.base_url, "https://page.test/final/page.html", + "文档 base = 重定向落点" + ); + assert!( + hits.lock() + .unwrap() + .contains(&"https://page.test/final/style.css".to_owned()), + "相对子资源按落点解析" + ); +} + +/// 地址栏输入规范化接进导航:无 scheme 补 http:// 后可达;非法输入走 +/// 抓取路径返回收敛错误串(错误页兑底),全程不 panic。 +#[test] +fn address_bar_navigation_normalizes_and_fails_safe() { + let fetcher = MockFetcher::new(); + fetcher.serve("http://plain.test/x", b"ok"); + + // 无 scheme 输入补全 http:// 后命中 + let normalized = normalize_address_bar_input("plain.test/x"); + assert_eq!(normalized, "http://plain.test/x"); + let fetched = fetch_document(&fetcher, &normalized).expect("补全后可导航"); + assert!(fetched.data.html.contains("ok")); + + // 非法输入(含空格)补全后仍非法:mock 按未登记 → 404 → 错误串收敛, + // 不 panic(真实后端 reqwest 同路径判 InvalidUrl →「无效的地址」) + let invalid = normalize_address_bar_input("hello world"); + assert_eq!( + fetch_document(&fetcher, &invalid).err().as_deref(), + Some("HTTP 404") + ); +} + +// ---- K4 T3:@font-face 字体子资源编排(无头 MockFetcher,与 app.rs 同序) ---- + +use nexty_chrome::resources::{ + FetchedFont, FontOrchestrator, FontRegistration, MAX_FONT_BODY_BYTES, fetch_fonts, +}; +use nexty_layout::TextRun; + +/// 独特测试族名:避开系统字体碰撞(nexty-text T2 偏差——同名系统字体合并 +/// 不保证 @font-face 优先)。 +const TEST_FAMILY: &str = "NextyChromeTestMono"; + +/// 测试字体字节:nexty-text T2 入库的 OFL 字体资产,复用同一份不另入库副本。 +fn test_font_bytes() -> Vec { + std::fs::read(concat!( + env!("CARGO_MANIFEST_DIR"), + "/../nexty-text/tests/data/SpaceMono-Regular.ttf" + )) + .expect("test font asset (nexty-text tests/data)") +} + +/// 树中首个非空文本 run(字体归属断言用);找不到时 panic(测试页必有文本)。 +fn first_run(fragment: &Fragment) -> &TextRun { + fn find(fragment: &Fragment) -> Option<&TextRun> { + for line in &fragment.lines { + for run in &line.runs { + if !run.glyphs.is_empty() { + return Some(run); + } + } + } + for child in &fragment.children { + if let Some(run) = find(child) { + return Some(run); + } + } + None + } + find(fragment).expect("no text run in fragment tree") +} + +/// ①③④:@font-face 页字体字节被抓取且注册(shape 归属);就绪后恰一轮 +/// 重排;同 URL 重复导航不重复抓取。编排序列与 app.rs 的 page_loaded / +/// spawn_font_fetch / fonts_ready 一致(无头模拟,整形器接线同构造点)。 +#[test] +fn font_face_page_fetches_registers_and_relayouts_exactly_once() { + let font_bytes = test_font_bytes(); + let fetcher = MockFetcher::new(); + fetcher.serve("https://page.test/mono.ttf", &font_bytes); + let html = format!( + "\ +

Hello

" + ); + let base = "https://page.test/index.html"; + + // 会话与整形器接线:与 app.rs 构造点同序(registry 先于 shaper) + let mut fonts = FontOrchestrator::new(); + let shaper = ParleyTextShaper::with_registry(fonts.registry()); + let mut layouts = 0usize; + + // 第一轮导航:抓取 → 装配 → 收集(build_page 之前,同 page_loaded) + let document = nexty_html::parse_document(&html, ParseOptions::default()); + let resources = resources::fetch_subresources(&fetcher, base, &document); + let requests = fonts.collect(&resources.stylesheets, base); + assert_eq!(requests.len(), 1, "收集到 @font-face 的 url() 源"); + let page = pipeline::build_page(document, resources.stylesheets, resources.images); + + // 首帧布局:注册表为空 → 系统回退字体(不 panic;字节不是注册字体) + let root1 = { + layouts += 1; + pipeline::layout_page(&page, &shaper, 400.0).expect("root") + }; + assert_eq!(layouts, 1); + assert!( + first_run(&root1) + .fonts + .iter() + .all(|font| font.data().as_ref() != font_bytes.as_slice()), + "字体未就绪首帧用系统字体渲染" + ); + + // SceneCache 缓存键(页面代次):基线一次 emit + let mut cache = pipeline::SceneCache::new(); + let _ = cache.scene_for(1, &page, &root1, 400.0, &[]); + assert_eq!(cache.emits(), 1); + + // 字节就绪(后台 fetch_fonts)→ 注册 → registered > 0 → 恰一轮重排 + let fetched = fetch_fonts(&fetcher, &requests); + assert_eq!(fetched.len(), 1); + let registration = fonts.register(fetched); + assert_eq!( + registration, + FontRegistration { + registered: 1, + rejected: 0 + } + ); + let root2 = { + layouts += 1; + pipeline::layout_page(&page, &shaper, 400.0).expect("root") + }; + assert_eq!(layouts, 2, "就绪后恰一轮重排(布局调用恰 +1)"); + + // shape 归属:run 字体表含注册字节(同一 shaper 实例自动生效,未重建) + assert!( + first_run(&root2) + .fonts + .iter() + .any(|font| font.data().as_ref() == font_bytes.as_slice()), + "注册字体进入 shape 归属" + ); + + // 代次推进 → 场景缓存失效重建(重排接既有缓存失效机制) + let _ = cache.scene_for(2, &page, &root2, 400.0, &[]); + assert_eq!(cache.emits(), 2, "重排推进代次使 SceneCache 重建"); + + // 重复/迟到载荷:registered == 0 → 不再重排(layouts 保持 2) + let duplicate = fonts.register(vec![FetchedFont { + url: "https://page.test/mono.ttf".to_owned(), + descriptor: requests[0].descriptor.clone(), + bytes: font_bytes.clone(), + }]); + assert_eq!(duplicate.registered, 0, "重复载荷不重复注册"); + + // 第二轮导航(同 URL):会话去重 → 不再收集、不再抓取、不再重排 + let document = nexty_html::parse_document(&html, ParseOptions::default()); + let resources = resources::fetch_subresources(&fetcher, base, &document); + assert!( + fonts.collect(&resources.stylesheets, base).is_empty(), + "会话去重:二次导航不再收集" + ); + assert_eq!(layouts, 2, "二次导航零重排"); + assert_eq!( + fetcher + .hits() + .lock() + .unwrap() + .iter() + .filter(|url| **url == "https://page.test/mono.ttf") + .count(), + 1, + "mock 计数恰 1" + ); +} + +/// ②:404 / 非字体数据 / 超预算字体 → 不 panic,页面回退系统字体照常 +/// 渲染;注册失败不触发重排。 +#[test] +fn font_failures_degrade_to_system_fonts_without_panicking() { + let fetcher = MockFetcher::new(); + fetcher.fail("https://page.test/lost.ttf", 404); + fetcher.serve("https://page.test/junk.ttf", b"not a font"); + fetcher.serve( + "https://page.test/huge.ttf", + &vec![0u8; MAX_FONT_BODY_BYTES + 1], + ); + let html = "

Hello

"; + let base = "https://page.test/index.html"; + + let mut fonts = FontOrchestrator::new(); + let shaper = ParleyTextShaper::with_registry(fonts.registry()); + let mut layouts = 0usize; + + let document = nexty_html::parse_document(html, ParseOptions::default()); + let resources = resources::fetch_subresources(&fetcher, base, &document); + let requests = fonts.collect(&resources.stylesheets, base); + assert_eq!( + requests.len(), + 3, + "url() 源全部收集(格式/预算过滤发生在抓取、注册层)" + ); + let page = pipeline::build_page(document, resources.stylesheets, resources.images); + let root = { + layouts += 1; + pipeline::layout_page(&page, &shaper, 400.0).expect("root") + }; + + // 抓取:404 / 超预算缺席;junk 字节到达但注册期拒收(记报告) + let fetched = fetch_fonts(&fetcher, &requests); + assert_eq!(fetched.len(), 1, "404 与超预算缺席"); + let registration = fonts.register(fetched); + assert_eq!( + registration, + FontRegistration { + registered: 0, + rejected: 1 + }, + "非字体数据拒收记数" + ); + assert_eq!(layouts, 1, "注册失败不触发重排"); + + // 页面照常渲染:系统回退文本进显示列表(不 panic、不空白) + let scene = pipeline::build_scene(&page, &root); + assert!( + scene + .commands + .iter() + .any(|command| matches!(command, Command::DrawText { .. })), + "回退路径照常渲染文本" + ); +} diff --git a/crates/nexty-chrome/tests/selection.rs b/crates/nexty-chrome/tests/selection.rs index c4ce707..72a5201 100644 --- a/crates/nexty-chrome/tests/selection.rs +++ b/crates/nexty-chrome/tests/selection.rs @@ -116,8 +116,8 @@ fn click_and_drag_are_distinguished_for_link_navigation() { #[test] fn highlight_is_emitted_between_background_and_text() { let page = pipeline::load_page( - "

abc

", - "body { background-color: #ffffff; margin: 0 }", + "

abc

", + "body { margin: 0 }", ); let shaper = ParleyTextShaper::new(); let root = pipeline::layout_page(&page, &shaper, 400.0).expect("root"); diff --git a/docs/decisions/2026-10-31-addressbar-url.md b/docs/decisions/2026-10-31-addressbar-url.md new file mode 100644 index 0000000..7ec93c9 --- /dev/null +++ b/docs/decisions/2026-10-31-addressbar-url.md @@ -0,0 +1,40 @@ +# ADR:地址栏输入的 URL 规范化(无 scheme 补 `http://`) + +日期:2026-10-31(K3 导航与网络完备轮 T5) + +## 决策 + +地址栏提交的输入(`BrowserApp::navigate` 的地址栏路径)在入历史栈与抓取前做 +一步规范化,实现为 `nexty-chrome::resources::normalize_address_bar_input`: + +1. **无 scheme 补 `http://`**(HTTP-first):输入不以 WHATWG URL 的 scheme + 前缀(`ALPHA *( ALPHA / DIGIT / "+" / "-" / "." ) ":"`)开头时,前面拼上 + `http://`。用户输入 `example.com` 实际导航 `http://example.com/`。 +2. **带合法 scheme 的输入原样返回**:`https://…`、`about:blank`、`mailto:…` + 各自走到其语义终点——`about:` 在 `load` 入口特判为内部空白页;其余非 + `http(s)` scheme 由抓取后端的协议白名单判 `InvalidUrl`,进既有错误页。 +3. **合法性不前置校验**:规范化只补 scheme、不做 URL 解析校验。非法输入 + (如含空格的 `hello world`)走既有抓取管线,由错误页兜底——错误页路径 + 已包含生命周期合成、历史语义与错误串收敛,不引入第二条错误路径。 + +## 为什么不是别的 + +- **不猜测 `www.` 前缀**:`example.com` → `http://example.com/` 即可, + Chromium 的 `www.` 自动补全是历史兼容行为,猜测错误时的行为更难解释。 +- **不在 http/https 间猜测升级**:HTTP-first 简单可预期;HSTS / HTTPS-first + 升级策略留给后续轮。 +- **不用正则 crate 判 scheme**:判定是「首字母 + 字符集 + 冒号」的几行字符 + 扫描,引入 `regex` 违反依赖最小化。 +- **不前置 `Url::parse` 校验**:校验点前移需要手工构建第二条错误页路径 + (历史栈、生命周期、转义),而抓取路径的 `InvalidUrl → 「无效的地址」 → + 错误页` 已完整存在,复用即可。 + +## 边界与已知偏差 + +- **不支持 host:port 简写**:`localhost:8080` 的 `localhost:` 恰好匹配 scheme + 语法前缀,会按 scheme=localhost 解析进错误页;需要显式输入 + `http://localhost:8080`。(Chromium 有 host 猜测启发式,本轮不引入。) +- 规范化作用于历史栈入口:栈里存的是规范化后的 URL,后退/前进重放的即 + 实际导航目标。 +- 页面链接点击不走此规范化:链接 href 已由 `resolve` 按文档 base 绝对化 + (带 scheme),规范化对其是无操作。 From 969b1fcc52b07b46b0481664ff219cbfc671796f Mon Sep 17 00:00:00 2001 From: zwork Date: Sat, 31 Oct 2026 18:30:13 +0800 Subject: [PATCH 12/14] [workspace] batch-1 round: AGENTS registration (5 layers + feature table), kernel roadmap + round goal, deps manifest regen, Cargo.lock sync --- AGENTS.md | 19 +- Cargo.lock | 14 +- docs/dependencies.html | 18 +- docs/plans/2026-10-31-kernel-roadmap.md | 362 ++++++++++++++++++ .../plans/2026-10-31-round-batch1-parallel.md | 230 +++++++++++ goal.md | 38 ++ 6 files changed, 658 insertions(+), 23 deletions(-) create mode 100644 docs/plans/2026-10-31-kernel-roadmap.md create mode 100644 docs/plans/2026-10-31-round-batch1-parallel.md create mode 100644 goal.md diff --git a/AGENTS.md b/AGENTS.md index 8182d7f..b8e09b0 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -12,18 +12,18 @@ MusKitty 的**不造轮子**分支。MusKitty 从零手写浏览器核心模块 已落地八层(全部骨架 crate 就位,管线端到端可跑): -- `nexty-dom`(v0.1.3)——自研 arena DOM:节点数据层、树变更算法(pre-insert/insert/remove/replace/clone/normalize)与文档模式控制。**输入边界防护**:节点携带树深度(`link_before` 单点维护、重挂重算、模板内容片段独立起算),`MAX_TREE_DEPTH = 512` 与 `Document::depth` 供下游防线使用。 +- `nexty-dom`(v0.1.4)——自研 arena DOM:节点数据层、树变更算法(pre-insert/insert/remove/replace/clone/normalize)与文档模式控制。**事件模型(K1)**:`event` 模块(feature `event`)——`Event`/`EventTarget`(监听器存 Document 侧 `ListenerRegistry`,句柄身份)、捕获/target/冒泡三阶段传播(target 上捕获与非捕获监听器按注册顺序混触发)、`stopPropagation`/`stopImmediatePropagation`/`preventDefault`(DOM §2.9 简化档:无 shadow/trusted/passive/once),数据面 UIEvent/MouseEvent/KeyboardEvent/WheelEvent/FocusEvent(FocusEvent 仅类型面,K10 补派发点),`EventLoop` FIFO 任务队列(派发中 post 不重入,由 `TaskContext` 类型结构性保证),生命周期事件类型 `DOMContentLoaded`/`load`。**输入边界防护**:节点携带树深度(`link_before` 单点维护、重挂重算、模板内容片段独立起算),`MAX_TREE_DEPTH = 512` 与 `Document::depth` 供下游防线使用。 - `nexty-html`(v0.1.5)——html5ever 的 `TreeSink` 桥接到 arena DOM,提供 `parse_document` 与 `parse_fragment`(含片段上下文命名空间);子资源清单收集(`collect_style_resources` 收集 `` 与 `