Skip to main content

muskitty_layout/
lib.rs

1//! MusKitty Layout — CSS 布局引擎。
2//!
3//! 将 DOM 树 + ComputedStyle 转换为布局盒树,
4//! 使用 taffy 引擎计算 Flexbox/Grid/Block 布局,
5//! 输出每个元素的位置和尺寸。
6//!
7//! # 数据流
8//!
9//! ```text
10//! DOM 树 + ComputedStyle per element
11//!     │  build_layout_tree
12//!     ▼
13//! LayoutTree (taffy TaffyTree + NodeId 映射)
14//!     │  compute_layout
15//!     ▼
16//! LayoutResult (per-element x/y/width/height)
17//! ```
18//!
19//! # 规范依据
20//!
21//! - CSS Display Level 3: box tree / formatting context
22//! - CSS Box Model Level 3: margin/border/padding/content
23//! - CSS Flexbox Level 1: flex container/item
24//! - CSS Grid Level 2: grid container/item
25
26pub(crate) mod convert;
27pub mod result;
28pub(crate) mod style_map;
29pub(crate) mod text;
30pub(crate) mod tree;
31
32pub use convert::{build_layout_tree, build_layout_tree_with_fonts};
33pub use result::{LayoutError, LayoutResult, NodeLayout};
34pub use tree::{LayoutTree, SharedFontSystem};
35
36use taffy::geometry::Size;
37use taffy::style::AvailableSpace;
38
39use std::collections::HashMap;
40use taffy::NodeId;
41
42use crate::text::measure_text;
43use crate::tree::NodeContext;
44
45/// 计算布局树,返回每个元素的布局结果。
46///
47/// `viewport_width` / `viewport_height` 为根容器的可用空间(px),
48/// 作为 taffy 布局计算的 definite available space。
49///
50/// 调用后 [`LayoutTree::taffy`] 内部缓存了每个节点的 [`taffy::tree::Layout`],
51/// 本函数遍历 `node_map` 提取位置与尺寸到 [`LayoutResult`]。
52///
53/// # 错误处理
54///
55/// 返回 `Result<LayoutResult, LayoutError>`。taffy 仅在 NodeId 查询失败/
56/// 树结构非法时报错;**它不检查 style 中的 NaN/Inf**(已对照 taffy 0.12.2
57/// 源码核实),非有限值会被 NaN 坐标/尺寸污染布局结果。该风险由
58/// [`style_map::clamp_length`](crate::style_map::clamp_length) 在
59/// ComputedValue → taffy 的边界统一钳制化解,调用方无需自行防御。
60/// 当 taffy 仍报告错误时,调用方应决定降级策略:使用空
61/// [`LayoutResult::default`] 让 paint 阶段自然跳过所有元素,或显示错误
62/// 占位符。**不应** `expect` panic 跨模块传播。
63pub fn compute_layout(
64    tree: &mut LayoutTree,
65    viewport_width: f32,
66    viewport_height: f32,
67) -> Result<LayoutResult, LayoutError> {
68    let mut result = LayoutResult::new();
69
70    if let Some(root) = tree.root {
71        // measure function:对 Text context 按容器可用宽度换行测量(T-3)。
72        // LAY-2:字体系统 Rc 共享(会话级注入),每次 measure 取 RefCell
73        // 可变借用——闭包持有 Rc 克隆,与 `&mut tree.taffy` 无借用冲突。
74        let font_system = std::rc::Rc::clone(&tree.font_system);
75        let measure = |_known: Size<Option<f32>>,
76                       available: Size<AvailableSpace>,
77                       _id: NodeId,
78                       ctx: Option<&mut NodeContext>,
79                       _style: &taffy::style::Style|
80         -> Size<f32> {
81            let Some(NodeContext::Text {
82                text,
83                font_size,
84                font_family,
85                font_weight,
86                line_height,
87                measured,
88            }) = ctx
89            else {
90                return Size::ZERO;
91            };
92            let max_width = match available.width {
93                AvailableSpace::Definite(w) => Some(w),
94                _ => None,
95            };
96            // LAY-3:同可用宽度的重复测量直接命中缓存(文本/字体参数
97            // 不可变,测量仅由可用宽度决定),跳过 Buffer::new + shaping。
98            let (measured_w, h) = if let Some((key, cached)) = measured {
99                if *key == max_width {
100                    // 命中:width 语义同下(Definite 取容器宽,占满行)。
101                    return Size {
102                        width: match available.width {
103                            AvailableSpace::Definite(w) => w,
104                            _ => cached.0,
105                        },
106                        height: cached.1,
107                    };
108                }
109                // key 不同:重测并覆盖缓存(单槽,最近一次为准)。
110                measure_text(
111                    text,
112                    *font_size,
113                    font_family,
114                    *font_weight,
115                    *line_height,
116                    max_width,
117                    &mut font_system.borrow_mut(),
118                )
119            } else {
120                measure_text(
121                    text,
122                    *font_size,
123                    font_family,
124                    *font_weight,
125                    *line_height,
126                    max_width,
127                    &mut font_system.borrow_mut(),
128                )
129            };
130            *measured = Some((max_width, (measured_w, h)));
131            // 换行时 width = 容器可用宽度(占满行),renderer 用同宽换行保持一致。
132            let width = match available.width {
133                AvailableSpace::Definite(w) => w,
134                _ => measured_w,
135            };
136            Size { width, height: h }
137        };
138
139        tree.taffy
140            .compute_layout_with_measure(
141                root,
142                Size {
143                    width: AvailableSpace::Definite(viewport_width),
144                    height: AvailableSpace::Definite(viewport_height),
145                },
146                measure,
147            )
148            // LAY-1:taffy 错误在边界处转 String,pub API 不泄漏引擎类型。
149            .map_err(|e| LayoutError::ComputeLayoutFailed(e.to_string()))?;
150
151        for (&dom_addr, &taffy_node) in &tree.node_map {
152            let layout = tree
153                .taffy
154                .layout(taffy_node)
155                // LAY-1:以 DOM 指针地址标识(与 LayoutResult 同 key)。
156                .map_err(|_| LayoutError::NodeLayoutMissing(dom_addr))?;
157            result.nodes.insert(
158                dom_addr,
159                NodeLayout {
160                    x: layout.location.x,
161                    y: layout.location.y,
162                    abs_x: 0.0,
163                    abs_y: 0.0,
164                    width: layout.size.width,
165                    height: layout.size.height,
166                },
167            );
168        }
169
170        // 绝对坐标:自根沿 taffy 树累加偏移(P2-19 / PERF-12)。
171        //
172        // taffy 的 location 相对其 taffy 父节点。`display: contents` /
173        // 非渲染标签 splice 后,DOM 祖先链 ≠ taffy 父链——Renderer 若沿
174        // DOM 祖先累加,未来引入 `position: absolute`(location 相对
175        // containing block)或 transform 时就会双重计数。因此这里直接沿
176        // taffy 树把偏移累加为画布绝对坐标,Renderer 只读 `abs_x`/`abs_y`。
177        let reverse: HashMap<NodeId, usize> =
178            tree.node_map.iter().map(|(&addr, &n)| (n, addr)).collect();
179        // 迭代式 DFS(避免深 DOM 递归溢出);children 顺序即 DOM 先序。
180        let mut stack: Vec<(NodeId, f32, f32)> = vec![(root, 0.0, 0.0)];
181        while let Some((node_id, parent_abs_x, parent_abs_y)) = stack.pop() {
182            if let Ok(layout) = tree.taffy.layout(node_id) {
183                let abs_x = parent_abs_x + layout.location.x;
184                let abs_y = parent_abs_y + layout.location.y;
185                if let Some(&addr) = reverse.get(&node_id) {
186                    if let Some(entry) = result.nodes.get_mut(&addr) {
187                        entry.abs_x = abs_x;
188                        entry.abs_y = abs_y;
189                    }
190                }
191                if let Ok(children) = tree.taffy.children(node_id) {
192                    for child in children {
193                        stack.push((child, abs_x, abs_y));
194                    }
195                }
196            }
197        }
198    }
199
200    Ok(result)
201}
202
203#[cfg(test)]
204mod tests {
205    use super::*;
206
207    #[test]
208    fn empty_tree_returns_ok_empty_result() {
209        let mut tree = LayoutTree::new();
210        let result = compute_layout(&mut tree, 800.0, 600.0).expect("empty tree should succeed");
211        assert!(result.nodes.is_empty());
212    }
213
214    #[test]
215    fn compute_layout_propagates_taffy_error_on_nan_input() {
216        // 构造一个会导致 taffy 报错的 LayoutTree:在 root style 中塞入 NaN 尺寸。
217        use taffy::geometry::Size as TaffySize;
218        use taffy::style::{Dimension, Style};
219
220        let mut tree = LayoutTree::new();
221        let root = tree
222            .taffy
223            .new_leaf(Style {
224                size: TaffySize {
225                    width: Dimension::length(f32::NAN),
226                    height: Dimension::length(f32::NAN),
227                },
228                ..Default::default()
229            })
230            .expect("new_leaf should succeed");
231        tree.root = Some(root);
232
233        let result = compute_layout(&mut tree, 800.0, 600.0);
234        // taffy 可能返回 Err 或成功;若返回 Err 应为 ComputeLayoutFailed
235        match result {
236            Err(LayoutError::ComputeLayoutFailed(_)) => {}
237            Ok(_) => {
238                // 某些 taffy 版本对 NaN 容忍,此情况下允许 Ok
239            }
240            Err(other) => panic!("expected ComputeLayoutFailed or Ok, got {other:?}"),
241        }
242    }
243}