Skip to main content

atmos/os_lib/layout/
baseline.rs

1// flex / grid アイテムのベースライン整列(`align-items` / `align-self: baseline`・`first baseline`・`last baseline`、
2// および `justify-items` / `justify-self: baseline`・縦書き・直交アイテムの合成ベースライン)。
3use super::*;
4
5/// `align-self` / `align-items` / `justify-self` / `justify-items` の値がベースライン整列を指すか。
6pub(crate) fn is_baseline_align(v: &str) -> bool {
7    let t = v.trim();
8    t.eq_ignore_ascii_case("baseline")
9        || t.eq_ignore_ascii_case("first baseline")
10        || t.eq_ignore_ascii_case("last baseline")
11}
12
13/// `last baseline` を指すか。
14pub(crate) fn is_last_baseline_align(v: &str) -> bool {
15    v.trim().eq_ignore_ascii_case("last baseline")
16}
17
18/// `first baseline`(または単なる `baseline`)を指すか。
19pub(crate) fn is_first_baseline_align(v: &str) -> bool {
20    let t = v.trim();
21    t.eq_ignore_ascii_case("baseline") || t.eq_ignore_ascii_case("first baseline")
22}
23
24/// ベースライン整列を行う世界か(縦書きを含め全世界で有効)。
25#[inline]
26pub(crate) fn baseline_enabled() -> bool {
27    true
28}
29
30/// テキストノードの `(1行高さ, margin/top からの ascent)`(Ahem フォントは正確な `0.8em`)。
31pub(crate) fn text_font_ascent(node: &StyledNode, _ch: i32) -> (i32, i32) {
32    let font_px = node
33        .value_ref("font-size")
34        .and_then(parse_font_size_u32)
35        .unwrap_or(16) as i32;
36    let lh = parse_line_height(node.value_ref("line-height"), font_px.max(1) as u32);
37    let line_h = lh.max(font_px);
38    let leading = (line_h - font_px).max(0) / 2;
39    let is_ahem = node
40        .value_ref("font-family")
41        .is_some_and(|f| f.to_ascii_lowercase().contains("ahem"));
42    let ascent = if is_ahem { (font_px * 4) / 5 } else { (font_px * 85) / 100 };
43    (line_h, leading + ascent)
44}
45
46impl<'a> LayoutBox<'a> {
47    /// 自身の content 箱の上端からの first baseline(流れの中の最初の行の基準線。無ければ `None`)。
48    pub(crate) fn first_baseline_in_content(&self) -> Option<i32> {
49        self.first_baseline_in_content_dir(false)
50    }
51
52    /// `lr_sideways = true` のときは `vertical-lr` 縦書き用に 1行目上端から `ch - ascent`(descent 側)を返す。
53    pub(crate) fn first_baseline_in_content_dir(&self, lr_sideways: bool) -> Option<i32> {
54        for c in self.children.iter() {
55            if c.is_whitespace_text()
56                || box_float(c) != "none"
57                || matches!(box_position(c), "absolute" | "fixed")
58            {
59                continue;
60            }
61            match &c.box_type {
62                BoxType::InlineNode(node) => {
63                    let (_, _, cet, _) = c.inline_block_edges();
64                    let cy = (c.dimensions.content.y - cet) - self.dimensions.content.y;
65                    if lr_sideways && !c.is_replaced_inline() {
66                        let (ch, asc) = text_font_ascent(node, c.dimensions.content.height);
67                        return Some(cy + cet + (ch - asc));
68                    }
69                    return Some(cy + c.box_baseline());
70                }
71                BoxType::InlineBlockNode(_) => {
72                    let (_, _, cet, _) = c.inline_block_edges();
73                    let cy = (c.dimensions.content.y - cet) - self.dimensions.content.y;
74                    if c.is_inline_grid() {
75                        if let Some(gb) = c.grid_first_baseline() {
76                            return Some(cy + cet + gb);
77                        }
78                    }
79                    return Some(cy + c.box_baseline());
80                }
81                BoxType::GridNode(_) => {
82                    if let Some(gb) = c.grid_first_baseline() {
83                        let cy = c.dimensions.content.y - self.dimensions.content.y;
84                        return Some(cy + gb);
85                    }
86                }
87                BoxType::BlockNode(_) | BoxType::AnonymousBlock | BoxType::FlexNode(_) => {
88                    if let Some(b) = c.first_baseline_in_content_dir(lr_sideways) {
89                        let cy = c.dimensions.content.y - self.dimensions.content.y;
90                        return Some(cy + b);
91                    }
92                }
93                _ => {}
94            }
95        }
96        None
97    }
98
99    /// 直交または縦書き要素の 1行目テキストの `(content左端からのx, content上端からのy, 幅, 高さ, ascent)` を探す。
100    fn first_inflow_text_box(&self) -> Option<(i32, i32, i32, i32, i32)> {
101        fn walk(root_x: i32, root_y: i32, b: &LayoutBox) -> Option<(i32, i32, i32, i32, i32)> {
102            for c in &b.children {
103                if c.is_whitespace_text()
104                    || box_float(c) != "none"
105                    || matches!(box_position(c), "absolute" | "fixed")
106                {
107                    continue;
108                }
109                match &c.box_type {
110                    BoxType::InlineNode(node) if !c.is_replaced_inline() => {
111                        let cx = c.dimensions.content.x - root_x;
112                        let cy = c.dimensions.content.y - root_y;
113                        let cw = c.dimensions.content.width;
114                        let ch = c.dimensions.content.height;
115                        let font_px = node
116                            .value_ref("font-size")
117                            .and_then(parse_font_size_u32)
118                            .unwrap_or(16) as i32;
119                        let is_ahem = node
120                            .value_ref("font-family")
121                            .is_some_and(|f| f.to_ascii_lowercase().contains("ahem"));
122                        let ascent = if is_ahem { (font_px * 4) / 5 } else { (font_px * 85) / 100 };
123                        return Some((cx, cy, cw.max(font_px), ch.max(font_px), ascent));
124                    }
125                    BoxType::BlockNode(_)
126                    | BoxType::AnonymousBlock
127                    | BoxType::FlexNode(_)
128                    | BoxType::GridNode(_)
129                    | BoxType::InlineBlockNode(_) => {
130                        if let Some(res) = walk(root_x, root_y, c) {
131                            return Some(res);
132                        }
133                    }
134                    _ => {}
135                }
136            }
137            None
138        }
139        walk(self.dimensions.content.x, self.dimensions.content.y, self)
140    }
141
142    /// グリッドコンテナ自身の first baseline(content-box 上端からの距離。CSS Grid §6.1)。
143    pub(crate) fn grid_first_baseline(&self) -> Option<i32> {
144        let mut items: Vec<(&LayoutBox, i32, i32, i32)> = Vec::new();
145        for c in &self.children {
146            if matches!(box_position(c), "absolute" | "fixed") {
147                continue;
148            }
149            let mb = c.dimensions.margin_box();
150            items.push((c, mb.x, mb.y, mb.y + mb.height));
151        }
152        if items.is_empty() {
153            return None;
154        }
155        // 最初の非空行のアイテム(最も小さい bottom より上に開始するアイテム群)を抽出する。
156        let first_bottom = items.iter().map(|it| it.3).min().unwrap_or(0);
157        let row_items: Vec<(&LayoutBox, i32, i32)> = items
158            .into_iter()
159            .filter(|it| it.2 < first_bottom)
160            .map(|(c, x, y, _)| (c, x, y))
161            .collect();
162        if row_items.is_empty() {
163            return None;
164        }
165        let parent_ai = box_style_value_ref(self, "align-items").unwrap_or("");
166        let is_item_first_bl = |c: &LayoutBox| -> bool {
167            let raw = match box_style_value_ref(c, "align-self").map(str::trim) {
168                Some(v) if !v.is_empty() && !v.eq_ignore_ascii_case("auto") => v,
169                _ => parent_ai,
170            };
171            is_first_baseline_align(raw)
172        };
173        let bl_pool: Vec<(&LayoutBox, i32, i32)> = row_items
174            .iter()
175            .copied()
176            .filter(|(c, _, _)| is_item_first_bl(c))
177            .collect();
178        let chosen = if !bl_pool.is_empty() {
179            bl_pool.iter().min_by_key(|it| it.1).map(|&(c, _, y)| (c, y))
180        } else {
181            row_items.iter().min_by_key(|it| it.1).map(|&(c, _, y)| (c, y))
182        };
183        chosen.map(|(c, mb_y)| (mb_y - self.dimensions.content.y) + c.item_baseline_from_margin_top())
184    }
185
186    /// マージン箱の上端から first baseline までの距離(flex / grid アイテム用)。
187    pub(crate) fn item_baseline_from_margin_top(&self) -> i32 {
188        let d = &self.dimensions;
189        let to_content = d.margin.top + d.border.top + d.padding.top;
190        match self.first_baseline_in_content() {
191            Some(b) => to_content + b,
192            // 合成: ボーダー箱の下端。
193            None => to_content + d.content.height + d.padding.bottom + d.border.bottom,
194        }
195    }
196
197    /// グリッドアイテムの行軸(`align-items/self: baseline`)ベースライン(マージン箱論理上端からの距離)。
198    /// 縦書きおよび直交アイテムの合成ベースライン(CSS Align 3 §9.1)を扱う。
199    pub(crate) fn item_grid_baseline(&self, container_world: u8) -> i32 {
200        let d = &self.dimensions;
201        let to_content = d.margin.top + d.border.top + d.padding.top;
202        let under_bottom = to_content + d.content.height + d.padding.bottom + d.border.bottom;
203        let cw_vert = (container_world & 1) != 0;
204        let cw_vlr = cw_vert && (container_world & 2) == 0;
205        let iw = super::types::inherited_world_of(self);
206        let iw_vert = (iw & 1) != 0;
207        if iw_vert != cw_vert {
208            // 直交アイテム: コンテナの line-under 側の border-box 辺を合成ベースラインにする。
209            return if cw_vlr { d.margin.top } else { under_bottom };
210        }
211        if cw_vlr {
212            // vertical-lr 平行アイテム: 1行目上端から descent 側(テキストが無ければ border-box 左=上端)。
213            return match self.first_baseline_in_content_dir(true) {
214                Some(b) => to_content + b,
215                None => d.margin.top,
216            };
217        }
218        self.item_baseline_from_margin_top()
219    }
220
221    /// グリッドアイテムの列軸(`justify-items/self: baseline`)の `(グループ番号, 基準位置)`。
222    /// `grp = 0`: 論理左端基準、`grp = 1`: 右端基準(横書き内の `vertical-rl` 等)。
223    pub(crate) fn item_col_baseline(&self, container_world: u8) -> (u8, i32) {
224        let d = &self.dimensions;
225        let cw_vert = (container_world & 1) != 0;
226        let iw = super::types::inherited_world_of(self);
227        let iw_vert = (iw & 1) != 0;
228        let to_left = d.margin.left + d.border.left + d.padding.left;
229        let under_right = to_left + d.content.width + d.padding.right + d.border.right;
230        if !cw_vert {
231            if !iw_vert {
232                // 横書きコンテナ内の横書きアイテム: 左 border-box 辺を合成。
233                return (0, d.margin.left);
234            }
235            let iw_vrl = (iw & 2) != 0;
236            if iw_vrl {
237                // 横書き内の vertical-rl アイテム: 物理右端基準 (grp = 1)。
238                let from_right = match self.first_inflow_text_box() {
239                    Some((cx, _, cw, _, asc)) => {
240                        let right_in_c = d.content.width - (cx + cw);
241                        d.margin.right + d.border.right + d.padding.right + right_in_c + asc
242                    }
243                    None => {
244                        d.margin.right + d.border.right + d.padding.right + d.content.width + d.padding.left + d.border.left
245                    }
246                };
247                return (1, from_right);
248            }
249            // 横書き内の vertical-lr アイテム: 物理左端から descent 位置 (grp = 0)。
250            let from_left = match self.first_inflow_text_box() {
251                Some((cx, _, cw, _, asc)) => to_left + cx + (cw - asc),
252                None => d.margin.left,
253            };
254            return (0, from_left);
255        }
256        // 縦書きコンテナ: 論理 X 軸は物理上から下(+y)。
257        if iw_vert {
258            // 平行(縦書き)アイテム: 論理右端(=物理下端)が合成ベースライン。
259            return (0, under_right);
260        }
261        // 縦書きコンテナ内の横書きアイテム: 論理 X 方向に 1行目のテキストがある。
262        let from_left = match self.first_inflow_text_box() {
263            Some((cx, _, _, _, asc)) => to_left + cx + asc,
264            None => under_right,
265        };
266        (0, from_left)
267    }
268}
269
270impl<'a> LayoutBox<'a> {
271    /// 単一行 flex(横並び)のベースライン整列。`(各子の交差軸オフセット(対象外は -1), 最大 ascent, 行の交差サイズ)`。
272    /// ベースライン整列の項目が無ければ `None`。
273    pub(crate) fn flex_baseline_layout(&self, oof: &[bool], align_items: &str) -> Option<(Vec<i32>, i32, i32)> {
274        if !baseline_enabled() {
275            return None;
276        }
277        let items: Vec<usize> = (0..self.children.len()).filter(|&i| !oof.get(i).copied().unwrap_or(false)).collect();
278        let (asc, total) = self.flex_baseline_layout_of(&items, align_items).map(|(_, a, t)| (a, t))?;
279        let mut offs = alloc::vec![-1i32; self.children.len()];
280        for &i in &items {
281            let c = &self.children[i];
282            let al = box_align_self(c);
283            let al = al.as_deref().unwrap_or(align_items);
284            if is_baseline_align(al) {
285                offs[i] = (asc - c.item_baseline_from_margin_top()).max(0);
286            }
287        }
288        Some((offs, asc, total))
289    }
290
291    /// 指定した項目(行)のうちベースライン整列のものの `(項目数, 最大 ascent, 行の交差サイズ)`。
292    pub(crate) fn flex_baseline_layout_of(&self, items: &[usize], align_items: &str) -> Option<(usize, i32, i32)> {
293        let mut max_asc = 0i32;
294        let mut max_desc = 0i32;
295        let mut max_other = 0i32;
296        let mut n = 0usize;
297        for &i in items {
298            let c = &self.children[i];
299            let al = box_align_self(c);
300            let al = al.as_deref().unwrap_or(align_items);
301            let h = c.dimensions.margin_box().height;
302            if is_baseline_align(al) {
303                let b = c.item_baseline_from_margin_top();
304                max_asc = max_asc.max(b);
305                max_desc = max_desc.max(h - b);
306                n += 1;
307            } else {
308                max_other = max_other.max(h);
309            }
310        }
311        if n == 0 {
312            return None;
313        }
314        Some((n, max_asc, (max_asc + max_desc).max(max_other)))
315    }
316}