muskitty_layout/tree.rs
1//! 布局树类型定义。
2//!
3//! [`LayoutTree`] 包装 [`taffy::TaffyTree`],维护 DOM 节点指针地址 →
4//! taffy [`NodeId`] 的映射,供布局计算后按 DOM 节点查询结果。
5//!
6//! # 规范依据
7//!
8//! - CSS Display Module Level 3 §2 (Box Tree)
9//! - CSS Box Model Module Level 3 §2 (Box Model)
10
11use std::cell::RefCell;
12use std::collections::HashMap;
13use std::rc::Rc;
14
15use cosmic_text::FontSystem;
16use taffy::NodeId;
17use taffy::TaffyTree;
18
19/// taffy 节点的 context,用于 text 节点的 measure function(T-3 换行)。
20///
21/// 仅 Text 节点携带 context;非 text 节点 measure function 收到的
22/// `Option<&mut NodeContext>` 为 `None`。
23pub(crate) enum NodeContext {
24 /// Text 节点:携带文本内容 + 字体样式,布局时由 measure function 按
25 /// 容器可用宽度换行测量。
26 Text {
27 /// 文本内容。M-3 batch 3:`text-transform` 已在此生效(存转换后文本,
28 /// 保证测量与绘制看到同一份内容,缓存键也因此自洽)。
29 text: String,
30 font_size: f32,
31 font_family: String,
32 font_weight: u16,
33 /// `line-height` 的使用值(px,M-3 batch 3;cascade
34 /// `text_props::used_line_height_px` 解析,含继承的倍数折算)。
35 line_height: f32,
36 /// LAY-3:最近一次测量缓存(key = 容器可用宽度,`None` = 不定
37 /// /单行;value = 自然尺寸 `(width, height)`)。
38 ///
39 /// taffy 嵌套布局对同一节点多次调用 measure(文本测量占布局
40 /// 耗时 80%+,每节点全量 `Buffer::new` + Advanced shaping)。
41 /// 文本/字体参数在节点生命周期内不可变,测量结果仅由可用宽度
42 /// 决定——同 key 重复调用直接命中,跳过 shaping。
43 measured: Option<(Option<f32>, (f32, f32))>,
44 },
45}
46
47/// 布局树。
48///
49/// 包装 taffy 的 [`TaffyTree`],并维护 DOM 节点指针地址(`usize`)
50/// 到 taffy [`NodeId`] 的映射。构建阶段由 [`build_layout_tree`](crate::build_layout_tree)
51/// 填充;计算阶段由 [`compute_layout`](crate::compute_layout) 读取。
52///
53/// # key 契约(PERF-12 降级)
54///
55/// node_map / LayoutResult 的 key 用 `Rc::as_ptr as usize` 裸地址(非不透明
56/// 句柄)。已知限制:DOM 树变更后地址可能失效/复用。后续批次应改为每个
57/// 元素一个稳定 id 的不透明句柄。
58pub struct LayoutTree {
59 /// taffy 的内部节点树(context 类型为 [`NodeContext`])。
60 pub(crate) taffy: TaffyTree<NodeContext>,
61 /// DOM 节点指针地址 → taffy NodeId 映射。
62 pub(crate) node_map: HashMap<usize, NodeId>,
63 /// 根节点 ID(若 DOM 根为 Element 且未 display:none 则有值)。
64 pub(crate) root: Option<NodeId>,
65 /// 文本测量用的字体系统(compute_layout 的 measure function 使用)。
66 ///
67 /// LAY-2:`Rc` 共享——由会话级 [`SharedFontSystem`] 注入(多次建树
68 /// 复用同一份系统字体枚举),不再每次 [`LayoutTree::new`] 重建。
69 pub(crate) font_system: Rc<RefCell<FontSystem>>,
70}
71
72/// 会话级共享的字体系统句柄(LAY-2)。
73///
74/// `FontSystem::new()` 枚举并解析系统字体(50–300 ms)。原实现每次
75/// `build_layout_tree` 都随 [`LayoutTree::new`] 新建一份——每次布局、
76/// resize、热重载都重复支付。本类型由页面/会话级持有一份,多个
77/// [`LayoutTree`] 通过 [`crate::build_layout_tree_with_fonts`] 注入共享
78///(`Rc` 引用计数)。
79///
80/// 包装类型不泄漏 cosmic-text(ADR:外部依赖解耦)。
81#[derive(Clone)]
82pub struct SharedFontSystem {
83 pub(crate) inner: Rc<RefCell<FontSystem>>,
84}
85
86impl SharedFontSystem {
87 /// 枚举系统字体并构建共享句柄(较慢,每会话一次)。
88 pub fn new() -> Self {
89 Self {
90 inner: Rc::new(RefCell::new(FontSystem::new())),
91 }
92 }
93}
94
95impl Default for SharedFontSystem {
96 fn default() -> Self {
97 Self::new()
98 }
99}
100
101impl LayoutTree {
102 /// 创建空布局树(内部新建一份 [`FontSystem`]——每次调用支付一次
103 /// 系统字体枚举;会话级复用请用 [`LayoutTree::new_with_fonts`])。
104 pub fn new() -> Self {
105 Self::new_with_fonts(&SharedFontSystem::new())
106 }
107
108 /// 创建空布局树,注入会话级共享字体系统(LAY-2)。
109 pub fn new_with_fonts(fonts: &SharedFontSystem) -> Self {
110 Self {
111 taffy: TaffyTree::new(),
112 node_map: HashMap::new(),
113 root: None,
114 font_system: Rc::clone(&fonts.inner),
115 }
116 }
117
118 // —— #[doc(hidden)] 测试辅助:对外只暴露抽象行为,隐藏 taffy 类型 ——
119
120 /// 是否有根节点。
121 #[doc(hidden)]
122 pub fn has_root(&self) -> bool {
123 self.root.is_some()
124 }
125
126 /// 布局节点数量。
127 #[doc(hidden)]
128 pub fn node_count(&self) -> usize {
129 self.node_map.len()
130 }
131
132 /// 某 DOM 地址是否在布局树中。
133 #[doc(hidden)]
134 pub fn contains_node(&self, addr: usize) -> bool {
135 self.node_map.contains_key(&addr)
136 }
137
138 /// `parent` 是否为 `child` 的 taffy 父节点(验证 contents splice 等)。
139 #[doc(hidden)]
140 pub fn has_child(&self, parent: usize, child: usize) -> bool {
141 let (Some(&p), Some(&c)) = (self.node_map.get(&parent), self.node_map.get(&child)) else {
142 return false;
143 };
144 self.taffy
145 .children(p)
146 .map(|cs| cs.contains(&c))
147 .unwrap_or(false)
148 }
149}
150
151impl Default for LayoutTree {
152 fn default() -> Self {
153 Self::new()
154 }
155}
156
157#[cfg(test)]
158mod tests {
159 use super::*;
160
161 /// LAY-2:`new_with_fonts` 注入的树共享同一份字体系统(Rc 指向同一
162 /// 分配),会话级句柄跨多次建树复用,系统字体只枚举一次。
163 #[test]
164 fn new_with_fonts_shares_one_font_system() {
165 let fonts = SharedFontSystem::new();
166 let a = LayoutTree::new_with_fonts(&fonts);
167 let b = LayoutTree::new_with_fonts(&fonts);
168 assert!(
169 Rc::ptr_eq(&a.font_system, &fonts.inner),
170 "tree must share the injected font system"
171 );
172 assert!(
173 Rc::ptr_eq(&a.font_system, &b.font_system),
174 "two trees from one handle must share one font system"
175 );
176 }
177
178 /// LAY-2:`LayoutTree::new`(兼容路径)自建字体系统,树间互不共享。
179 #[test]
180 fn new_owns_fresh_font_system() {
181 let a = LayoutTree::new();
182 let b = LayoutTree::new();
183 assert!(!Rc::ptr_eq(&a.font_system, &b.font_system));
184 }
185}