Skip to main content

atmos/os_lib/layout/
types.rs

1// 分割: layout.rs より機械的に移動(2026-07-16 リファクタ フェーズ4)。
2// ロジック不変。可視性のみ pub(crate) へ昇格し、親が pub(crate) use で再エクスポート。
3use super::*;
4
5pub(crate) static IMAGE_SIZE_CACHE: Mutex<Option<BTreeMap<String, (i32, i32)>>> = Mutex::new(None);
6
7/// 【2026-08-05】ネットワークから取得した画像の自然サイズを登録する。
8///
9/// `<img>` に `width`/`height` が無い場合、レイアウトは画像の自然サイズを
10/// 使うべきだが、`values.rs` はローカルファイルシステム(`src` が `/` 始まり)
11/// しか見ていなかった。ネットワーク画像は**既定の 400×200** に落ちるため、
12/// `App_Store_Badge_US-UK_135x40.svg`(本来 135×40)が
13/// 画面外へはみ出すほど大きく描かれていた。
14///
15/// デコード完了時にここへ登録し、次のレイアウトで拾わせる。
16pub fn register_image_natural_size(src: &str, w: i32, h: i32) {
17    let mut cache = IMAGE_SIZE_CACHE.lock();
18    if cache.is_none() {
19        *cache = Some(BTreeMap::new());
20    }
21    if let Some(ref mut c) = *cache {
22        c.insert(alloc::string::String::from(src), (w, h));
23    }
24}
25
26#[derive(Debug, Clone, Default)]
27pub struct Rect {
28    pub x: i32,
29    pub y: i32,
30    pub width: i32,
31    pub height: i32,
32}
33
34#[derive(Debug, Clone, Default)]
35pub struct EdgeSizes {
36    pub left: i32,
37    pub right: i32,
38    pub top: i32,
39    pub bottom: i32,
40}
41
42#[derive(Debug, Clone, Default)]
43pub struct Dimensions {
44    pub content: Rect,
45    pub padding: EdgeSizes,
46    pub border: EdgeSizes,
47    pub margin: EdgeSizes,
48}
49
50impl Dimensions {
51    /// パディングボックス(content + padding)。絶対配置の包含ブロックに使う。
52    pub fn padding_box(&self) -> Rect {
53        Rect {
54            x: self.content.x - self.padding.left,
55            y: self.content.y - self.padding.top,
56            width: self.content.width + self.padding.left + self.padding.right,
57            height: self.content.height + self.padding.top + self.padding.bottom,
58        }
59    }
60
61    pub fn margin_box(&self) -> Rect {
62        Rect {
63            x: self.content.x - self.padding.left - self.border.left - self.margin.left,
64            y: self.content.y - self.padding.top - self.border.top - self.margin.top,
65            width: self.content.width
66                + self.padding.left
67                + self.padding.right
68                + self.border.left
69                + self.border.right
70                + self.margin.left
71                + self.margin.right,
72            height: self.content.height
73                + self.padding.top
74                + self.padding.bottom
75                + self.border.top
76                + self.border.bottom
77                + self.margin.top
78                + self.margin.bottom,
79        }
80    }
81}
82
83// Clone: inline-flex の寸法計測で試し組みするため(2026-09-26)。
84#[derive(Clone)]
85pub struct LayoutBox<'a> {
86    pub dimensions: Dimensions,
87    pub box_type: BoxType<'a>,
88    pub children: Vec<LayoutBox<'a>>,
89    /// 文字ノードの先頭の空白(畳まれた 1 つ)を計測にも描画にも含めない印。
90    /// 行頭に来た文字(CSS Text 3 §4.1.2)と、flex/grid 直下の匿名アイテムの文字に立つ。
91    /// 【2026-10-14】従来は箱の幅だけ空白ぶん縮め、描画は空白込みで箱の左端から
92    /// 描いていたため、行頭の文字が空白 1 つぶん右へずれた(index.htm のロゴ「IoT」)。
93    pub trim_leading_space: bool,
94    /// このボックスを根とする部分木内の `LayoutBox` 総数(`build_layout_tree` でボトムアップ事前計算)。
95    pub subtree_boxes: u32,
96}
97
98#[derive(Clone, Copy)]
99pub enum BoxType<'a> {
100    BlockNode(&'a StyledNode<'a>),
101    InlineNode(&'a StyledNode<'a>),
102    InlineBlockNode(&'a StyledNode<'a>),
103    FlexNode(&'a StyledNode<'a>),
104    GridNode(&'a StyledNode<'a>),
105    TableNode(&'a StyledNode<'a>),
106    TableRowGroupNode(&'a StyledNode<'a>),
107    TableRowNode(&'a StyledNode<'a>),
108    TableCellNode(&'a StyledNode<'a>),
109    AnonymousBlock,
110}
111
112// 【2026-11-19】`default_display_for` は css のカスケードも使うので `css/cascade.rs` へ移した(css が layout に頼らないように)。
113pub(crate) use crate::os_lib::css::default_display_for;
114
115/// セルの colspan / rowspan を読む (HTML 属性)。1 未満や巨大値はクランプ。
116pub(crate) fn cell_spans(cell: &LayoutBox) -> (usize, usize) {
117    if let BoxType::TableCellNode(styled) = &cell.box_type {
118        if let NodeType::Element { attributes, .. } = &styled.node.node_type {
119            let cs = attributes
120                .get("colspan")
121                .and_then(|v| v.trim().parse::<usize>().ok())
122                .unwrap_or(1)
123                .clamp(1, 256);
124            let rs = attributes
125                .get("rowspan")
126                .and_then(|v| v.trim().parse::<usize>().ok())
127                .unwrap_or(1)
128                .clamp(1, 1024);
129            return (cs, rs);
130        }
131    }
132    (1, 1)
133}
134
135/// LayoutBox が表す要素のタグ名 (text ノードや AnonymousBlock は None)。
136pub(crate) fn box_tag_name<'a>(b: &LayoutBox<'a>) -> Option<&'a str> {
137    let styled = match &b.box_type {
138        BoxType::BlockNode(s)
139        | BoxType::InlineNode(s)
140        | BoxType::InlineBlockNode(s)
141        | BoxType::FlexNode(s)
142        | BoxType::GridNode(s)
143        | BoxType::TableNode(s)
144        | BoxType::TableRowGroupNode(s)
145        | BoxType::TableRowNode(s)
146        | BoxType::TableCellNode(s) => *s,
147        BoxType::AnonymousBlock => return None,
148    };
149    match &styled.node.node_type {
150        NodeType::Element { tag_name, .. } => Some(tag_name.as_str()),
151        NodeType::Text(_) => None,
152    }
153}
154
155/// LayoutBox が表す要素の CSS プロパティ値(flex の子サイズ判定用)。
156pub(crate) fn box_style_value<'a>(b: &LayoutBox<'a>, prop: &str) -> Option<String> {
157    let styled = match &b.box_type {
158        BoxType::BlockNode(s)
159        | BoxType::InlineNode(s)
160        | BoxType::InlineBlockNode(s)
161        | BoxType::FlexNode(s)
162        | BoxType::GridNode(s)
163        | BoxType::TableNode(s)
164        | BoxType::TableRowGroupNode(s)
165        | BoxType::TableRowNode(s)
166        | BoxType::TableCellNode(s) => *s,
167        BoxType::AnonymousBlock => return None,
168    };
169    styled.value(prop)
170}
171
172/// `box_style_value` の借用版(値を写さない。レイアウトの頻出経路用)。
173pub(crate) fn box_style_value_ref<'a>(b: &LayoutBox<'a>, prop: &str) -> Option<&'a str> {
174    match &b.box_type {
175        BoxType::BlockNode(s)
176        | BoxType::InlineNode(s)
177        | BoxType::InlineBlockNode(s)
178        | BoxType::FlexNode(s)
179        | BoxType::GridNode(s)
180        | BoxType::TableNode(s)
181        | BoxType::TableRowGroupNode(s)
182        | BoxType::TableRowNode(s)
183        | BoxType::TableCellNode(s) => s.value_ref(prop),
184        BoxType::AnonymousBlock => None,
185    }
186}
187
188/// 世界の論理→物理写像を通さない生値参照(`direction` 等の世界構築・比較用)。
189pub(crate) fn box_style_value_raw<'a>(b: &LayoutBox<'a>, prop: &str) -> Option<&'a str> {
190    match &b.box_type {
191        BoxType::BlockNode(s)
192        | BoxType::InlineNode(s)
193        | BoxType::InlineBlockNode(s)
194        | BoxType::FlexNode(s)
195        | BoxType::GridNode(s)
196        | BoxType::TableNode(s)
197        | BoxType::TableRowGroupNode(s)
198        | BoxType::TableRowNode(s)
199        | BoxType::TableCellNode(s) => s.value_raw(prop),
200        BoxType::AnonymousBlock => None,
201    }
202}
203
204/// 世界の論理→物理写像を通さない `direction: rtl` 判定(縦書き内の子の向き判定用)。
205pub(crate) fn box_is_rtl_raw(b: &LayoutBox) -> bool {
206    box_style_value_raw(b, "direction")
207        .map(|v| v.trim().eq_ignore_ascii_case("rtl"))
208        .unwrap_or(false)
209}
210
211/// LayoutBox が表す要素の計算済み font-size (px)。デフォルト 16.0。
212pub(crate) fn box_font_size(b: &LayoutBox) -> f32 {
213    box_style_value_ref(b, "font-size")
214        .and_then(parse_font_size_u32)
215        .unwrap_or(16) as f32
216}
217
218impl<'a> LayoutBox<'a> {
219    pub(crate) fn font_size(&self) -> f32 {
220        box_font_size(self)
221    }
222
223    /// W3C CSSOM View: 要素の padding box の幅 (px)。
224    pub fn client_width(&self) -> i32 {
225        self.dimensions.padding_box().width
226    }
227
228    /// W3C CSSOM View: 要素の padding box の高さ (px)。
229    pub fn client_height(&self) -> i32 {
230        self.dimensions.padding_box().height
231    }
232
233    /// W3C CSSOM View: 要素のパディングボックス基準での全コンテンツの最大右端・下端から、
234    /// スクロール可能領域の幅・高さを算出 (clientWidth / clientHeight 以上の値)。
235    /// 戻り値: (client_width, client_height, scroll_width, scroll_height)
236    pub fn scroll_dimensions(&self) -> (i32, i32, i32, i32) {
237        let cw = self.client_width();
238        let ch = self.client_height();
239        let pbox = self.dimensions.padding_box();
240
241        // 子孫要素の margin_box() の最大右端・下端を親の padding_box 原点基準で集計
242        let mut max_right = pbox.width;
243        let mut max_bottom = pbox.height;
244
245        fn collect_max_bounds(parent_pbox: &Rect, b: &LayoutBox, max_r: &mut i32, max_b: &mut i32) {
246            for child in &b.children {
247                let mbox = child.dimensions.margin_box();
248                let r = mbox.x + mbox.width - parent_pbox.x;
249                let b_edge = mbox.y + mbox.height - parent_pbox.y;
250                if r > *max_r {
251                    *max_r = r;
252                }
253                if b_edge > *max_b {
254                    *max_b = b_edge;
255                }
256                // 子要素がそれ自体 overflow: scroll/hidden のスクロールコンテナでない場合、
257                // さらにその子孫のはみ出しもこのコンテナのスクロール領域に寄与する。
258                let is_child_scroll = match &child.box_type {
259                    BoxType::BlockNode(s)
260                    | BoxType::InlineNode(s)
261                    | BoxType::InlineBlockNode(s)
262                    | BoxType::FlexNode(s)
263                    | BoxType::GridNode(s)
264                    | BoxType::TableNode(s)
265                    | BoxType::TableRowGroupNode(s)
266                    | BoxType::TableRowNode(s)
267                    | BoxType::TableCellNode(s) => {
268                        ["overflow", "overflow-x", "overflow-y"].iter().any(|k| {
269                            s.value_ref(k).is_some_and(|v| matches!(v.trim(), "hidden" | "scroll" | "auto"))
270                        })
271                    }
272                    BoxType::AnonymousBlock => false,
273                };
274                if !is_child_scroll {
275                    collect_max_bounds(parent_pbox, child, max_r, max_b);
276                }
277            }
278        }
279
280        collect_max_bounds(&pbox, self, &mut max_right, &mut max_bottom);
281
282        (cw, ch, max_right.max(cw), max_bottom.max(ch))
283    }
284
285    /// W3C CSSOM View: スクロール領域の幅 (px)。
286    pub fn scroll_width(&self) -> i32 {
287        self.scroll_dimensions().2
288    }
289
290    /// W3C CSSOM View: スクロール領域の高さ (px)。
291    pub fn scroll_height(&self) -> i32 {
292        self.scroll_dimensions().3
293    }
294}
295
296/// 指定プロパティが明示指定されているか(auto/空は未指定扱い)。
297pub(crate) fn box_has_explicit(b: &LayoutBox, prop: &str) -> bool {
298    box_style_value_ref(b, prop).is_some_and(|v| {
299        let t = v.trim();
300        !t.is_empty() && !t.eq_ignore_ascii_case("auto") && !calc_size_is_auto(t)
301    })
302}
303
304/// aspect-ratio の (num, den) を取得する。
305pub(crate) fn box_aspect_ratio(b: &LayoutBox) -> Option<(f32, f32)> {
306    box_style_value_ref(b, "aspect-ratio")
307        .and_then(parse_aspect_ratio)
308        .map(world_swap_ratio)
309}
310
311pub(crate) fn parse_svg_data_uri_ratio(src: &str) -> Option<(f32, f32)> {
312    let low = src.to_ascii_lowercase();
313    if !low.starts_with("data:image/svg+xml") {
314        return None;
315    }
316    let (_, body) = src.split_once(',')?;
317    // 簡易 URL デコード(%3C %3E %20 %22 %27 %2F %3D %3A 等)
318    let mut dec = String::with_capacity(body.len());
319    let b = body.as_bytes();
320    let mut i = 0;
321    while i < b.len() {
322        if b[i] == b'%' && i + 2 < b.len() {
323            if let (Some(h), Some(l)) = ((b[i + 1] as char).to_digit(16), (b[i + 2] as char).to_digit(16)) {
324                dec.push(((h * 16 + l) as u8) as char);
325                i += 3;
326                continue;
327            }
328        }
329        dec.push(b[i] as char);
330        i += 1;
331    }
332    let find_attr = |name: &str| -> Option<f32> {
333        let pat = alloc::format!("{}=", name);
334        let p = dec.find(&pat)?;
335        let rest = dec.get(p + pat.len()..)?.trim_start();
336        let q = rest.chars().next()?;
337        let val = if q == '"' || q == '\'' {
338            rest.strip_prefix(q)?.split_once(q)?.0
339        } else {
340            rest.split(|c: char| c.is_whitespace() || c == '>' || c == '/').next()?
341        };
342        val.trim().trim_end_matches("px").parse::<f32>().ok().filter(|x| *x > 0.0)
343    };
344    if let (Some(w), Some(h)) = (find_attr("width"), find_attr("height")) {
345        return Some((w, h));
346    }
347    if let Some(p) = dec.find("viewBox=") {
348        if let Some(rest) = dec.get(p + 8..).map(str::trim_start) {
349            if let Some(q) = rest.chars().next() {
350                if q == '"' || q == '\'' {
351                    if let Some((inner, _)) = rest.strip_prefix(q).and_then(|s| s.split_once(q)) {
352                        let nums: Vec<f32> = inner
353                            .split(|c: char| c == ',' || c.is_whitespace())
354                            .filter_map(|t| t.parse::<f32>().ok())
355                            .collect();
356                        if let [_, _, w, h] = nums.as_slice() {
357                            if *w > 0.0 && *h > 0.0 {
358                                return Some((*w, *h));
359                            }
360                        }
361                    }
362                }
363            }
364        }
365    }
366    None
367}
368
369/// 置換要素(`img` / `canvas`)の自然サイズから固有アスペクト比 `(rw, rh)` を返す。
370pub(crate) fn box_intrinsic_ratio(b: &LayoutBox) -> Option<(f32, f32)> {
371    let node = match &b.box_type {
372        BoxType::InlineNode(n) | BoxType::InlineBlockNode(n) | BoxType::BlockNode(n) => *n,
373        _ => return None,
374    };
375    if let NodeType::Element { tag_name, attributes, .. } = &node.node.node_type {
376        if tag_name == "img" {
377            if let Some(src) = attributes.get("src") {
378                if let Some((w, h)) = IMAGE_SIZE_CACHE.lock().as_ref().and_then(|c| c.get(src).copied()) {
379                    if w > 0 && h > 0 {
380                        return Some(world_swap_ratio((w as f32, h as f32)));
381                    }
382                }
383                if let Some((w, h)) = parse_svg_data_uri_ratio(src) {
384                    return Some(world_swap_ratio((w, h)));
385                }
386            }
387            let aw = attributes.get("width").and_then(|v| v.trim().parse::<f32>().ok()).filter(|&x| x > 0.0);
388            let ah = attributes.get("height").and_then(|v| v.trim().parse::<f32>().ok()).filter(|&x| x > 0.0);
389            if let (Some(w), Some(h)) = (aw, ah) {
390                return Some(world_swap_ratio((w, h)));
391            }
392        } else if tag_name == "canvas" {
393            let aw = attributes.get("width").and_then(|v| v.trim().parse::<f32>().ok()).filter(|&x| x > 0.0).unwrap_or(300.0);
394            let ah = attributes.get("height").and_then(|v| v.trim().parse::<f32>().ok()).filter(|&x| x > 0.0).unwrap_or(150.0);
395            return Some(world_swap_ratio((aw, ah)));
396        }
397    }
398    None
399}
400
401/// 縦書きの世界では aspect-ratio(物理の 幅 / 高さ)を論理(inline / block = 高さ / 幅)へ入れ替える。
402#[inline]
403pub(crate) fn world_swap_ratio(r: (f32, f32)) -> (f32, f32) {
404    if crate::os_lib::css::CUR_WORLD.load(AtomicOrdering::Relaxed) != 0 {
405        (r.1, r.0)
406    } else {
407        r
408    }
409}
410
411/// flex アイテムの flex-grow 係数(小数対応)。
412pub(crate) fn box_flex_grow_f32(b: &LayoutBox) -> f32 {
413    if let Some(g) = box_style_value_ref(b, "flex-grow") {
414        return g.trim().parse::<f32>().unwrap_or(0.0).max(0.0);
415    }
416    if let Some(f) = box_style_value_ref(b, "flex") {
417        let t = f.trim();
418        if t.eq_ignore_ascii_case("none") || t.eq_ignore_ascii_case("initial") {
419            return 0.0;
420        }
421        if t.eq_ignore_ascii_case("auto") {
422            return 1.0; // flex:auto = 1 1 auto
423        }
424        if let Some(first) = t.split_whitespace().next() {
425            return first.parse::<f32>().unwrap_or(0.0).max(0.0);
426        }
427    }
428    0.0
429}
430
431pub(crate) fn box_flex_grow(b: &LayoutBox) -> i32 {
432    box_flex_grow_f32(b) as i32
433}
434
435/// flex アイテムの flex-shrink 係数(`flex-shrink` 優先、無ければ `flex` ショートハンドの
436/// 2 番目、無指定は 1 = 既定で縮小可)。`flex:none` は 0、`flex:N`(単一数値)は 1。
437/// トークンが `flex` ショートハンドの basis に使える長さ値(px/%/em/rem/vh/vw)かどうかを
438/// 判定する。以前は `px`/`%`/`em` の3種のみ対応しており、`flex: 1 40vw` のような
439/// vw/vh/rem 単位の basis が length として認識されず、`box_flex_shrink` では誤って
440/// shrink の数値パースに回されて(失敗し既定値1にフォールバック)、`box_flex_basis` では
441/// 該当トークンが見つからず basis が丸ごと失われる、という実害のあるバグがあった
442/// (`transition`/`animation` の時間値誤分類と同種の「対応単位の一部だけを見る」バグ)。
443/// 末尾を剥がした残りが実際に数値としてパースできることまで確認する。
444pub(crate) fn is_flex_length_token(tok: &str) -> bool {
445    for suffix in ["px", "%", "rem", "em", "vh", "vw"] {
446        if tok.len() > suffix.len() {
447            let (head, tail) = tok.split_at(tok.len() - suffix.len());
448            if tail.eq_ignore_ascii_case(suffix) && head.trim().parse::<f32>().is_ok() {
449                return true;
450            }
451        }
452    }
453    false
454}
455
456pub(crate) fn box_flex_shrink_f32(b: &LayoutBox) -> f32 {
457    if let Some(s) = box_style_value_ref(b, "flex-shrink") {
458        return s.trim().parse::<f32>().unwrap_or(1.0).max(0.0);
459    }
460    if let Some(f) = box_style_value_ref(b, "flex") {
461        let t = f.trim();
462        if t.eq_ignore_ascii_case("none") {
463            return 0.0; // flex:none = 0 0 auto
464        }
465        if t.eq_ignore_ascii_case("initial") {
466            return 1.0; // flex:initial = 0 1 auto
467        }
468        if t.eq_ignore_ascii_case("auto") {
469            return 1.0; // flex:auto = 1 1 auto
470        }
471        // `flex: <grow> <shrink> <basis>` の 2 番目があれば採用。
472        let mut it = t.split_whitespace();
473        let _first = it.next();
474        if let Some(second) = it.next() {
475            // 2 番目が単位付き(basis)なら shrink 省略 → 既定 1。
476            if !is_flex_length_token(second) && !second.eq_ignore_ascii_case("auto") {
477                return second.parse::<f32>().unwrap_or(1.0).max(0.0);
478            }
479        }
480        // `flex: N`(単一数値)は 1 1 0 相当 → shrink=1。
481        return 1.0;
482    }
483    1.0
484}
485
486pub(crate) fn box_flex_shrink(b: &LayoutBox) -> i32 {
487    box_flex_shrink_f32(b) as i32
488}
489
490/// flex/grid アイテムの `order`(描画順の並び替え)。未指定/不正は 0。負値可。
491pub(crate) fn box_order(b: &LayoutBox) -> i32 {
492    box_style_value_ref(b, "order")
493        .and_then(|v| v.trim().parse::<i32>().ok())
494        .unwrap_or(0)
495}
496
497/// flex アイテムの flex-basis(主軸初期サイズ)。`flex-basis` 優先、無ければ `flex`
498/// ショートハンドの長さトークン(px/%)。`auto`/`content`/未指定は None(width/height に従う)。
499/// `main_size` は % 解決の基準(コンテナ主軸長)。
500/// flex-basis が `%`、または `flex: <number>` 由来(`0%` 相当)か。主軸方向の確定した長さが無い
501/// コンテナ(高さ auto の列)では `content` として扱う(CSS Flexbox §7.2.3)。
502pub(crate) fn box_flex_basis_is_percentage(b: &LayoutBox) -> bool {
503    if let Some(v) = box_style_value_ref(b, "flex-basis") {
504        let t = v.trim();
505        return t.ends_with('%') && !t.contains('(');
506    }
507    if let Some(f) = box_style_value_ref(b, "flex") {
508        let t = f.trim();
509        if t.is_empty() {
510            return false;
511        }
512        if t.split_whitespace().all(|tok| tok.parse::<f32>().is_ok()) {
513            return true;
514        }
515        return t.split_whitespace().any(|tok| tok.ends_with('%') && !tok.contains('('));
516    }
517    false
518}
519
520pub(crate) fn box_flex_basis(b: &LayoutBox, main_size: i32) -> Option<i32> {
521    let font_px = box_font_size(b);
522    // 明示 flex-basis を最優先。
523    if let Some(v) = box_style_value_ref(b, "flex-basis") {
524        let t = v.trim();
525        if t.is_empty() || t.eq_ignore_ascii_case("auto") || t.eq_ignore_ascii_case("content") {
526            return None;
527        }
528        if t.eq_ignore_ascii_case("min-content") {
529            return Some(b.block_intrinsic_widths().0);
530        }
531        if t.eq_ignore_ascii_case("max-content") {
532            return Some(b.block_intrinsic_widths().1);
533        }
534        if t.eq_ignore_ascii_case("fit-content") {
535            let (minc, maxc) = b.block_intrinsic_widths();
536            return Some(maxc.min(main_size.max(0)).max(minc));
537        }
538        if t.len() >= 13
539            && t.get(..12).is_some_and(|h| h.eq_ignore_ascii_case("fit-content("))
540            && t.ends_with(')')
541        {
542            let fit = t.get(12..t.len() - 1).unwrap_or("");
543            let limit = resolve_basis_len_with_font(fit, main_size, font_px).unwrap_or(main_size);
544            let (minc, maxc) = b.block_intrinsic_widths();
545            return Some(maxc.min(limit.max(0)).max(minc));
546        }
547        return resolve_basis_len_with_font(t, main_size, font_px);
548    }
549    // flex ショートハンドの第3トークン(長さ)から basis を拾う。
550    if let Some(f) = box_style_value_ref(b, "flex") {
551        let t = f.trim();
552        if t.eq_ignore_ascii_case("none")
553            || t.eq_ignore_ascii_case("auto")
554            || t.eq_ignore_ascii_case("initial")
555        {
556            return None; // basis=auto 相当
557        }
558        // `flex: <grow> <shrink>? <basis>?` の末尾トークンが長さなら basis。
559        for tok in t.split_whitespace() {
560            if tok.eq_ignore_ascii_case("min-content") {
561                return Some(b.block_intrinsic_widths().0);
562            }
563            if tok.eq_ignore_ascii_case("max-content") {
564                return Some(b.block_intrinsic_widths().1);
565            }
566            if tok.eq_ignore_ascii_case("fit-content") {
567                let (minc, maxc) = b.block_intrinsic_widths();
568                return Some(maxc.min(main_size.max(0)).max(minc));
569            }
570            if is_flex_length_token(tok) {
571                return resolve_basis_len_with_font(tok, main_size, font_px);
572            }
573        }
574        // `flex: N` / `flex: N M`(数値のみ)は basis=0。
575        if !t.is_empty() && t.split_whitespace().all(|tok| tok.parse::<f32>().is_ok()) {
576            return Some(0);
577        }
578    }
579    None
580}
581
582/// flex-basis のトークン("40px" / "25%" / "2em")を px へ解決する。
583/// `font_px` は要素自身の算出フォントサイズ(`em` 単位の計算に使用)。
584pub(crate) fn resolve_basis_len_with_font(tok: &str, main_size: i32, font_px: f32) -> Option<i32> {
585    let t = tok.trim();
586    if let Some(p) = t.strip_suffix('%') {
587        return p
588            .trim()
589            .parse::<f32>()
590            .ok()
591            .map(|pct| round_f32_to_i32(main_size as f32 * pct / 100.0).max(0));
592    }
593    if let Some(num) = t.strip_suffix("em") {
594        return num
595            .trim()
596            .parse::<f32>()
597            .ok()
598            .map(|v| round_f32_to_i32(v * font_px).max(0));
599    }
600    parse_px_like(t).map(|v| v.max(0))
601}
602
603pub(crate) fn resolve_basis_len(tok: &str, main_size: i32) -> Option<i32> {
604    resolve_basis_len_with_font(tok, main_size, 16.0)
605}
606
607/// flex アイテムの align-self(個別交差軸整列)。未指定/auto なら None(コンテナの align-items に従う)。
608pub(crate) fn box_align_self(b: &LayoutBox) -> Option<String> {
609    box_style_value_ref(b, "align-self").and_then(|v| {
610        let t = v.trim();
611        if t.is_empty() || t.eq_ignore_ascii_case("auto") {
612            None
613        } else {
614            Some(t.to_lowercase())
615        }
616    })
617}
618
619/// grid アイテムの整列値を解決する。`self_prop`(justify-self/align-self)が
620/// auto/未指定なら、コンテナの `items_default`(justify-items/align-items の値)へ委譲。
621/// 返り値を正規化: "start"/"end"/"center"/"stretch"。`flex-start`/`flex-end`/`self-start`/
622/// `self-end` も start/end に正規化する。既定は stretch。
623pub(crate) fn is_replaced_element(b: &LayoutBox) -> bool {
624    let node = match &b.box_type {
625        BoxType::InlineNode(n) | BoxType::InlineBlockNode(n) | BoxType::BlockNode(n) => *n,
626        _ => return false,
627    };
628    matches!(
629        &node.node.node_type,
630        NodeType::Element { tag_name, .. }
631            if matches!(
632                tag_name.as_str(),
633                "img" | "video" | "canvas" | "iframe" | "embed" | "object" | "svg"
634            )
635    )
636}
637
638/// `safe` / `unsafe` 接頭辞を除いた整列キーワード。
639pub(crate) fn strip_overflow_kw(raw: &str) -> &str {
640    let t = raw.trim();
641    for kw in ["unsafe", "safe"] {
642        if let Some(rest) = t.strip_prefix(kw) {
643            if rest.starts_with(char::is_whitespace) {
644                return rest.trim_start();
645            }
646        }
647    }
648    t
649}
650
651/// 整列指定が `safe` 付きか。
652pub(crate) fn is_safe_align(raw: &str) -> bool {
653    let t = raw.trim();
654    t.strip_prefix("safe").is_some_and(|r| r.starts_with(char::is_whitespace))
655}
656
657pub(crate) fn grid_item_align(b: &LayoutBox, self_prop: &str, items_default: &str) -> &'static str {
658    let raw = match box_style_value_ref(b, self_prop) {
659        Some(v) => {
660            let t = v.trim();
661            if t.is_empty() || t.eq_ignore_ascii_case("auto") {
662                items_default.trim()
663            } else {
664                t
665            }
666        }
667        None => items_default.trim(),
668    };
669    let raw = strip_overflow_kw(raw);
670    if raw.eq_ignore_ascii_case("center") {
671        "center"
672    } else if raw.eq_ignore_ascii_case("end")
673        || raw.eq_ignore_ascii_case("flex-end")
674        || raw.eq_ignore_ascii_case("self-end")
675    {
676        "end"
677    } else if raw.eq_ignore_ascii_case("start")
678        || raw.eq_ignore_ascii_case("flex-start")
679        || raw.eq_ignore_ascii_case("self-start")
680        || raw.eq_ignore_ascii_case("left")
681        || raw.eq_ignore_ascii_case("right")
682    {
683        // `left` / `right` は align-* 軸(縦軸想定)では仕様上無効で `start` フォールバック。
684        "start"
685    } else if raw.eq_ignore_ascii_case("normal") || raw.is_empty() {
686        if is_replaced_element(b) || box_aspect_ratio(b).is_some() {
687            "start"
688        } else {
689            "stretch"
690        }
691    } else {
692        "stretch"
693    }
694}
695
696/// 継承値ベースで要素の世界ビット列(`writing_mode::world_of` と同形式)を返す。
697pub(crate) fn inherited_world_of(b: &LayoutBox) -> u8 {
698    let wm = box_style_value_raw(b, "writing-mode").map(str::trim).unwrap_or("");
699    let (fb, fi) = match wm {
700        "vertical-rl" | "tb-rl" | "sideways-rl" => (true, false),
701        "vertical-lr" | "tb-lr" => (false, false),
702        "sideways-lr" => (false, true),
703        _ => return 0,
704    };
705    let rtl = box_is_rtl_raw(b);
706    1 | ((fb as u8) << 1) | (((fi ^ rtl) as u8) << 2)
707}
708
709/// グリッドコンテナの論理軸(`is_justify=true`: 列/インライン軸, `false`: 行/ブロック軸)に対する
710/// アイテムの整列キーワード(`"start" | "end" | "center" | "stretch"`)を返す。
711/// `self-start` / `self-end` / `left` / `right` をコンテナ・子双方の `writing-mode` と `direction` から解決する。
712pub(crate) fn resolve_grid_axis_align(
713    child: &LayoutBox,
714    self_prop: &str,
715    items_default: &str,
716    container_world: u8,
717    container_rtl_h: bool,
718    is_justify: bool,
719) -> &'static str {
720    let raw = match box_style_value_ref(child, self_prop).map(str::trim) {
721        Some(v) if !v.is_empty() && !v.eq_ignore_ascii_case("auto") => v,
722        _ => items_default.trim(),
723    };
724    let raw = strip_overflow_kw(raw);
725    let p_start: usize = if is_justify {
726        if container_world == 0 {
727            if container_rtl_h { 1 } else { 3 }
728        } else {
729            crate::os_lib::css::world_phys_side(container_world, 3)
730        }
731    } else if container_world == 0 {
732        0
733    } else {
734        crate::os_lib::css::world_phys_side(container_world, 0)
735    };
736    let p_end = (p_start + 2) % 4;
737    if raw.eq_ignore_ascii_case("self-start") || raw.eq_ignore_ascii_case("self-end") {
738        let cw = inherited_world_of(child);
739        let c_in_start = if cw == 0 {
740            if box_is_rtl_raw(child) { 1 } else { 3 }
741        } else {
742            crate::os_lib::css::world_phys_side(cw, 3)
743        };
744        let c_bl_start = if cw == 0 {
745            0
746        } else {
747            crate::os_lib::css::world_phys_side(cw, 0)
748        };
749        let c_start = if c_in_start == p_start || c_in_start == p_end {
750            c_in_start
751        } else {
752            c_bl_start
753        };
754        let is_self_start = raw.eq_ignore_ascii_case("self-start");
755        let same_dir = c_start == p_start;
756        return if is_self_start == same_dir { "start" } else { "end" };
757    }
758    if raw.eq_ignore_ascii_case("left") || raw.eq_ignore_ascii_case("right") {
759        if !is_justify {
760            // align-self/items における left/right は仕様上無効 -> start フォールバック
761            return "start";
762        }
763        let target = if (container_world & 1) != 0 {
764            if raw.eq_ignore_ascii_case("left") { 0 } else { 2 }
765        } else if raw.eq_ignore_ascii_case("left") {
766            3
767        } else {
768            1
769        };
770        return if p_start == target {
771            "start"
772        } else if p_end == target || raw.eq_ignore_ascii_case("right") {
773            "end"
774        } else {
775            "start"
776        };
777    }
778    if raw.eq_ignore_ascii_case("center") {
779        "center"
780    } else if raw.eq_ignore_ascii_case("end") || raw.eq_ignore_ascii_case("flex-end") {
781        "end"
782    } else if raw.eq_ignore_ascii_case("start")
783        || raw.eq_ignore_ascii_case("flex-start")
784        || super::baseline::is_baseline_align(raw)
785    {
786        "start"
787    } else if raw.eq_ignore_ascii_case("normal") || raw.is_empty() {
788        if is_replaced_element(child) {
789            "start"
790        } else {
791            "stretch"
792        }
793    } else {
794        "stretch"
795    }
796}
797