Skip to main content

atmos/os_lib/layout/
tree.rs

1// 分割: layout.rs より機械的に移動(2026-07-16 リファクタ フェーズ4)。
2// ロジック不変。可視性のみ pub(crate) へ昇格し、親が pub(crate) use で再エクスポート。
3use super::*;
4
5// --- 不変サブツリーのブロック配置スキップ(LAYOUT_MEMO) ---------------------
6// DOM 変更・ホバー・スクロール後の再レイアウトにおいて、入力内容(DOM 部分木+算出スタイル)と
7// 包含ブロック条件(幅・基準高さ・ビューポート・フォント世代)が変わらないサブツリーについて、
8// 前回確定した各ボックスの `(Dimensions, trim_leading_space)` を `(dx, dy)` 平行移動のみで
9// 復元し、ブロック/flex/grid/table/inline の再配置およびテキスト折り返し計測を丸ごと省く。
10
11#[derive(Clone, Copy, PartialEq, Eq, PartialOrd, Ord)]
12struct LayoutMemoKey {
13    subtree_hash: (u64, u64),
14    box_flags: u8,
15    cb_w: i32,
16    cb_h_key: i32,
17    pct_base_h: i32,
18    forced_h: i32,
19    env_hash: u64,
20}
21
22struct LayoutMemoEntry {
23    cb_x: i32,
24    cb_y_flow: i32,
25    boxes: Vec<(Dimensions, bool)>,
26    last_used: u64,
27}
28
29struct LayoutMemo {
30    map: BTreeMap<LayoutMemoKey, LayoutMemoEntry>,
31    hits: u64,
32    misses: u64,
33    tick: u64,
34}
35
36impl LayoutMemo {
37    const MAX_ENTRIES: usize = 2048;
38    const MAX_SUBTREE_BOXES: usize = 8192;
39
40    const fn new() -> Self {
41        Self {
42            map: BTreeMap::new(),
43            hits: 0,
44            misses: 0,
45            tick: 0,
46        }
47    }
48}
49
50static GLOBAL_LAYOUT_MEMO: Mutex<LayoutMemo> = Mutex::new(LayoutMemo::new());
51static GRID_INTRINSIC_AVAIL_W: AtomicI32 = AtomicI32::new(-1);
52static NEXT_DEFINITE_H: AtomicI32 = AtomicI32::new(-1);
53static IN_FLEX_OR_GRID_ITEM: AtomicBool = AtomicBool::new(false);
54
55/// レイアウト使い回し表を空にし、統計カウンタをリセットする。
56pub fn clear_layout_memo() {
57    let mut g = GLOBAL_LAYOUT_MEMO.lock();
58    g.map.clear();
59    g.hits = 0;
60    g.misses = 0;
61    g.tick = 0;
62}
63
64/// レイアウト使い回し表の統計 `(hits, misses, entries)` を返す。
65pub fn layout_memo_stats() -> (u64, u64, usize) {
66    let g = GLOBAL_LAYOUT_MEMO.lock();
67    (g.hits, g.misses, g.map.len())
68}
69
70fn current_layout_env_hash() -> u64 {
71    let vw = VIEWPORT_HINT_W.load(AtomicOrdering::Relaxed) as u32 as u64;
72    let vh = VIEWPORT_HINT_H.load(AtomicOrdering::Relaxed) as u32 as u64;
73    let rem = crate::os_lib::css::units::root_font_px().to_bits() as u64;
74    let fgen = CUSTOM_FONT_GEN.load(AtomicOrdering::Relaxed) as u64;
75    let mut h = 0xcbf2_9ce4_8422_2325u64;
76    for v in [vw, vh, rem, fgen] {
77        h = (h ^ v).wrapping_mul(0x0000_0100_0000_01b3);
78    }
79    h
80}
81
82/// このノード自身のレイアウトが(`cb_y_flow` 以外で)`containing_block.content.height` を
83/// 参照しうるかを判定する。該当しない場合、`cb_h_key` を 0 に正規化することで、
84/// 先行する兄弟ブロックの高さ変化で `y_cursor` がずれても後続の不変兄弟ブロックが
85/// そのまま `LAYOUT_MEMO` にヒットして `(dx, dy)` 平行移動だけで配置完了できる。
86fn node_uses_cb_height(node: &StyledNode) -> bool {
87    const PROPS: [&str; 5] = [
88        "height",
89        "min-height",
90        "max-height",
91        "grid-template-rows",
92        "grid-auto-rows",
93    ];
94    for p in PROPS {
95        if let Some(v) = node.value_ref(p) {
96            if v.contains('%') || v.contains('(') {
97                return true;
98            }
99        }
100    }
101    false
102}
103
104impl<'a> StyledNode<'a> {
105    /// このスタイル済みサブツリーの特徴ハッシュ `(h0, h1)` と、サブツリー単位の
106    /// レイアウト再利用(`LAYOUT_MEMO`)が可能か `can_memo` を返す。
107    pub(crate) fn layout_subtree_info(&self) -> (u64, u64, bool) {
108        if let Some(cached) = self.layout_subtree_cache.get() {
109            return cached;
110        }
111        let mut h = crate::os_lib::css::style_memo::KeyHasher::new();
112        let mut can_memo = true;
113        let mut has_unloaded_local_img = false;
114
115        match &self.node.node_type {
116            NodeType::Element {
117                tag_name,
118                attributes,
119                classes,
120                id,
121            } => {
122                h.u64(1);
123                h.bytes(tag_name.as_bytes());
124                h.bytes(id.as_deref().unwrap_or("").as_bytes());
125                h.u64(classes.len() as u64);
126                for c in classes {
127                    h.bytes(c.as_bytes());
128                }
129                h.u64(attributes.len() as u64);
130                for (k, v) in attributes {
131                    h.bytes(k.as_bytes());
132                    h.bytes(v.as_bytes());
133                }
134                if tag_name == "img" {
135                    if let Some(src) = attributes.get("src") {
136                        let s = src.trim();
137                        let img_sz = IMAGE_SIZE_CACHE
138                            .lock()
139                            .as_ref()
140                            .and_then(|c| c.get(s).copied());
141                        if let Some((w, ih)) = img_sz {
142                            h.u64(1);
143                            h.u64(w as u64);
144                            h.u64(ih as u64);
145                        } else {
146                            h.u64(0);
147                            if s.starts_with('/') {
148                                can_memo = false;
149                                has_unloaded_local_img = true;
150                            }
151                        }
152                    }
153                }
154            }
155            NodeType::Text(t) => {
156                h.u64(2);
157                h.bytes(t.as_bytes());
158            }
159        }
160
161        h.u64(self.specified_values.len() as u64);
162        for (k, v) in self.specified_values.iter() {
163            h.bytes(k.as_bytes());
164            h.bytes(v.as_bytes());
165            if k == "position" || k == "__before_position" || k == "__after_position" {
166                let p = v.trim();
167                if p.eq_ignore_ascii_case("absolute") || p.eq_ignore_ascii_case("fixed") {
168                    can_memo = false;
169                }
170            }
171        }
172
173        h.u64(self.children.len() as u64);
174        for child in &self.children {
175            let (ch0, ch1, c_ok) = child.layout_subtree_info();
176            h.key((ch0, ch1));
177            if !c_ok {
178                can_memo = false;
179            }
180        }
181
182        let (h0, h1) = h.finish();
183        let res = (h0, h1, can_memo);
184        if !has_unloaded_local_img {
185            self.layout_subtree_cache.set(Some(res));
186        }
187        res
188    }
189}
190
191/// 計算量: **O(N × D)** — N はスタイル済みノード数、D は
192/// テキストを含むノードでの行分割コスト(文字数に比例)。
193///
194/// ブロック整形は 1 パスだが、flex / grid コンテナは子の寸法を決めるのに
195/// **子を 2 回走査**する(伸長・収縮の分配)。入れ子の深さぶん掛かるため
196/// 深いフレックス入れ子では定数倍が増える。
197///
198/// 実測(sugi-lab.net: N=358): 48〜89 tick。
199/// `style_tree`(291 tick)の 1/4 以下で、**レイアウトの支配項ではない**。
200/// レイアウトの長いループの止める確かめ(`window_mgr::layout_poll`。2026-11-18、TODO R2 (b) ②・(d) ①)。
201/// 真ならこのタブだけを止める合図が来ている(残りの箱を組まずに戻ってよい)。ホストの試験では何もしない。
202#[inline]
203fn layout_poll() -> bool {
204    #[cfg(target_os = "none")]
205    return crate::kernel::window_mgr::layout_poll();
206    #[cfg(not(target_os = "none"))]
207    false
208}
209
210/// このタブだけを止める合図が来ているか(確かめは呼ばない。使い回しの表に途中までの結果を入れないため)。
211#[inline]
212fn layout_aborting() -> bool {
213    #[cfg(target_os = "none")]
214    return crate::kernel::window_mgr::layout_aborting();
215    #[cfg(not(target_os = "none"))]
216    false
217}
218
219/// 絶対配置の子の `justify-self`/`align-self`(`auto`・`normal`・`stretch` 以外)を
220/// `"start" | "center" | "end"` で返す(コンテナの inline 軸基準。`left`/`right`・`self-*`・`last baseline` を解決)。
221/// 埋める(`stretch`/`normal`/`auto`/指定なし)なら `None`。
222fn abs_axis_align(child: &LayoutBox, prop: &str, cb_rtl: bool, is_justify: bool) -> Option<&'static str> {
223    let raw = box_style_value_ref(child, prop).map(str::trim)?;
224    if raw.is_empty() || raw.eq_ignore_ascii_case("auto") || raw.eq_ignore_ascii_case("normal") || raw.eq_ignore_ascii_case("stretch") {
225        return None;
226    }
227    // `last baseline` は end 側へフォールバックする(first baseline は start)。
228    if raw.as_bytes().get(..13).is_some_and(|b| b.eq_ignore_ascii_case(b"last baseline")) {
229        return Some("end");
230    }
231    match resolve_grid_axis_align(child, prop, "", 0, cb_rtl, is_justify) {
232        "stretch" => None,
233        a => Some(a),
234    }
235}
236
237pub fn layout_tree<'a>(node: &'a StyledNode<'a>, containing_block: Dimensions) -> LayoutBox<'a> {
238    // 初期包含ブロック = ビューポート。absolute(positioned祖先なし)と fixed の基準。
239    let icb = &containing_block.content;
240    let icb_h = if icb.height > 0 {
241        icb.height
242    } else {
243        VIEWPORT_HINT_H.load(AtomicOrdering::Relaxed)
244    };
245    abs_cb_set(icb.x, icb.y, icb.width, icb_h);
246    fixed_cb_set(None);
247    VP_ORIGIN_X.store(icb.x, AtomicOrdering::Relaxed);
248    VP_ORIGIN_Y.store(icb.y, AtomicOrdering::Relaxed);
249    // 初期包含ブロック(ビューポート)の高さをパーセント高さの基準として設定(CSS 2.1 §10.5)
250    let _pct_h_guard = PctBaseHGuard::set(icb_h);
251    let mut layout_box = build_layout_tree(node);
252    layout_box.layout(containing_block);
253    layout_box
254}
255
256fn normalize_multi_display(v: &str) -> &str {
257    let t = v.trim();
258    if !t.contains(char::is_whitespace) {
259        return t;
260    }
261    let mut toks = t.split_whitespace();
262    let a = toks.next().unwrap_or("");
263    let b = toks.next().unwrap_or("");
264    if toks.next().is_some() {
265        return t;
266    }
267    let (a_low, b_low) = (a.to_ascii_lowercase(), b.to_ascii_lowercase());
268    let (p1, p2) = (a_low.as_str(), b_low.as_str());
269    match (p1, p2) {
270        ("inline", "grid-lanes") | ("grid-lanes", "inline") | ("inline", "masonry") | ("masonry", "inline") => "inline-grid-lanes",
271        ("block", "grid-lanes") | ("grid-lanes", "block") | ("block", "masonry") | ("masonry", "block") => "grid-lanes",
272        ("inline", "grid") | ("grid", "inline") => "inline-grid",
273        ("block", "grid") | ("grid", "block") => "grid",
274        ("inline", "flex") | ("flex", "inline") => "inline-flex",
275        ("block", "flex") | ("flex", "block") => "flex",
276        ("inline", "flow-root") | ("flow-root", "inline") => "inline-block",
277        ("block", "flow") | ("flow", "block") | ("block", "flow-root") | ("flow-root", "block") => "block",
278        ("inline", "flow") | ("flow", "inline") => "inline",
279        ("inline", "table") | ("table", "inline") => "inline-table",
280        ("block", "table") | ("table", "block") => "table",
281        _ => t,
282    }
283}
284
285pub(crate) fn resolved_display<'a>(node: &'a StyledNode<'a>) -> &'a str {
286    match &node.node.node_type {
287        NodeType::Element { tag_name, .. } => node
288            .value_ref("display")
289            .map(normalize_multi_display)
290            .unwrap_or_else(|| default_display_for(tag_name)),
291        NodeType::Text(_) => "inline",
292    }
293}
294
295pub(crate) fn build_layout_tree<'a>(node: &'a StyledNode<'a>) -> LayoutBox<'a> {
296    let box_type = match &node.node.node_type {
297        NodeType::Element { .. } => {
298            let mut display = resolved_display(node);
299            // CSS Display §2.7: position:absolute/fixed の箱は blockify される(inline → block 等)。
300            if matches!(display, "inline" | "inline-block" | "inline-flex" | "inline-grid" | "inline-grid-lanes")
301                && matches!(node.value_ref("position").map(str::trim), Some("absolute" | "fixed"))
302            {
303                display = match display {
304                    "inline-flex" => "flex",
305                    "inline-grid" => "grid",
306                    "inline-grid-lanes" => "grid-lanes",
307                    _ => "block",
308                };
309            }
310            match display {
311                "block" => BoxType::BlockNode(node),
312                // inline-flex: 外側は inline-block として行に流し、内側は flex で組む
313                // (`layout_inline_flex`。2026-09-26 まで InlineNode 扱いで子が flex 配置されなかった)。
314                // inline-grid も同じ方式(外側 inline-block・内側 grid。2026-09-26 まで
315                // block 扱いの GridNode で、前の文字の後ろに並ばず改行していた)。
316                "inline-block" | "inline-flex" | "inline-grid" | "inline-grid-lanes" => BoxType::InlineBlockNode(node),
317                "flex" => BoxType::FlexNode(node),
318                "grid" | "grid-lanes" => BoxType::GridNode(node),
319                "table" => BoxType::TableNode(node),
320                "table-row-group" => BoxType::TableRowGroupNode(node),
321                "table-row" => BoxType::TableRowNode(node),
322                "table-cell" => BoxType::TableCellNode(node),
323                _ => BoxType::InlineNode(node), // "none" は下で除外
324            }
325        }
326        NodeType::Text(_) => BoxType::InlineNode(node),
327    };
328
329    let mut layout_box = LayoutBox {
330        dimensions: Dimensions::default(),
331        box_type,
332        children: Vec::new(),
333        trim_leading_space: false,
334        subtree_boxes: 1,
335    };
336
337    // flex/grid/table 系の直下の空白だけの文字は箱を作らない(CSS Flexbox §4・Grid §6・
338    // Tables §3.4。パーサが要素間の空白を残すようになった 2026-10-09 から必要)。
339    let drops_space = match &layout_box.box_type {
340        BoxType::FlexNode(_)
341        | BoxType::GridNode(_)
342        | BoxType::TableNode(_)
343        | BoxType::TableRowGroupNode(_)
344        | BoxType::TableRowNode(_) => true,
345        BoxType::InlineBlockNode(n) => {
346            matches!(resolved_display(n), "inline-flex" | "inline-grid" | "inline-grid-lanes")
347        }
348        _ => false,
349    };
350    for child in &node.children {
351        // 【2026-11-18 TODO R2 (b) ②】子 1 つごとに止める確かめ(錠を持っていない所)。このタブだけ止めるなら残りの子を作らない。
352        if layout_poll() {
353            break;
354        }
355        if drops_space && matches!(&child.node.node_type, NodeType::Text(t) if t.trim().is_empty()) {
356            continue;
357        }
358        if resolved_display(child) != "none" {
359            // visibility: hidden — include in layout but mark invisible (handled in web_engine)
360            let mut b = build_layout_tree(child);
361            // flex/grid の子で display:inline のまま中にブロックを持つ要素は、block として組む
362            // (CSS Display §2.7 の blockification の一部)。【2026-10-24】display 指定の無い
363            // カスタム要素(既定 inline)が flex アイテムのとき行内要素として組まれ、YouTube の
364            // `#page-manager{display:flex}` > `ytd-watch-flexy` の中の `width:100%` が 1px になっていた。
365            // 文字だけのリンク等は従来どおり(内容幅で並ぶ。一律に block にすると sugi-lab.net の
366            // ヒーローのボタンが幅いっぱいに伸びた)。
367            if drops_space
368                && is_flex_or_grid_container(&layout_box.box_type)
369                && matches!(b.box_type, BoxType::InlineNode(_))
370                && !b.is_replaced_inline()
371                && matches!(&child.node.node_type, NodeType::Element { .. })
372                && b.children.iter().any(|c| {
373                    matches!(
374                        c.box_type,
375                        BoxType::BlockNode(_) | BoxType::FlexNode(_) | BoxType::GridNode(_) | BoxType::TableNode(_)
376                    )
377                })
378            {
379                if let BoxType::InlineNode(n) = b.box_type {
380                    b.box_type = BoxType::BlockNode(n);
381                }
382            } else if drops_space
383                && is_flex_or_grid_container(&layout_box.box_type)
384                && matches!(b.box_type, BoxType::InlineNode(_))
385                && !b.is_replaced_inline()
386                && matches!(&child.node.node_type, NodeType::Element { .. })
387            {
388                // 文字だけの inline の項目は、内容幅のまま margin/padding/border を持つ箱にする
389                // (inline-block。InlineNode には余白が適用されない)。【2026-10-25】YouTube の
390                // ヘッダーの国コード `#country-code{margin:12px 0 0 -10px}`(flex の中の span)の
391                // margin が無視され、「JP」がロゴから離れて上端に描かれていた。
392                if let BoxType::InlineNode(n) = b.box_type {
393                    b.box_type = BoxType::InlineBlockNode(n);
394                }
395            }
396            // flex/grid の子に明示した `display:inline-block` は block になる(CSS Display §2.7
397            // の blockification)。【2026-11-18】inline-block のままだと、中身がブロック級(flex の
398            // `<a>` 等)のときアイテムの高さを行の高さ 1 行分でしか見積もらず、YouTube のミニガイド
399            // (`#items{display:flex;flex-direction:column}` > `ytd-mini-guide-entry-renderer
400            // {display:inline-block}`)の項目が 16px ほどに潰れ、アイコンと文字が重なっていた。
401            if drops_space
402                && is_flex_or_grid_container(&layout_box.box_type)
403                && matches!(&child.node.node_type, NodeType::Element { tag_name, .. }
404                    if !matches!(tag_name.as_str(), "img" | "video" | "canvas" | "iframe" | "embed" | "object" | "input" | "button" | "select" | "textarea"))
405                && matches!(b.box_type, BoxType::InlineBlockNode(n) if resolved_display(n) == "inline-block")
406            {
407                if let BoxType::InlineBlockNode(n) = b.box_type {
408                    b.box_type = BoxType::BlockNode(n);
409                }
410            }
411            // flex/grid 直下の文字は匿名アイテム(ブロック)の先頭なので先頭空白を落とす。
412            if drops_space && matches!(&child.node.node_type, NodeType::Text(_)) {
413                b.trim_leading_space = true;
414            }
415            layout_box.children.push(b);
416        }
417    }
418
419    // インラインの中に通常フローのブロックがあれば、インラインはそこで分割され、ブロックは
420    // 包含ブロックの幅いっぱいになる(CSS 2.1 §9.2.1.1)。分割はせずブロックとして組む近似。
421    // 【2026-11-01】幅 1 に潰れていた。既定が inline のカスタム要素(YouTube の `yt-smartimation` 等)で多発する。
422    if matches!(layout_box.box_type, BoxType::InlineNode(_))
423        && matches!(&node.node.node_type, NodeType::Element { .. })
424        && !layout_box.is_replaced_inline()
425        && layout_box.children.iter().any(|c| {
426            matches!(c.box_type, BoxType::BlockNode(_) | BoxType::FlexNode(_) | BoxType::GridNode(_) | BoxType::TableNode(_))
427                && !box_style_value_ref(c, "position").is_some_and(|p| matches!(p.trim(), "absolute" | "fixed"))
428                && box_style_value_ref(c, "float").is_none_or(|f| f.trim() == "none")
429        })
430    {
431        if let BoxType::InlineNode(n) = layout_box.box_type {
432            layout_box.box_type = BoxType::BlockNode(n);
433        }
434    }
435
436    // テーブルの行グループ (thead/tbody/tfoot) は透過し、行 (tr) を table の直接の子へ引き上げる。
437    // これにより layout_table は「table の子 = 行」という単純な前提で計算できる。
438    if matches!(layout_box.box_type, BoxType::TableNode(_)) {
439        let mut flattened: Vec<LayoutBox<'a>> = Vec::new();
440        for child in layout_box.children.drain(..) {
441            if matches!(child.box_type, BoxType::TableRowGroupNode(_)) {
442                for row in child.children {
443                    flattened.push(row);
444                }
445            } else {
446                flattened.push(child);
447            }
448        }
449        layout_box.children = flattened;
450    }
451
452    layout_box.subtree_boxes = 1u32.saturating_add(
453        layout_box
454            .children
455            .iter()
456            .map(|c| c.subtree_boxes.max(1))
457            .fold(0u32, u32::saturating_add),
458    );
459    layout_box
460}
461
462/// flex/grid コンテナか(外側 inline の inline-flex/inline-grid を含む)。
463fn is_flex_or_grid_container(t: &BoxType) -> bool {
464    match t {
465        BoxType::FlexNode(_) | BoxType::GridNode(_) => true,
466        BoxType::InlineBlockNode(n) => matches!(resolved_display(n), "inline-flex" | "inline-grid"),
467        _ => false,
468    }
469}
470
471/// スタイルから (margin, padding, border) を解決する(`%` は `containing_width` 基準)。
472/// `init` の現在値を初期値にして、指定のある辺だけ上書きする(従来の
473/// `apply_box_model_styles_with_base` と同じ意味。内在幅の計測でも使うため切り出した)。
474pub(crate) fn style_box_edges(
475    node: &StyledNode,
476    containing_width: i32,
477    init: &Dimensions,
478) -> (EdgeSizes, EdgeSizes, EdgeSizes) {
479    // 縦書きの世界: 物理の辺で解決してから論理の辺へ並べ替える(覚え書きは世界を区別しないので使わない)。
480    let w = crate::os_lib::css::CUR_WORLD.load(AtomicOrdering::Relaxed);
481    if w != 0 {
482        return super::writing_mode::style_box_edges_world(node, containing_width, init, w);
483    }
484    // 覚え書き(`StyledNode::edges_cache`)。同じ包含幅・初期値なら前回の結果を返す。
485    let pack = |m: &EdgeSizes, p: &EdgeSizes, b: &EdgeSizes| -> [i32; 12] {
486        [m.left, m.right, m.top, m.bottom, p.left, p.right, p.top, p.bottom, b.left, b.right, b.top, b.bottom]
487    };
488    let key = pack(&init.margin, &init.padding, &init.border);
489    if let Ok(cache) = node.edges_cache.try_borrow() {
490        if let Some((_, _, v)) = cache.iter().find(|(cw, k, _)| *cw == containing_width && *k == key) {
491            let e = |i: usize| EdgeSizes { left: v[i], right: v[i + 1], top: v[i + 2], bottom: v[i + 3] };
492            return (e(0), e(4), e(8));
493        }
494    }
495    let r = style_box_edges_uncached(node, containing_width, init);
496    if let Ok(mut cache) = node.edges_cache.try_borrow_mut() {
497        if cache.len() >= 8 {
498            cache.remove(0);
499        }
500        cache.push((containing_width, key, pack(&r.0, &r.1, &r.2)));
501    }
502    r
503}
504
505pub(crate) fn style_box_edges_uncached(
506    node: &StyledNode,
507    containing_width: i32,
508    init: &Dimensions,
509) -> (EdgeSizes, EdgeSizes, EdgeSizes) {
510    let mut margin = init.margin.clone();
511    let mut padding = init.padding.clone();
512    let mut border = init.border.clone();
513    // 【2026-10-04】`em` は要素自身の文字サイズ基準(CSS Values 4 §6.1.1)。
514    // 下の `apply_*` → `parse_px_like` は `em` を常に 16px で換算するので、
515    // その前に要素の文字サイズで px へ置き換えておく
516    // (smarthome.htm の `h1{font-size:2.5rem; margin-top:1em}` が 16px になっていた)。
517    let font_px = node
518        .value_ref("font-size")
519        .and_then(parse_font_size_u32)
520        .unwrap_or(16) as f32;
521    // `em` を含むときだけ換算する(含まない値は借用のまま渡す。2026-10-18 レイアウトの最頻出経路の削減)。
522    let val = |name: &str| -> Option<alloc::borrow::Cow<'_, str>> {
523        node.value_ref(name).map(|s| {
524            if s.as_bytes().windows(2).any(|w| w.eq_ignore_ascii_case(b"em")) {
525                alloc::borrow::Cow::Owned(crate::os_lib::css::units::resolve_em_lengths(s, font_px))
526            } else {
527                alloc::borrow::Cow::Borrowed(s)
528            }
529        })
530    };
531    apply_box_value(
532        val("margin"),
533        &mut margin,
534        containing_width,
535    );
536    apply_box_value(
537        val("padding"),
538        &mut padding,
539        containing_width,
540    );
541
542    apply_edge_value(
543        val("margin-top"),
544        &mut margin.top,
545        containing_width,
546    );
547    apply_edge_value(
548        val("margin-right"),
549        &mut margin.right,
550        containing_width,
551    );
552    apply_edge_value(
553        val("margin-bottom"),
554        &mut margin.bottom,
555        containing_width,
556    );
557    apply_edge_value(
558        val("margin-left"),
559        &mut margin.left,
560        containing_width,
561    );
562
563    apply_edge_value(
564        val("padding-top"),
565        &mut padding.top,
566        containing_width,
567    );
568    apply_edge_value(
569        val("padding-right"),
570        &mut padding.right,
571        containing_width,
572    );
573    apply_edge_value(
574        val("padding-bottom"),
575        &mut padding.bottom,
576        containing_width,
577    );
578    apply_edge_value(
579        val("padding-left"),
580        &mut padding.left,
581        containing_width,
582    );
583
584    // border-width / border は単純に幅だけ扱う
585    apply_box_value(
586        val("border-width"),
587        &mut border,
588        containing_width,
589    );
590    if let Some(border_val) = val("border") {
591        if let Some(px) = parse_px_like(&border_val) {
592            border.top = px;
593            border.right = px;
594            border.bottom = px;
595            border.left = px;
596        }
597    }
598    apply_edge_value(
599        val("border-top-width"),
600        &mut border.top,
601        containing_width,
602    );
603    apply_edge_value(
604        val("border-right-width"),
605        &mut border.right,
606        containing_width,
607    );
608    apply_edge_value(
609        val("border-bottom-width"),
610        &mut border.bottom,
611        containing_width,
612    );
613    apply_edge_value(
614        val("border-left-width"),
615        &mut border.left,
616        containing_width,
617    );
618    // CSS 2.1 §8.4 / §8.5: padding と border-width は負になれない。
619    padding.top = padding.top.max(0);
620    padding.right = padding.right.max(0);
621    padding.bottom = padding.bottom.max(0);
622    padding.left = padding.left.max(0);
623    border.top = border.top.max(0);
624    border.right = border.right.max(0);
625    border.bottom = border.bottom.max(0);
626    border.left = border.left.max(0);
627    (margin, padding, border)
628}
629
630/// 子の内在幅(min/max-content)の寄与を、子自身の `min-width`/`max-width`(px)で挟む
631/// (CSS Sizing 3: 寄与は min/max-width で制限される)。`%` は基準が無いので無視。
632/// 【2026-09-26】英語版ヒーローで、`max-width:800px` の hero-content の寄与が見出しの全長
633/// (数千 px)のままになり、flex 項目が中央寄せで左へ大きくはみ出していた。
634/// `content_based`: `cmin`/`cmax` が content 幅か(明示の border-box 幅なら false)。
635pub(crate) fn clamp_contribution(b: &LayoutBox, cmin: i32, cmax: i32, content_based: bool) -> (i32, i32) {
636    let inner = if content_based { border_box_inner_w(b) } else { 0 };
637    let px = |prop: &str| match parse_length_value(box_style_value_ref(b, prop)) {
638        Some(LengthValue::Px(v)) => Some((v - inner).max(0)),
639        _ => None,
640    };
641    let (mut lo, mut hi) = (cmin, cmax);
642    if let Some(mx) = px("max-width") {
643        lo = lo.min(mx);
644        hi = hi.min(mx);
645    }
646    if let Some(mn) = px("min-width") {
647        lo = lo.max(mn);
648        hi = hi.max(mn);
649    }
650    (lo, hi.max(lo))
651}
652
653/// `box-sizing:border-box` の箱なら左右の padding+border、それ以外は 0。
654///
655/// `min-width`/`max-width` の長さは box-sizing に従って border-box を測る(CSS Sizing 3 §3.1)。
656/// content 幅と比べる前にこの分を引く。【2026-10-17】`*{box-sizing:border-box}` のサイトで
657/// `max-width:800px; padding:0 20px` の箱の content が 760 でなく 800 になり、英語版ヒーロー
658/// 見出しの折り返し位置が Chrome と違っていた(sugi-lab.net/index_e.html)。
659pub(crate) fn border_box_inner_w(b: &LayoutBox) -> i32 {
660    let node = match &b.box_type {
661        BoxType::BlockNode(n)
662        | BoxType::InlineBlockNode(n)
663        | BoxType::FlexNode(n)
664        | BoxType::GridNode(n)
665        | BoxType::TableNode(n) => *n,
666        BoxType::InlineNode(n) if b.is_replaced_inline() => *n,
667        _ => return 0,
668    };
669    if node.value_ref("box-sizing").is_none_or(|v| v.trim() != "border-box") {
670        return 0;
671    }
672    let (_, p, bd) = style_box_edges(node, 0, &Dimensions::default());
673    (p.left + p.right + bd.left + bd.right).max(0)
674}
675
676pub(crate) fn border_box_inner_h(b: &LayoutBox) -> i32 {
677    let node = match &b.box_type {
678        BoxType::BlockNode(n)
679        | BoxType::InlineBlockNode(n)
680        | BoxType::FlexNode(n)
681        | BoxType::GridNode(n)
682        | BoxType::TableNode(n) => *n,
683        BoxType::InlineNode(n) if b.is_replaced_inline() => *n,
684        _ => return 0,
685    };
686    if node.value_ref("box-sizing").is_none_or(|v| v.trim() != "border-box") {
687        return 0;
688    }
689    let (_, p, bd) = style_box_edges(node, 0, &Dimensions::default());
690    (p.top + p.bottom + bd.top + bd.bottom).max(0)
691}
692
693fn subtree_has_pct_h_or_oof(b: &LayoutBox) -> bool {
694    let is_col_flex_grow = matches!(b.box_type, BoxType::FlexNode(n) if n.value_ref("flex-direction").is_some_and(|d| d.trim().starts_with("column")))
695        && b.children.iter().any(|c| !LayoutBox::child_is_out_of_flow(c) && box_flex_grow_f32(c) > 0.0);
696    is_col_flex_grow
697        || b.children.iter().any(|c| {
698            LayoutBox::child_is_out_of_flow(c)
699                || ["height", "min-height", "max-height", "flex-basis"]
700                    .iter()
701                    .any(|p| box_style_value_ref(c, p).is_some_and(|v| v.contains('%')))
702                || box_aspect_ratio(c).is_some()
703                || subtree_has_pct_h_or_oof(c)
704        })
705}
706
707fn subtree_has_oof(b: &LayoutBox) -> bool {
708    b.children.iter().any(|c| LayoutBox::child_is_out_of_flow(c) || subtree_has_oof(c))
709}
710
711/// サイズの値が `stretch`(CSS Sizing 4。接頭辞付きの `-webkit-fill-available` なども同じ)か。
712/// 包含ブロックの余白を除いた残りの大きさ(margin box が包含ブロックを満たす)を表す。
713fn is_stretch_kw(v: Option<&str>) -> bool {
714    v.is_some_and(is_stretch_value)
715}
716
717/// `min-width`/`max-width` の値が長さ(px・%・calc)か。`min-content` 等の内容基準の
718/// キーワードは content 幅そのものなので border-box の換算をしない。
719fn is_length_sizing(v: Option<&str>) -> bool {
720    matches!(
721        parse_length_value(v),
722        Some(LengthValue::Px(_) | LengthValue::Percent(_) | LengthValue::MathExpr(_))
723    )
724}
725
726/// 内在幅の合計へ入れる、子の横方向の非 content 分(margin + border + padding)。
727/// 【2026-09-26】従来は子の content 幅だけを足しており、入れ子の flex や
728/// shrink-to-fit の箱が子の padding 分だけ狭く見積もられていた。
729/// 明示幅が `box-sizing:border-box` のときは padding/border が幅に含まれるので margin だけ。
730/// 箱の左右の margin(内在幅の計測用。`%` は 0、負は 0 として扱う)。
731fn inline_h_margins(b: &LayoutBox) -> i32 {
732    let node = match &b.box_type {
733        BoxType::InlineBlockNode(n) | BoxType::InlineNode(n) => *n,
734        _ => return 0,
735    };
736    let (m, _, _) = style_box_edges(node, 0, &Dimensions::default());
737    m.left.max(0) + m.right.max(0)
738}
739
740/// 行内ブロック(inline-block / inline-flex / inline-grid。置換要素は除く)の上下の
741/// margin+border+padding(`intrinsic_h_edges` の縦版。レイアウト前にスタイルから求める)。
742/// 【2026-10-25】行内要素の中身の大きさを子の固有サイズで見積もる際に足していなかった。
743pub(crate) fn intrinsic_v_edges(b: &LayoutBox) -> i32 {
744    let node = match &b.box_type {
745        BoxType::InlineBlockNode(n) => *n,
746        _ => return 0,
747    };
748    let (m, p, bd) = style_box_edges(node, 0, &Dimensions::default());
749    m.top.max(0) + m.bottom.max(0) + p.top + p.bottom + bd.top + bd.bottom
750}
751
752/// `<svg>` の自然な縦横比(幅, 高さ)。`width`/`height` 属性(数値・px)、無ければ `viewBox`。
753/// 【2026-10-25】高さが内容依存の親の中の `svg{height:100%}` は % が解けず auto になるが、
754/// svg は中身(path)が流れに高さを作らないため 0 になっていた(YouTube のメニューアイコン)。
755/// 仕様では svg は置換要素で、auto の高さは自然な縦横比と幅から決まる。
756fn svg_natural_ratio(node: &StyledNode) -> Option<(f32, f32)> {
757    let NodeType::Element { tag_name, attributes, .. } = &node.node.node_type else {
758        return None;
759    };
760    if tag_name != "svg" {
761        return None;
762    }
763    let num = |v: &str| v.trim().trim_end_matches("px").parse::<f32>().ok().filter(|x| *x > 0.0);
764    let aw = attributes.get("width").and_then(|v| num(v));
765    let ah = attributes.get("height").and_then(|v| num(v));
766    if let (Some(w), Some(h)) = (aw, ah) {
767        return Some((w, h));
768    }
769    let vb: Vec<f32> = attributes
770        .get("viewBox")
771        .map(|v| v.split(|c: char| c == ',' || c.is_whitespace()).filter_map(|t| t.parse::<f32>().ok()).collect())
772        .unwrap_or_default();
773    match vb.as_slice() {
774        [_, _, w, h] if *w > 0.0 && *h > 0.0 => Some((*w, *h)),
775        _ => None,
776    }
777}
778
779/// `box-sizing:border-box` の行内ブロックの明示サイズから引く左右・上下の padding+border。
780/// content-box なら (0, 0)。【2026-10-25】`intrinsic_inline_size` は content の大きさを返す約束
781/// (配置側はその値を content に置き、余白を外に足す)だが、border-box の明示サイズを
782/// そのまま返していたため、YouTube のヘッダーのボタン(40×40、padding 8)が 56×56 になっていた。
783fn border_box_inner(node: &StyledNode) -> (i32, i32) {
784    if node.value_ref("box-sizing").is_none_or(|v| v.trim() != "border-box") {
785        return (0, 0);
786    }
787    let (_, p, bd) = style_box_edges(node, 0, &Dimensions::default());
788    (p.left + p.right + bd.left + bd.right, p.top + p.bottom + bd.top + bd.bottom)
789}
790
791/// 行内要素の子 1 つが行で占める大きさ(行内ブロックは余白込み)。
792fn inline_child_outer_size(child: &LayoutBox, avail: i32) -> (i32, i32) {
793    let (w, h) = child.intrinsic_inline_size(avail);
794    if matches!(child.box_type, BoxType::InlineBlockNode(_)) {
795        (w + intrinsic_h_edges(child, false), h + intrinsic_v_edges(child))
796    } else {
797        (w, h)
798    }
799}
800
801pub(crate) fn intrinsic_h_edges(b: &LayoutBox, explicit_width: bool) -> i32 {
802    let node = match &b.box_type {
803        BoxType::BlockNode(n)
804        | BoxType::InlineBlockNode(n)
805        | BoxType::FlexNode(n)
806        | BoxType::GridNode(n)
807        | BoxType::TableNode(n) => *n,
808        BoxType::InlineNode(n) if b.is_replaced_inline() => *n,
809        _ => return 0,
810    };
811    // 内在幅の計測中は包含幅が未確定なので `%` は 0 扱い。
812    let (m, p, bd) = style_box_edges(node, 0, &Dimensions::default());
813    let margins = m.left.max(0) + m.right.max(0);
814    let border_box = explicit_width
815        && node.value_ref("box-sizing").map(|v| v.trim() == "border-box").unwrap_or(false);
816    if border_box {
817        margins
818    } else {
819        margins + p.left + p.right + bd.left + bd.right
820    }
821}
822
823/// 文字ノードの書体指定(font-family のリスト, ウェイト)。描画側(`web_engine` の
824/// `final_weight`)と同じく `font-weight` を数値にする(2026-10-03。従来は太字か否かの 2 値)。
825fn text_font_of<'a>(node: &'a StyledNode<'a>) -> (&'a str, u16) {
826    let fam = node.value_ref("font-family").map(str::trim).unwrap_or("");
827    let weight = node
828        .value_ref("font-weight")
829        .map(crate::kernel::font_select::parse_font_weight)
830        .unwrap_or(400);
831    (fam, weight)
832}
833
834/// `::before`/`::after` の内容の大きさ(幅, 行の高さ)。本文が空白だけで子要素も無い要素に限る
835/// (描画側 `web_engine` が疑似要素を要素の箱に描くのと同じ対象。本文がある要素では足さない)。
836///
837/// 【2026-10-03】レイアウトが疑似要素の内容を見ておらず、Font Awesome の `<i class="fas fa-home">`
838/// が幅 0・高さ 0 の箱になっていた。flex の中央寄せがその点を中心に置き、描画側は箱の左端から
839/// アイコンを描くため、円の中心から右下へずれていた(sugi-lab.net/profile.htm)。
840fn pseudo_content_size(node: &StyledNode) -> Option<(i32, i32)> {
841    // 【2026-11-07 最適化】要素の大半は疑似要素を持たないため、`format!` 確保を避けて静的キーで先に引く。
842    let before_txt = if node.value_ref("x-before-display") == Some("none") {
843        ""
844    } else {
845        node.value_ref("x-before-content").unwrap_or("")
846    };
847    let after_txt = if node.value_ref("x-after-display") == Some("none") {
848        ""
849    } else {
850        node.value_ref("x-after-content").unwrap_or("")
851    };
852    if before_txt.is_empty() && after_txt.is_empty() {
853        return None;
854    }
855    let only_ws = node.node.children.iter().all(|c| match &c.node_type {
856        NodeType::Text(t) => t.trim().is_empty(),
857        _ => false,
858    });
859    if !only_ws {
860        return None;
861    }
862    let mut text = String::with_capacity(before_txt.len() + after_txt.len());
863    text.push_str(before_txt);
864    text.push_str(after_txt);
865    let font_size = node
866        .value_ref("font-size")
867        .and_then(parse_font_size_u32)
868        .unwrap_or(16);
869    let fam = node
870        .value_ref("x-before-font-family")
871        .or_else(|| node.value_ref("font-family"))
872        .map(str::trim)
873        .unwrap_or("");
874    let (_, weight) = text_font_of(node);
875    let (w, _) = crate::kernel::vector_font::get_vector_string_wrapped_size_family(
876        &text, font_size, 1_000_000, 0, 0, false, false, false, fam, weight,
877    );
878    let line_h = parse_line_height(node.value_ref("line-height"), font_size);
879    Some((w as i32, line_h.max(1)))
880}
881
882impl<'a> LayoutBox<'a> {
883    /// 明示の px 高さを content 高に換算して返す(`box-sizing:border-box` なら
884    /// 縦の padding/border を引く)。明示 px でなければ None。
885    /// 【2026-09-26】flex コンテナが border-box の明示高さをそのまま content 高に使い、
886    /// padding 分だけ背が高くなっていた(`*{box-sizing:border-box}` のサイト全般)。
887    fn explicit_content_height_px(&self, height_val: Option<&str>) -> Option<i32> {
888        let Some(LengthValue::Px(px)) = parse_length_value(height_val) else {
889            return None;
890        };
891        let border_box = box_style_value_ref(self, "box-sizing")
892            .map(|v| v.trim() == "border-box")
893            .unwrap_or(false);
894        if border_box {
895            let d = &self.dimensions;
896            Some((px - d.padding.top - d.padding.bottom - d.border.top - d.border.bottom).max(0))
897        } else {
898            Some(px.max(0))
899        }
900    }
901
902    /// 横方向の content 以外(margin + border + padding の左右合計)。
903    fn h_non_content(&self) -> i32 {
904        let d = &self.dimensions;
905        d.margin.left + d.margin.right + d.border.left + d.border.right + d.padding.left + d.padding.right
906    }
907
908    /// 行内で content の外側に占める (左, 右, 上, 下) の幅(margin+border+padding)。
909    /// inline-block(inline-flex 含む)のみ。素の inline 要素は box model 自体が
910    /// 未適用(常に 0)なので従来どおり 0。レイアウト後に呼ぶこと。
911    ///
912    /// 【2026-10-09/2026-10-13】置換要素(`img` 等)は縦・横の margin+border+padding も
913    /// 行内で占める(CSS 2.1 §10.3.2 / §10.6.2)。
914    pub(crate) fn inline_block_edges(&self) -> (i32, i32, i32, i32) {
915        if self.is_replaced_inline() || matches!(self.box_type, BoxType::InlineBlockNode(_)) {
916            let d = &self.dimensions;
917            return (
918                d.margin.left + d.border.left + d.padding.left,
919                d.margin.right + d.border.right + d.padding.right,
920                d.margin.top + d.border.top + d.padding.top,
921                d.margin.bottom + d.border.bottom + d.padding.bottom,
922            );
923        }
924        (0, 0, 0, 0)
925    }
926
927    /// このボックスに対応する StyledNode(テキスト/インライン/ブロック/コンテナ問わず)を返す。
928    pub(crate) fn styled_node(&self) -> Option<&'a StyledNode<'a>> {
929        match &self.box_type {
930            BoxType::BlockNode(n)
931            | BoxType::InlineNode(n)
932            | BoxType::InlineBlockNode(n)
933            | BoxType::FlexNode(n)
934            | BoxType::GridNode(n)
935            | BoxType::TableNode(n)
936            | BoxType::TableRowGroupNode(n)
937            | BoxType::TableRowNode(n)
938            | BoxType::TableCellNode(n) => Some(*n),
939            BoxType::AnonymousBlock => None,
940        }
941    }
942
943    /// 置換要素(`img`/`video`/`canvas`/`iframe` 等、`inline` および flex/grid で blockify された `inline-block`)か。
944    pub(crate) fn is_replaced_inline(&self) -> bool {
945        match &self.box_type {
946            BoxType::InlineNode(n) | BoxType::InlineBlockNode(n) => matches!(
947                &n.node.node_type,
948                NodeType::Element { tag_name, .. }
949                    if matches!(tag_name.as_str(), "img" | "video" | "canvas" | "iframe" | "embed" | "object")
950            ),
951            _ => false,
952        }
953    }
954
955    /// 行内の箱のベースライン(margin-box 上端からの距離)。
956    /// CSS 2.1 §10.8.1:
957    /// - 置換要素(img, input 等): 下マージン端
958    /// - inline-block: overflow が visible 以外、または行ボックスを持たない場合は下マージン端。
959    ///   それ以外は最後の行ボックス(最後のテキスト/インライン子孫)のベースライン。
960    /// - 素の inline(InlineNode): フォントの ascent(+ 行送りの中央揃え leading)。
961    pub(crate) fn box_baseline(&self) -> i32 {
962        let (_, _, et, eb) = self.inline_block_edges();
963        let outer_h = et + self.dimensions.content.height + eb;
964        if self.is_replaced_inline() {
965            return outer_h;
966        }
967        match &self.box_type {
968            BoxType::InlineNode(node) => {
969                let (ch, asc) = super::baseline::text_font_ascent(node, self.dimensions.content.height);
970                let _ = ch;
971                et + asc
972            }
973            BoxType::InlineBlockNode(_) => {
974                let clips = box_style_value_ref(self, "overflow")
975                    .is_some_and(|v| v.split_whitespace().any(|t| t != "visible"));
976                if clips {
977                    return outer_h;
978                }
979                if self.is_inline_grid() {
980                    if let Some(gb) = self.grid_first_baseline() {
981                        return et + gb;
982                    }
983                    return outer_h;
984                }
985                if let Some(inner_bl) = self.last_inflow_baseline() {
986                    et + inner_bl
987                } else {
988                    outer_h
989                }
990            }
991            _ => outer_h,
992        }
993    }
994
995    /// インラインブロック内の最後のインライン要素のベースラインを、
996    /// 自身の content-box 上端からの相対距離として取得する。
997    fn last_inflow_baseline(&self) -> Option<i32> {
998        for c in self.children.iter().rev() {
999            if c.is_whitespace_text()
1000                || box_float(c) != "none"
1001                || matches!(box_position(c), "absolute" | "fixed")
1002            {
1003                continue;
1004            }
1005            match &c.box_type {
1006                BoxType::InlineNode(_) => {
1007                    let (_, _, cet, _) = c.inline_block_edges();
1008                    let cy = (c.dimensions.content.y - cet) - self.dimensions.content.y;
1009                    return Some(cy + c.box_baseline());
1010                }
1011                BoxType::InlineBlockNode(_) => {
1012                    let (_, _, cet, _) = c.inline_block_edges();
1013                    let cy = (c.dimensions.content.y - cet) - self.dimensions.content.y;
1014                    return Some(cy + c.box_baseline());
1015                }
1016                BoxType::BlockNode(_) | BoxType::AnonymousBlock => {
1017                    if let Some(b) = c.last_inflow_baseline() {
1018                        let (_, _, cet, _) = c.inline_block_edges();
1019                        let cy = (c.dimensions.content.y - cet) - self.dimensions.content.y;
1020                        return Some(cy + b);
1021                    }
1022                }
1023                _ => {}
1024            }
1025        }
1026        None
1027    }
1028
1029    /// 子孫に空白以外の文字ノードがあるか(inline-block が行ボックスを持つかの近似)。
1030    fn has_inflow_text(&self) -> bool {
1031        if let BoxType::InlineNode(n) = &self.box_type {
1032            if let NodeType::Text(t) = &n.node.node_type {
1033                return !t.trim().is_empty();
1034            }
1035        }
1036        self.children.iter().any(|c| c.has_inflow_text())
1037    }
1038
1039    /// 空白だけの文字ノードで、空白が畳まれる(`white-space` が normal/nowrap/pre-line)もの。
1040    fn is_collapsible_space(&self) -> bool {
1041        if !self.is_whitespace_text() {
1042            return false;
1043        }
1044        !matches!(
1045            box_style_value_ref(self, "white-space").map(str::trim),
1046            Some("pre" | "pre-wrap" | "break-spaces")
1047        )
1048    }
1049
1050    /// 畳まれた空白 1 つの幅(描画と同じ書体・letter/word-spacing 込み)。
1051    fn collapsed_space_width(&self) -> i32 {
1052        let BoxType::InlineNode(node) = &self.box_type else {
1053            return 0;
1054        };
1055        let font_px = node
1056            .value_ref("font-size")
1057            .and_then(parse_font_size_u32)
1058            .unwrap_or(16);
1059        let ls = parse_letter_spacing_with_font(node.value_ref("letter-spacing"), 0, font_px as f32);
1060        let ws = parse_word_spacing_with_font(node.value_ref("word-spacing"), 0, font_px as f32);
1061        let (fam, weight) = text_font_of(node);
1062        crate::kernel::vector_font::get_vector_string_width_family(" ", font_px, fam, weight, ls, ws) as i32
1063    }
1064
1065    /// 中身が空白だけの素の inline 要素か(`<span> </span>`。前後の空白と畳まれる)。
1066    fn is_blank_inline(&self) -> bool {
1067        matches!(self.box_type, BoxType::InlineNode(_))
1068            && !self.is_replaced_inline()
1069            && !self.has_inflow_text()
1070            && self.children.iter().all(|c| c.is_whitespace_text() || c.is_blank_inline())
1071    }
1072
1073    /// 空白だけの文字ノードか(行内に並んでも見えず、揃えの対象にしない)。
1074    pub(crate) fn is_whitespace_text(&self) -> bool {
1075        matches!(&self.box_type, BoxType::InlineNode(n)
1076            if matches!(&n.node.node_type, NodeType::Text(t) if t.trim().is_empty()))
1077    }
1078
1079    /// テキストノードで末尾に空白を持つか(改行・タブ含む)。
1080    fn text_ends_with_space(&self) -> bool {
1081        if let BoxType::InlineNode(n) = &self.box_type {
1082            if let NodeType::Text(t) = &n.node.node_type {
1083                return t.ends_with(' ') || t.ends_with('\t') || t.ends_with('\n');
1084            }
1085        }
1086        false
1087    }
1088
1089    /// テキストノードで先頭に空白を持つか(改行・タブ含む)。
1090    fn text_starts_with_space(&self) -> bool {
1091        if let BoxType::InlineNode(n) = &self.box_type {
1092            if let NodeType::Text(t) = &n.node.node_type {
1093                return t.starts_with(' ') || t.starts_with('\t') || t.starts_with('\n');
1094            }
1095        }
1096        false
1097    }
1098
1099    /// インライン要素の中(`layout_inline`)で並べる子の幅を、畳まれた空白の分だけ直す(2026-11-18)。
1100    ///
1101    /// 【なぜ必要か】ブロックの直下の行(`layout_block` の行内の子)は要素間の空白・文字の末尾の空白に
1102    /// 半角 1 つぶんの幅を持たせている(2026-10-09)が、インライン要素の中の子は持たせておらず、
1103    /// `<span><b>w0</b> <i>x</i></span>`・`<span>w0 <i>x</i></span>` の空白が消えて「w0x」と詰まっていた。
1104    ///
1105    /// `measured` は子の計測幅(文字は末尾の空白を含まず、先頭の空白は `trim_leading_space` が偽なら含む)。
1106    /// `after_space` は直前が空白だったか(`None` はインライン要素の最初の行の先頭で、前の状態が分からない。
1107    /// 従来どおり空白だけの子は幅 0、先頭の空白は残す)。返すのは(幅、先頭の空白を落とすか、この子の後ろは空白か)。
1108    fn inline_child_space_adjust(&self, measured: i32, after_space: Option<bool>) -> (i32, bool, bool) {
1109        if self.is_collapsible_space() {
1110            let w = if after_space == Some(false) { self.collapsed_space_width() } else { 0 };
1111            return (w, false, true);
1112        }
1113        let mut w = measured;
1114        let trim = after_space == Some(true) && self.text_starts_with_space();
1115        let sp = if trim || self.text_ends_with_space() || self.trim_leading_space {
1116            self.collapsed_space_width()
1117        } else {
1118            0
1119        };
1120        // 計測は今の印(`trim_leading_space`)で済んでいるので、印との差だけ足し引きする。
1121        if trim && !self.trim_leading_space {
1122            w = w.saturating_sub(sp);
1123        } else if !trim && self.trim_leading_space {
1124            w += sp;
1125        }
1126        let ends_space = self.text_ends_with_space();
1127        if ends_space {
1128            w += sp;
1129        }
1130        (w.max(0), trim, ends_space)
1131    }
1132
1133    /// `[start, end)` の子を 1 行とみなし、`vertical-align`(既定 baseline)に従って
1134    /// 各箱を垂直方向に整列させる(CSS 2.1 §10.8)。
1135    /// 整列後の行全体の高さを返す。
1136    fn align_line_baselines(children: &mut [LayoutBox], start: usize, end: usize) -> i32 {
1137        let Some(line) = children.get_mut(start..end) else {
1138            return 0;
1139        };
1140
1141        // 1. vertical-align: baseline(既定)の箱の揃え
1142        let mut baseline_aligned: Vec<(usize, i32, i32)> = Vec::new();
1143        for (i, c) in line.iter().enumerate() {
1144            if c.is_whitespace_text()
1145                || !matches!(c.box_type, BoxType::InlineNode(_) | BoxType::InlineBlockNode(_))
1146                || box_float(c) != "none"
1147                || matches!(box_position(c), "absolute" | "fixed")
1148            {
1149                continue;
1150            }
1151            let va = box_style_value_ref(c, "vertical-align").unwrap_or("");
1152            let va = va.trim();
1153            if va.is_empty() || va == "baseline" {
1154                let b = c.box_baseline();
1155                let (_, _, et, eb) = c.inline_block_edges();
1156                let outer_h = et + c.dimensions.content.height + eb;
1157                baseline_aligned.push((i, b, outer_h));
1158            }
1159        }
1160
1161        let mut max_baseline = 0i32;
1162        let mut max_descent = 0i32;
1163        if !baseline_aligned.is_empty() {
1164            max_baseline = baseline_aligned.iter().map(|&(_, b, _)| b).max().unwrap_or(0);
1165            for &(i, b, outer_h) in &baseline_aligned {
1166                let descent = outer_h - b;
1167                if descent > max_descent {
1168                    max_descent = descent;
1169                }
1170                let shift = max_baseline - b;
1171                if shift > 0 {
1172                    if let Some(c) = line.get_mut(i) {
1173                        c.translate_y(shift);
1174                    }
1175                }
1176            }
1177        }
1178
1179        // 2. vertical-align: middle / bottom / text-bottom の箱の揃え
1180        let mut line_h = (max_baseline + max_descent).max(0);
1181        for c in line.iter() {
1182            if c.is_whitespace_text()
1183                || !matches!(c.box_type, BoxType::InlineNode(_) | BoxType::InlineBlockNode(_))
1184                || box_float(c) != "none"
1185                || matches!(box_position(c), "absolute" | "fixed")
1186            {
1187                continue;
1188            }
1189            let (_, _, et, eb) = c.inline_block_edges();
1190            let ch = et + c.dimensions.content.height + eb;
1191            if ch > line_h {
1192                line_h = ch;
1193            }
1194        }
1195
1196        if line_h > 0 {
1197            for c in line.iter_mut() {
1198                if c.is_whitespace_text()
1199                    || !matches!(c.box_type, BoxType::InlineNode(_) | BoxType::InlineBlockNode(_))
1200                    || box_float(c) != "none"
1201                    || matches!(box_position(c), "absolute" | "fixed")
1202                {
1203                    continue;
1204                }
1205                let va = box_style_value_ref(c, "vertical-align").unwrap_or("");
1206                let va = va.trim();
1207                let (_, _, et, eb) = c.inline_block_edges();
1208                let ch = et + c.dimensions.content.height + eb;
1209                let offset = match va {
1210                    "middle" => (line_h - ch) / 2,
1211                    "bottom" | "text-bottom" => line_h - ch,
1212                    _ => 0,
1213                };
1214                if offset > 0 {
1215                    c.translate_y(offset);
1216                }
1217            }
1218        }
1219
1220        line_h
1221    }
1222
1223    /// `display: inline-flex` の箱か(外側 InlineBlockNode・内側 flex)。
1224    pub(crate) fn is_inline_flex(&self) -> bool {
1225        match &self.box_type {
1226            BoxType::InlineBlockNode(n) => resolved_display(n).trim() == "inline-flex",
1227            _ => false,
1228        }
1229    }
1230
1231    /// `display: inline-grid` の箱か(外側 InlineBlockNode・内側 grid)。
1232    pub(crate) fn is_inline_grid(&self) -> bool {
1233        match &self.box_type {
1234            BoxType::InlineBlockNode(n) => matches!(resolved_display(n).trim(), "inline-grid" | "inline-grid-lanes"),
1235            _ => false,
1236        }
1237    }
1238
1239    /// inline-flex の content 幅: 明示幅があればそれ、無ければ shrink-to-fit
1240    /// (flex 行の max-content を利用幅で頭打ち。下限は min-content)。
1241    fn inline_flex_content_width(&self, avail: i32) -> i32 {
1242        let node = match &self.box_type {
1243            BoxType::InlineBlockNode(n) => Some(*n),
1244            _ => None,
1245        };
1246        let mut w = if let Some(n) = node {
1247            if let Some(w) = parse_length_value(len_value(n, "width"))
1248                .and_then(|v| resolve_length_value(v, avail.max(0)))
1249            {
1250                w.max(0)
1251            } else {
1252                let (minc, maxc) = self.block_intrinsic_widths();
1253                let d = &self.dimensions;
1254                let non_content = d.margin.left + d.margin.right + d.border.left + d.border.right
1255                    + d.padding.left + d.padding.right;
1256                maxc.min((avail - non_content).max(0)).max(minc).max(0)
1257            }
1258        } else {
1259            let prev_avail = GRID_INTRINSIC_AVAIL_W.swap(avail.max(0), AtomicOrdering::Relaxed);
1260            let (minc, maxc) = self.block_intrinsic_widths();
1261            GRID_INTRINSIC_AVAIL_W.store(prev_avail, AtomicOrdering::Relaxed);
1262            let d = &self.dimensions;
1263            let non_content = d.margin.left + d.margin.right + d.border.left + d.border.right
1264                + d.padding.left + d.padding.right;
1265            maxc.min((avail - non_content).max(0)).max(minc).max(0)
1266        };
1267        if let Some(n) = node {
1268            let inner = self.dimensions.border.left
1269                + self.dimensions.border.right
1270                + self.dimensions.padding.left
1271                + self.dimensions.padding.right;
1272            let bb = n.value_ref("box-sizing").is_some_and(|v| v.trim() == "border-box");
1273            let bb_inner = if bb { inner } else { 0 };
1274            let explicit_w = !matches!(parse_length_value(len_value(n, "width")), Some(LengthValue::Auto) | None);
1275            if explicit_w && bb {
1276                w = (w - inner).max(0);
1277            }
1278            let max_val = len_value(n, "max-width");
1279            if let Some(mx) = self.resolve_sizing_value(max_val.as_deref(), avail.max(0)) {
1280                let mx = if is_length_sizing(max_val.as_deref()) { (mx - bb_inner).max(0) } else { mx };
1281                w = w.min(mx);
1282            }
1283            let min_val = len_value(n, "min-width");
1284            if let Some(mn) = self.resolve_sizing_value(min_val.as_deref(), avail.max(0)) {
1285                let mn = if is_length_sizing(min_val.as_deref()) { (mn - bb_inner).max(0) } else { mn };
1286                w = w.max(mn);
1287            }
1288        }
1289        w.max(0)
1290    }
1291
1292    /// 自身を flex コンテナとして content 幅 `content_w`・content 原点 (x, y) に組む。
1293    /// `layout_flex` は FlexNode しか受け付けないので、その間だけ型を差し替える。
1294    fn layout_as_flex_at(&mut self, x: i32, y: i32, content_w: i32) {
1295        let BoxType::InlineBlockNode(node) = self.box_type else {
1296            return;
1297        };
1298        let as_grid = self.is_inline_grid();
1299        self.box_type = if as_grid { BoxType::GridNode(node) } else { BoxType::FlexNode(node) };
1300        let d = &self.dimensions;
1301        let left = d.margin.left + d.border.left + d.padding.left;
1302        let top = d.margin.top + d.border.top + d.padding.top;
1303        let h_non = left + d.padding.right + d.border.right + d.margin.right;
1304        let cb = Dimensions {
1305            content: Rect { x: x - left, y: y - top, width: content_w + h_non, height: 0 },
1306            ..Default::default()
1307        };
1308        if as_grid {
1309            self.layout_grid(cb);
1310        } else {
1311            self.layout_flex(cb);
1312        }
1313        self.box_type = BoxType::InlineBlockNode(node);
1314    }
1315
1316    /// `display: inline-flex` のレイアウト。位置の決め方は `layout_inline` と同じ
1317    /// (cb の content 原点 + 縦カーソル + margin/border/padding)で、親が最後に
1318    /// スロット位置へ子孫ごと平行移動する。
1319    fn layout_inline_flex(&mut self, containing_block: Dimensions) {
1320        self.apply_box_model_styles_with_base(containing_block.content.width);
1321        let w = self.inline_flex_content_width(containing_block.content.width.max(1));
1322        let d = &self.dimensions;
1323        let x = containing_block.content.x + d.margin.left + d.border.left + d.padding.left;
1324        let y = containing_block.content.y
1325            + containing_block.content.height
1326            + d.margin.top
1327            + d.border.top
1328            + d.padding.top;
1329        self.layout_as_flex_at(x, y, w);
1330    }
1331
1332    /// 自身と全子孫の絶対 y 座標を dy だけ平行移動する(table セルの `vertical-align` 実装用)。
1333    /// 各ボックスの content.y は既に絶対ピクセル座標として確定しているため、
1334    /// この再帰1回で子孫すべての位置がまとめてずれる。
1335    fn translate_y(&mut self, dy: i32) {
1336        if dy == 0 {
1337            return;
1338        }
1339        self.dimensions.content.y += dy;
1340        for child in &mut self.children {
1341            child.translate_y(dy);
1342        }
1343    }
1344
1345    /// 自身と全子孫の絶対座標を (dx, dy) だけ平行移動する。
1346    ///
1347    /// 多段組で「通常フローで積み終えた子を列の位置へ移す」ために使う。
1348    /// `translate_y` の 2 軸版で、考え方は同じ(content 座標が絶対値なので
1349    /// 再帰 1 回で子孫がまとめてずれる)。
1350    pub(crate) fn translate(&mut self, dx: i32, dy: i32) {
1351        if dx == 0 && dy == 0 {
1352            return;
1353        }
1354        self.dimensions.content.x += dx;
1355        self.dimensions.content.y += dy;
1356        for child in &mut self.children {
1357            child.translate(dx, dy);
1358        }
1359    }
1360
1361    /// 親ブロックと先頭子の上マージン相殺時に、子を `-cmt` 上へ引き上げる。
1362    /// 子自身が絶対配置の包含ブロックを持たない場合、子孫の `position: absolute` は
1363    /// 外側の包含ブロック基準で既に確定しているため移動から除外する。
1364    fn translate_collapse_margin_top(&mut self, dy: i32, parent_establishes_cb: bool) {
1365        if dy == 0 {
1366            return;
1367        }
1368        self.dimensions.content.y += dy;
1369        let est = parent_establishes_cb || box_establishes_abs_cb(self);
1370        for child in &mut self.children {
1371            // 縦の位置が静的位置(`top`/`bottom` とも auto)の絶対配置は流れに付いて動く(CSS 2.1 §10.6.4)。
1372            // 外の包含ブロック基準で `top`/`bottom` が決まっているものだけ動かさない(WPT flexbox abspos/position-absolute-002)。
1373            if !est && box_position(child) == "absolute" {
1374                let static_y = box_inset_len(child, "top", 0).is_none() && box_inset_len(child, "bottom", 0).is_none();
1375                if static_y {
1376                    child.translate(0, dy);
1377                }
1378                continue;
1379            }
1380            child.translate_collapse_margin_top(dy, est);
1381        }
1382    }
1383
1384    /// `indices` で指定した caption 群を y から順に縦積みでレイアウトし、消費した合計高さを返す。
1385    /// `caption-side:top`(既定)/`bottom` どちらの配置にも使う共通ヘルパー。
1386    fn layout_captions_at(&mut self, indices: &[usize], base_x: i32, y: i32, width: i32) -> i32 {
1387        let mut consumed = 0i32;
1388        for &ci in indices {
1389            let cap_y = y + consumed;
1390            let cap = &mut self.children[ci];
1391            let mut cb = Dimensions::default();
1392            cb.content.x = base_x;
1393            cb.content.y = cap_y;
1394            cb.content.height = 0;
1395            cb.content.width = width;
1396            cap.layout(cb);
1397            consumed += cap.dimensions.margin_box().height;
1398        }
1399        consumed
1400    }
1401
1402    pub(crate) fn layout(&mut self, containing_block: Dimensions) {
1403        // 【2026-11-18 TODO R2 (b) ②・(d) ①】箱 1 つごとに止める確かめ(錠を持っていない所。ウィンドウごと止めるならここで終わる)。
1404        // このタブだけ止める合図なら、この箱と子孫を組まずに戻る(寸法は 0 のまま。途中までの木はタブごと捨てられる)。
1405        if layout_poll() {
1406            // 使い回しの表に当たったときと同じく、親がこの箱に渡した高さの指定を消しておく(次の箱へ残さない)。
1407            if matches!(self.box_type, BoxType::BlockNode(_) | BoxType::TableCellNode(_)) {
1408                FORCED_BLOCK_H.store(-1, AtomicOrdering::Relaxed);
1409            }
1410            return;
1411        }
1412        // 縦書き: 親と世界が違う箱は自分の世界で組んで写す。世界の中では使い回しの表を使わない。
1413        let cur_world = crate::os_lib::css::CUR_WORLD.load(AtomicOrdering::Relaxed);
1414        if cur_world != 0 || crate::os_lib::css::WM_SEEN.load(AtomicOrdering::Relaxed) {
1415            if let Some(n) = self.world_node() {
1416                let w = super::writing_mode::world_of(n);
1417                if w != cur_world {
1418                    self.layout_other_world(containing_block, cur_world, w);
1419                    return;
1420                }
1421            }
1422        }
1423        let is_fg_item = IN_FLEX_OR_GRID_ITEM.swap(false, AtomicOrdering::Relaxed);
1424        let can_check_memo = cur_world == 0 && self.is_virgin_box() && get_subgrid_ctx().is_none();
1425        let target = if can_check_memo {
1426            match &self.box_type {
1427                BoxType::BlockNode(n) => Some((1u8, *n)),
1428                BoxType::FlexNode(n) => Some((2u8, *n)),
1429                BoxType::GridNode(n) => Some((3u8, *n)),
1430                BoxType::TableNode(n) => Some((4u8, *n)),
1431                BoxType::TableCellNode(n) => Some((5u8, *n)),
1432                _ => None,
1433            }
1434        } else {
1435            None
1436        };
1437        let box_flags = target
1438            .map(|(tag, _)| tag | ((self.trim_leading_space as u8) << 4) | ((is_fg_item as u8) << 5))
1439            .unwrap_or(0);
1440        let pre_pct_base_h = PCT_BASE_H.load(AtomicOrdering::Relaxed);
1441        let pre_forced_h = FORCED_BLOCK_H.load(AtomicOrdering::Relaxed);
1442        let cb_x = containing_block.content.x;
1443        let cb_w = containing_block.content.width;
1444        let cb_h = containing_block.content.height;
1445        let cb_y_flow = containing_block.content.y + cb_h;
1446
1447        let has_oof = subtree_has_oof(self);
1448        if let Some((_, node)) = target {
1449            let (h0, h1, can_memo) = node.layout_subtree_info();
1450            if can_memo && !has_oof {
1451                let cb_h_key = if node_uses_cb_height(node) { cb_h } else { 0 };
1452                let key = LayoutMemoKey {
1453                    subtree_hash: (h0, h1),
1454                    box_flags,
1455                    cb_w,
1456                    cb_h_key,
1457                    pct_base_h: pre_pct_base_h,
1458                    forced_h: pre_forced_h,
1459                    env_hash: current_layout_env_hash(),
1460                };
1461                if self.try_apply_layout_memo(&key, cb_x, cb_y_flow) {
1462                    if pre_forced_h >= 0
1463                        && matches!(
1464                            self.box_type,
1465                            BoxType::BlockNode(_) | BoxType::TableCellNode(_)
1466                        )
1467                    {
1468                        FORCED_BLOCK_H.store(-1, AtomicOrdering::Relaxed);
1469                    }
1470                    return;
1471                }
1472            }
1473        }
1474
1475        if cur_world != 0 || crate::os_lib::css::WM_SEEN.load(AtomicOrdering::Relaxed) {
1476            // 子が向きの違う箱のとき「親が flex/grid か」で block サイズの決め方が変わる(`writing_mode.rs`)。
1477            let fg = matches!(self.box_type, BoxType::FlexNode(_) | BoxType::GridNode(_))
1478                || self.is_inline_flex()
1479                || self.is_inline_grid();
1480            let prev = super::writing_mode::PARENT_FLEXGRID.swap(fg, AtomicOrdering::Relaxed);
1481            self.layout_inner(containing_block, is_fg_item);
1482            super::writing_mode::PARENT_FLEXGRID.store(prev, AtomicOrdering::Relaxed);
1483        } else {
1484            self.layout_inner(containing_block, is_fg_item);
1485        }
1486
1487        if let Some((_, node)) = target {
1488            let (h0, h1, can_memo) = node.layout_subtree_info();
1489            // 止める合図の後の結果は途中までなので、使い回しの表(ほかのタブ・アプリも引く)に入れない(2026-11-18)。
1490            if can_memo && !has_oof && !layout_aborting() {
1491                let cb_h_key = if node_uses_cb_height(node) { cb_h } else { 0 };
1492                let key = LayoutMemoKey {
1493                    subtree_hash: (h0, h1),
1494                    box_flags,
1495                    cb_w,
1496                    cb_h_key,
1497                    pct_base_h: pre_pct_base_h,
1498                    forced_h: pre_forced_h,
1499                    env_hash: current_layout_env_hash(),
1500                };
1501                self.store_layout_memo(key, cb_x, cb_y_flow);
1502            }
1503        }
1504    }
1505
1506    fn is_virgin_box(&self) -> bool {
1507        let d = &self.dimensions;
1508        d.content.width == 0
1509            && d.content.height == 0
1510            && d.padding.top == 0
1511            && d.padding.right == 0
1512            && d.padding.bottom == 0
1513            && d.padding.left == 0
1514            && d.border.top == 0
1515            && d.border.right == 0
1516            && d.border.bottom == 0
1517            && d.border.left == 0
1518            && d.margin.top == 0
1519            && d.margin.right == 0
1520            && d.margin.bottom == 0
1521            && d.margin.left == 0
1522    }
1523
1524    fn can_memo_subtree(&self) -> bool {
1525        match &self.box_type {
1526            BoxType::BlockNode(n)
1527            | BoxType::InlineNode(n)
1528            | BoxType::InlineBlockNode(n)
1529            | BoxType::FlexNode(n)
1530            | BoxType::GridNode(n)
1531            | BoxType::TableNode(n)
1532            | BoxType::TableRowGroupNode(n)
1533            | BoxType::TableRowNode(n)
1534            | BoxType::TableCellNode(n) => n.layout_subtree_info().2,
1535            BoxType::AnonymousBlock => self.children.iter().all(|c| c.can_memo_subtree()),
1536        }
1537    }
1538
1539    pub fn subtree_box_count(&self) -> usize {
1540        if self.subtree_boxes > 1 || (self.subtree_boxes == 1 && self.children.is_empty()) {
1541            self.subtree_boxes as usize
1542        } else {
1543            1 + self.children.iter().map(|c| c.subtree_box_count()).sum::<usize>()
1544        }
1545    }
1546
1547    fn collect_memo_boxes(&self, out: &mut Vec<(Dimensions, bool)>) {
1548        out.push((self.dimensions.clone(), self.trim_leading_space));
1549        for child in &self.children {
1550            child.collect_memo_boxes(out);
1551        }
1552    }
1553
1554    fn apply_memo_boxes(
1555        &mut self,
1556        boxes: &[(Dimensions, bool)],
1557        idx: &mut usize,
1558        dx: i32,
1559        dy: i32,
1560    ) -> bool {
1561        let Some((dim, trim)) = boxes.get(*idx) else {
1562            return false;
1563        };
1564        *idx += 1;
1565        let mut d = dim.clone();
1566        d.content.x += dx;
1567        d.content.y += dy;
1568        self.dimensions = d;
1569        self.trim_leading_space = *trim;
1570        for child in &mut self.children {
1571            if !child.apply_memo_boxes(boxes, idx, dx, dy) {
1572                return false;
1573            }
1574        }
1575        true
1576    }
1577
1578    fn try_apply_layout_memo(&mut self, key: &LayoutMemoKey, cb_x: i32, cb_y_flow: i32) -> bool {
1579        let expected_len = self.subtree_box_count();
1580        let mut g = GLOBAL_LAYOUT_MEMO.lock();
1581        g.tick = g.tick.wrapping_add(1);
1582        let tick = g.tick;
1583        if let Some(entry) = g.map.get_mut(key) {
1584            if entry.boxes.len() == expected_len {
1585                let dx = cb_x - entry.cb_x;
1586                let dy = cb_y_flow - entry.cb_y_flow;
1587                let mut idx = 0;
1588                if self.apply_memo_boxes(&entry.boxes, &mut idx, dx, dy) && idx == expected_len {
1589                    entry.last_used = tick;
1590                    g.hits += 1;
1591                    return true;
1592                }
1593            }
1594        }
1595        g.misses += 1;
1596        false
1597    }
1598
1599    fn store_layout_memo(&self, key: LayoutMemoKey, cb_x: i32, cb_y_flow: i32) {
1600        let count = self.subtree_box_count();
1601        if count > LayoutMemo::MAX_SUBTREE_BOXES {
1602            return;
1603        }
1604        let mut boxes = Vec::with_capacity(count);
1605        self.collect_memo_boxes(&mut boxes);
1606        let mut g = GLOBAL_LAYOUT_MEMO.lock();
1607        if g.map.len() >= LayoutMemo::MAX_ENTRIES && !g.map.contains_key(&key) {
1608            let cutoff = g.tick.saturating_sub(LayoutMemo::MAX_ENTRIES as u64 / 2);
1609            g.map.retain(|_, v| v.last_used >= cutoff);
1610            if g.map.len() >= LayoutMemo::MAX_ENTRIES {
1611                g.map.clear();
1612            }
1613        }
1614        g.tick = g.tick.wrapping_add(1);
1615        let tick = g.tick;
1616        g.map.insert(
1617            key,
1618            LayoutMemoEntry {
1619                cb_x,
1620                cb_y_flow,
1621                boxes,
1622                last_used: tick,
1623            },
1624        );
1625    }
1626
1627    fn layout_fg_item(&mut self, containing_block: Dimensions) {
1628        IN_FLEX_OR_GRID_ITEM.store(true, AtomicOrdering::Relaxed);
1629        self.layout(containing_block);
1630    }
1631
1632    fn layout_inner(&mut self, containing_block: Dimensions, is_fg_item: bool) {
1633        match &self.box_type {
1634            BoxType::BlockNode(_) => self.layout_block(containing_block, is_fg_item),
1635            BoxType::InlineNode(_) => self.layout_inline(containing_block, false),
1636            BoxType::InlineBlockNode(_) if self.is_inline_flex() || self.is_inline_grid() => {
1637                self.layout_inline_flex(containing_block)
1638            }
1639            BoxType::InlineBlockNode(_) => self.layout_inline(containing_block, true),
1640            BoxType::FlexNode(_) => self.layout_flex(containing_block),
1641            BoxType::GridNode(_) => self.layout_grid(containing_block),
1642            BoxType::TableNode(_) => self.layout_table(containing_block),
1643            // 行グループ・行・セルは table 経由でレイアウトされる。
1644            // 単独で呼ばれた場合 (table の外にある等) は block としてフォールバック。
1645            BoxType::TableRowGroupNode(_)
1646            | BoxType::TableRowNode(_)
1647            | BoxType::TableCellNode(_) => self.layout_block(containing_block, false),
1648            BoxType::AnonymousBlock => {}
1649        }
1650    }
1651
1652    /// この要素が包含ブロックを作る(位置指定、または `transform`/`filter`/`contain:paint` 等)なら、
1653    /// 子孫 absolute(および transform 等なら fixed)の包含ブロックを self のパディング箱に切替え、
1654    /// 切替前の値を返す。戻り値は `restore_abs_cb` に渡して復元する。
1655    /// content.width / content.height が確定済みであることを前提とする(bottom/right 解決のため)。
1656    fn establish_abs_cb(
1657        &self,
1658    ) -> (
1659        Option<(i32, i32, i32, i32)>,
1660        Option<Option<(i32, i32, i32, i32)>>,
1661    ) {
1662        let pb = self.dimensions.padding_box();
1663        let prev_abs = if box_establishes_abs_cb(self) {
1664            // 【2026-10-03】包含ブロックは positioned 祖先の**パディングボックス**(CSS 2.1 10.1)。
1665            // 従来は content box で、`padding-bottom:56.25%; height:0` の縦横比の箱に入れた
1666            // `height:100%` の絶対配置(動画・地図の埋め込みの定番)が高さ 0 になっていた。
1667            let prev = abs_cb_get();
1668            abs_cb_set(pb.x, pb.y, pb.width, pb.height);
1669            Some(prev)
1670        } else {
1671            None
1672        };
1673        let prev_fixed = if box_establishes_fixed_cb(self) {
1674            let prev = fixed_cb_get();
1675            fixed_cb_set(Some((pb.x, pb.y, pb.width, pb.height)));
1676            Some(prev)
1677        } else {
1678            None
1679        };
1680        (prev_abs, prev_fixed)
1681    }
1682
1683    /// `establish_abs_cb` の戻り値を使って ABS_CB / FIXED_CB を元に戻す。
1684    fn restore_abs_cb(
1685        saved: (
1686            Option<(i32, i32, i32, i32)>,
1687            Option<Option<(i32, i32, i32, i32)>>,
1688        ),
1689    ) {
1690        if let Some(prev) = saved.0 {
1691            abs_cb_set(prev.0, prev.1, prev.2, prev.3);
1692        }
1693        if let Some(prev) = saved.1 {
1694            fixed_cb_set(prev);
1695        }
1696    }
1697
1698    /// 子のうち out-of-flow(absolute / fixed)なものを判定するヘルパ。
1699    pub(crate) fn child_is_out_of_flow(child: &LayoutBox) -> bool {
1700        matches!(box_position(child), "absolute" | "fixed")
1701    }
1702
1703    /// position 後処理。全フォーマッティングコンテキスト(block/flex/grid/table)で共有。
1704    /// - relative: フロー確定位置から top/left(または bottom/right の符号反転)でオフセット。
1705    /// - absolute: 最近傍 positioned 祖先(ABS_CB、昇り解決済み)基準で top/left/right/bottom 配置。
1706    /// - fixed: ビューポート原点基準で配置。
1707    /// - transform: translate を最後に視覚シフトとして適用(兄弟は再フローしない=仕様通り)。
1708    ///
1709    /// self.dimensions.content.{width,height} が確定済みであることを前提とする。
1710    fn apply_positioned_offsets(&mut self) {
1711        self.apply_positioned_offsets_with(None, false);
1712    }
1713
1714    /// `apply_positioned_offsets` の本体。`abs_areas[i]` があれば i 番目の子の absolute の
1715    /// 包含ブロックとして使う(grid コンテナが包含ブロックのとき、グリッドエリアが基準になる)。
1716    fn apply_positioned_offsets_with(
1717        &mut self,
1718        abs_areas: Option<&[Option<(i32, i32, i32, i32)>]>,
1719        static_from_flow: bool,
1720    ) {
1721        self.apply_positioned_offsets_grid(abs_areas, None, static_from_flow);
1722    }
1723
1724    fn apply_positioned_offsets_grid(
1725        &mut self,
1726        abs_areas: Option<&[Option<(i32, i32, i32, i32)>]>,
1727        rel_cell_sizes: Option<&[Option<(i32, i32)>]>,
1728        static_from_flow: bool,
1729    ) {
1730        let cw = self.dimensions.content.width;
1731        let ch = self.dimensions.content.height;
1732        // grid コンテナが包含ブロックの絶対配置の子は、inset が auto の軸で `justify-self` / `align-self`
1733        // (無ければ `justify-items` / `align-items`)に従ってグリッドエリア内に整列する(CSS Grid 2 §9)。
1734        let cur_world = crate::os_lib::css::CUR_WORLD.load(AtomicOrdering::Relaxed);
1735        let (j_items, a_items, grid_rtl_phys, grid_rtl_logic) = match (self.box_type, abs_areas.is_some()) {
1736            (BoxType::GridNode(n), true) => (
1737                n.value_ref("justify-items").unwrap_or(""),
1738                n.value_ref("align-items").unwrap_or(""),
1739                box_is_rtl(self),
1740                if cur_world == 0 { box_is_rtl(self) } else { false },
1741            ),
1742            (BoxType::InlineBlockNode(n), true) if self.is_inline_grid() => (
1743                n.value_ref("justify-items").unwrap_or(""),
1744                n.value_ref("align-items").unwrap_or(""),
1745                box_is_rtl(self),
1746                if cur_world == 0 { box_is_rtl(self) } else { false },
1747            ),
1748            _ => ("", "", false, false),
1749        };
1750        let self_rtl = box_is_rtl(self);
1751                for (child_idx, child) in self.children.iter_mut().enumerate() {
1752            match box_position(child) {
1753                "relative" => {
1754                    let (rcw, rch) = rel_cell_sizes
1755                        .and_then(|r| r.get(child_idx).copied().flatten())
1756                        .unwrap_or((cw, ch));
1757                    let dx = box_inset_len(child, "left", rcw)
1758                        .or_else(|| box_inset_len(child, "right", rcw).map(|r| -r))
1759                        .unwrap_or(0);
1760                    let dy = box_inset_len(child, "top", rch)
1761                        .or_else(|| box_inset_len(child, "bottom", rch).map(|b| -b))
1762                        .unwrap_or(0);
1763                    if dx != 0 || dy != 0 {
1764                        shift_layout_box(child, dx, dy);
1765                    }
1766                }
1767                pos @ ("absolute" | "fixed") => {
1768                    // 基準矩形: absolute=ABS_CB(昇り解決済み)、fixed=FIXED_CB(transform 等の祖先があればそのパディング箱、無ければビューポート原点)。
1769                    let (bx, by, bw, bh) = if let Some(area) = abs_areas
1770                        .and_then(|a| a.get(child_idx).copied().flatten())
1771                    {
1772                        area
1773                    } else if pos == "fixed" {
1774                        fixed_cb_get().filter(|&(_, _, _, h)| h > 0).unwrap_or_else(|| {
1775                            let (vx, vy) = vp_origin_get();
1776                            (
1777                                vx,
1778                                vy,
1779                                VIEWPORT_HINT_W.load(AtomicOrdering::Relaxed),
1780                                VIEWPORT_HINT_H.load(AtomicOrdering::Relaxed),
1781                            )
1782                        })
1783                    } else {
1784                        abs_cb_get()
1785                    };
1786                    // 【2026-09-26 バグ修正】幅 auto の絶対配置は、left と right が両方あれば
1787                    // 包含ブロックから幅を決め、そうでなければ内容幅に縮む(shrink-to-fit。
1788                    // CSS 2.1 §10.3.7)。従来は通常フローと同じく親の幅いっぱいに組まれ、
1789                    // 実サイトのヒーロー下部の矢印(left:50% + translateX(-50%))が左端に出ていた。
1790                    // 【2026-10-03】% の幅・高さは包含ブロック(bw × bh)基準で組み直す。通常フローとして
1791                    // 組まれた時点では親の content 幅・未確定の高さが基準になっている。
1792                    let is_pct = |name: &str| {
1793                        matches!(
1794                            parse_length_value(box_style_value_ref(child, name)),
1795                            Some(LengthValue::Percent(_))
1796                        )
1797                    };
1798                    // 【2026-10-18】`%` の基準・縮み幅・top+bottom の高さを先に全部決め、組み直しは
1799                    // 1 回にまとめる。従来は条件ごとに最大 3 回組み直し、入れ子の absolute ごとに
1800                    // 掛け算で増えていた(YouTube の操作部でレイアウト時間の約半分)。
1801                    let need_pct = is_pct("width") || is_pct("height");
1802                    let block_like = matches!(
1803                        child.box_type,
1804                        BoxType::BlockNode(_) | BoxType::FlexNode(_) | BoxType::GridNode(_) | BoxType::InlineBlockNode(_)
1805                    );
1806                    let h_non = child.h_non_content();
1807                    // 【2026-11-30】left/right(top/bottom)が両方ある絶対配置は、`justify-self`(`align-self`)が
1808                    // start/center/end 等のとき包含ブロックを埋めず fit-content になり、その軸の余白の中で整列する
1809                    // (CSS Box Alignment §6・CSS Position 3 §5.2。`normal`/`stretch` は従来どおり埋める)。
1810                    // 横書き(自身・現在の世界とも)の通常の子だけが対象(縦書きは未対応)。
1811                    let own_area_early = abs_areas.is_some_and(|a| a.get(child_idx).copied().flatten().is_some());
1812                    let abs_align_ok = block_like && !own_area_early && cur_world == 0 && inherited_world_of(child) == 0;
1813                    let j_abs: Option<&'static str> = if abs_align_ok
1814                        && !box_has_explicit(child, "width")
1815                        && box_inset_len(child, "left", bw).is_some()
1816                        && box_inset_len(child, "right", bw).is_some()
1817                    {
1818                        abs_axis_align(child, "justify-self", self_rtl, true)
1819                    } else {
1820                        None
1821                    };
1822                    let a_abs: Option<&'static str> = if abs_align_ok
1823                        && !box_has_explicit(child, "height")
1824                        && box_inset_len(child, "top", bh).is_some()
1825                        && box_inset_len(child, "bottom", bh).is_some()
1826                    {
1827                        abs_axis_align(child, "align-self", self_rtl, false)
1828                    } else {
1829                        None
1830                    };
1831                    // 【2026-11-30 TODO S2】`width:stretch`(`-webkit-fill-available`)の絶対配置は、包含ブロック
1832                    // (パディング箱)の残りを margin box で満たす。inset が無い側は 0(両方 auto なら静的位置から)。
1833                    let w_stretch = block_like && is_stretch_kw(box_style_value_ref(child, "width"));
1834                    let h_stretch = block_like && is_stretch_kw(box_style_value_ref(child, "height"));
1835                    let target_w: Option<i32> = if w_stretch {
1836                        let l = box_inset_len(child, "left", bw);
1837                        let r = box_inset_len(child, "right", bw);
1838                        let start = match (l, r) {
1839                            (Some(l), _) => l,
1840                            (None, Some(_)) => 0,
1841                            (None, None) if static_from_flow && pos == "absolute" => (child.dimensions.margin_box().x - bx).max(0),
1842                            (None, None) => 0,
1843                        };
1844                        Some((bw - start - r.unwrap_or(0) - h_non).max(0))
1845                    } else if block_like && !box_has_explicit(child, "width") {
1846                        let l = box_inset_len(child, "left", bw);
1847                        let r = box_inset_len(child, "right", bw);
1848                        Some(match (l, r) {
1849                            (Some(l), Some(r)) if j_abs.is_some() => {
1850                                let (minc, maxc) = child.block_intrinsic_widths();
1851                                let avail = (bw - l - r - h_non).max(0);
1852                                maxc.min(avail).max(minc).max(0)
1853                            }
1854                            (Some(l), Some(r)) => (bw - l - r - h_non).max(0),
1855                            _ => {
1856                                let (minc, maxc) = child.block_intrinsic_widths();
1857                                let avail = (bw - l.or(r).unwrap_or(0) - h_non).max(0);
1858                                maxc.min(avail).max(minc).max(0)
1859                            }
1860                        })
1861                    } else {
1862                        None
1863                    };
1864                    // 高さ auto で top と bottom が両方あれば、包含ブロックから高さを決める
1865                    // (CSS 2.1 §10.6.4)。【2026-10-17】`position:absolute; inset:0` の覆い
1866                    // (YouTube 埋め込みのサムネイル・操作部)が内容の高さに縮んでいた。
1867                    let target_h: Option<i32> = if h_stretch {
1868                        let t = box_inset_len(child, "top", bh);
1869                        let b = box_inset_len(child, "bottom", bh);
1870                        let start = match (t, b) {
1871                            (Some(t), _) => t,
1872                            (None, Some(_)) => 0,
1873                            (None, None) if static_from_flow && pos == "absolute" => (child.dimensions.margin_box().y - by).max(0),
1874                            (None, None) => 0,
1875                        };
1876                        let mb0 = child.dimensions.margin_box();
1877                        let v_non = mb0.height - child.dimensions.content.height;
1878                        Some((bh - start - b.unwrap_or(0) - v_non).max(0))
1879                    } else if block_like && !box_has_explicit(child, "height") {
1880                        match (box_inset_len(child, "top", bh), box_inset_len(child, "bottom", bh)) {
1881                            (Some(_), Some(_)) if a_abs.is_some() => None,
1882                            (Some(t), Some(b)) => {
1883                                let mb0 = child.dimensions.margin_box();
1884                                let v_non = mb0.height - child.dimensions.content.height;
1885                                Some((bh - t - b - v_non).max(0))
1886                            }
1887                            _ => None,
1888                        }
1889                    } else {
1890                        None
1891                    };
1892                    let is_block = matches!(child.box_type, BoxType::BlockNode(_) | BoxType::GridNode(_) | BoxType::FlexNode(_));
1893                    let need_w = target_w.is_some_and(|w| w != child.dimensions.content.width);
1894                    // 子の `height:100%` もこの高さで解決させるため、ブロックは高さを確定させて組み直す。
1895                    let need_h = is_block && target_h.is_some_and(|h| h != child.dimensions.content.height);
1896                    if need_pct || need_w || need_h {
1897                        let mb0 = child.dimensions.margin_box();
1898                        let _pct_h = PctBaseHGuard::set(bh);
1899                        let width = match target_w {
1900                            Some(w) => w + h_non,
1901                            None if need_pct => bw,
1902                            None => mb0.width,
1903                        };
1904                        if need_h {
1905                            if let Some(h) = target_h {
1906                                FORCED_BLOCK_H.store(h, AtomicOrdering::Relaxed);
1907                            }
1908                        }
1909                        let cb = Dimensions {
1910                            content: Rect { x: mb0.x, y: mb0.y, width, height: 0 },
1911                            ..Default::default()
1912                        };
1913                        child.layout(cb);
1914                        FORCED_BLOCK_H.store(-1, AtomicOrdering::Relaxed);
1915                    }
1916                    if let Some(h) = target_h {
1917                        if h != child.dimensions.content.height {
1918                            child.dimensions.content.height = h;
1919                        }
1920                    }
1921                    let mb = child.dimensions.margin_box();
1922                    // grid コンテナが包含ブロックでない子の静的位置は、グリッドが置いた
1923                    // 位置(コンテンツ箱の起点)そのもの。
1924                    let own_area = own_area_early;
1925                    let keep_static = static_from_flow && !own_area && pos == "absolute";
1926                    let l_val = box_inset_len(child, "left", bw);
1927                    let r_val = box_inset_len(child, "right", bw);
1928                    let tx = match (l_val, r_val) {
1929                        (Some(l), Some(r)) if j_abs.is_some() => {
1930                            let free = bw - l - r - mb.width;
1931                            // `start`/`end` はコンテナの inline 軸基準(rtl なら start は右)。
1932                            let from_left = match (j_abs, self_rtl) {
1933                                (Some("center"), _) => free / 2,
1934                                (Some("end"), false) | (Some("start"), true) => free,
1935                                _ => 0,
1936                            };
1937                            bx + l + from_left
1938                        }
1939                        (Some(l), Some(r)) => {
1940                            let over = own_area && grid_rtl_phys && (box_has_explicit(child, "width") || target_w.is_none());
1941                            if over {
1942                                bx + bw - r - mb.width
1943                            } else {
1944                                bx + l
1945                            }
1946                        }
1947                        (Some(l), None) => bx + l,
1948                        (None, Some(r)) => bx + bw - r - mb.width,
1949                        (None, None) => {
1950                            if keep_static {
1951                                // 静的位置の絶対配置は、`justify-self` が start/center/end 等なら静的位置の矩形
1952                                // (ブロック/inline-block の入れ物の content 箱。flex/grid の項目は別の規則)の中で整列する
1953                                // (CSS Box Alignment §6.1。WPT css-align abspos/justify-self-static-position-*)。
1954                                match (abs_align_ok && !matches!(self.box_type, BoxType::FlexNode(_) | BoxType::GridNode(_)))
1955                                    .then(|| abs_axis_align(child, "justify-self", self_rtl, true))
1956                                    .flatten()
1957                                {
1958                                    Some(al) => {
1959                                        let rx = self.dimensions.content.x;
1960                                        let free = cw - mb.width;
1961                                        match al {
1962                                            "center" => rx + free / 2,
1963                                            "end" => rx + free,
1964                                            _ => rx,
1965                                        }
1966                                    }
1967                                    None => mb.x,
1968                                }
1969                            } else if own_area {
1970                                let free = bw - mb.width;
1971                                let (ml, mr) = Self::h_auto_margins(child);
1972                                let j = if ml || mr {
1973                                    "start"
1974                                } else {
1975                                    resolve_grid_axis_align(child, "justify-self", j_items, cur_world, grid_rtl_phys, true)
1976                                };
1977                                match (j, grid_rtl_logic) {
1978                                    ("center", _) => bx + free / 2,
1979                                    ("end", false) | ("start", true) => bx + free,
1980                                    _ => bx,
1981                                }
1982                            } else {
1983                                bx
1984                            }
1985                        }
1986                    };
1987                    let ty = if let (Some(t), Some(b), Some(al)) =
1988                        (box_inset_len(child, "top", bh), box_inset_len(child, "bottom", bh), a_abs)
1989                    {
1990                        let free = bh - t - b - mb.height;
1991                        by + t + match al {
1992                            "center" => free / 2,
1993                            "end" => free,
1994                            _ => 0,
1995                        }
1996                    } else if let Some(t) = box_inset_len(child, "top", bh) {
1997                        by + t
1998                    } else if let Some(b) = box_inset_len(child, "bottom", bh) {
1999                        by + bh - b - mb.height
2000                    } else if keep_static {
2001                        mb.y
2002                    } else if own_area {
2003                        let free = bh - mb.height;
2004                        match resolve_grid_axis_align(child, "align-self", a_items, cur_world, grid_rtl_phys, false) {
2005                            "center" => by + free / 2,
2006                            "end" => by + free,
2007                            _ => by,
2008                        }
2009                    } else {
2010                        by
2011                    };
2012                    shift_layout_box(child, tx - mb.x, ty - mb.y);
2013                }
2014                _ => {}
2015            }
2016
2017            // transform: translate(レイアウト確定後の視覚シフト。position の後に適用、
2018            // 兄弟は再フローしない=仕様通り)。% は要素自身の content 寸法基準。
2019            let (txx, tyy) = box_translate(child);
2020            if txx != 0 || tyy != 0 {
2021                shift_layout_box(child, txx, tyy);
2022            }
2023        }
2024    }
2025
2026    // ===== CSS Grid レイアウト =====
2027    fn prepare_child_subgrid_ctx(
2028        child: &LayoutBox,
2029        col_widths: &[i32],
2030        col_gap_eff: i32,
2031        c: usize,
2032        cs: usize,
2033        cell_w: i32,
2034    ) -> Option<SubgridContext> {
2035        let child_node = match &child.box_type {
2036            BoxType::GridNode(n) => Some(*n),
2037            BoxType::InlineBlockNode(n) if child.is_inline_grid() => Some(*n),
2038            _ => None,
2039        }?;
2040        let cols_val = child_node.value_ref("grid-template-columns").unwrap_or("");
2041        if !is_subgrid(cols_val) {
2042            return None;
2043        }
2044        let end_c = (c + cs).min(col_widths.len());
2045        let sub_cols = if c < end_c {
2046            col_widths[c..end_c].to_vec()
2047        } else {
2048            alloc::vec![cell_w]
2049        };
2050        Some(SubgridContext {
2051            col_widths: sub_cols,
2052            col_gap: col_gap_eff,
2053        })
2054    }
2055
2056    /// グリッドアイテムの `justify-self` が stretch 以外で幅が auto のとき、アイテムは
2057    /// セル幅を埋めず fit-content(`min(max-content, max(min-content, セル幅))`)になる
2058    /// (CSS Box Alignment §6.2・Grid §6.2)。配置済みの子のその外側幅を返す。
2059    /// 置換要素・明示幅・縦書き・aspect-ratio 付きは対象外(None)。
2060    fn grid_fit_outer_width(child: &LayoutBox, cell_w: i32, justify: &str) -> Option<i32> {
2061        if justify == "stretch" {
2062            return None;
2063        }
2064        let node = match &child.box_type {
2065            BoxType::BlockNode(n) | BoxType::FlexNode(n) | BoxType::GridNode(n) => *n,
2066            _ => return None,
2067        };
2068        // aspect-ratio が幅を決めるのは高さが確定しているときだけ(高さ auto なら幅は内容に縮み、高さが比から決まる)。
2069        if box_has_explicit(child, "width") || (box_aspect_ratio(child).is_some() && box_has_explicit(child, "height")) {
2070            return None;
2071        }
2072        if let NodeType::Element { tag_name, .. } = &node.node.node_type {
2073            if matches!(
2074                tag_name.as_str(),
2075                "img" | "video" | "canvas" | "iframe" | "embed" | "object" | "svg" | "input"
2076                    | "button" | "select" | "textarea"
2077            ) {
2078                return None;
2079            }
2080        }
2081        let h_non = child.h_non_content();
2082        let (minc, maxc) = child.block_intrinsic_widths();
2083        let avail = (cell_w - h_non).max(0);
2084        let mut w = maxc.min(avail).max(minc).max(0);
2085        let inner = child.dimensions.border.left
2086            + child.dimensions.border.right
2087            + child.dimensions.padding.left
2088            + child.dimensions.padding.right;
2089        let bb_inner = if box_style_value_ref(child, "box-sizing").is_some_and(|v| v.trim() == "border-box") {
2090            inner
2091        } else {
2092            0
2093        };
2094        let max_val = len_value(node, "max-width");
2095        if let Some(mx) = child.resolve_sizing_value(max_val.as_deref(), cell_w.max(0)) {
2096            let mx = if is_length_sizing(max_val.as_deref()) { (mx - bb_inner).max(0) } else { mx };
2097            w = w.min(mx);
2098        }
2099        let min_val = len_value(node, "min-width");
2100        if let Some(mn) = child.resolve_sizing_value(min_val.as_deref(), cell_w.max(0)) {
2101            let mn = if is_length_sizing(min_val.as_deref()) { (mn - bb_inner).max(0) } else { mn };
2102            w = w.max(mn);
2103        }
2104        let outer = w.max(0) + h_non;
2105        if outer == cell_w {
2106            None
2107        } else {
2108            Some(outer)
2109        }
2110    }
2111
2112    fn layout_grid(&mut self, containing_block: Dimensions) {
2113        self.layout_grid_impl(containing_block, None);
2114    }
2115
2116    /// `grid-template-columns` / `grid-template-rows` の解決済みトラックリストを返す(WPT / getComputedStyle 用)。
2117    pub fn resolve_grid_computed_tracks(&mut self, containing_block: Dimensions) -> Option<(String, String)> {
2118        if !matches!(self.box_type, BoxType::GridNode(_)) {
2119            return None;
2120        }
2121        let mut out = (String::new(), String::new());
2122        self.layout_grid_impl(containing_block, Some(&mut out));
2123        Some(out)
2124    }
2125
2126    fn layout_grid_impl(&mut self, containing_block: Dimensions, resolved_out: Option<&mut (String, String)>) {
2127        // 外から確定させた高さ(絶対配置の top+bottom。`FORCED_BLOCK_H`)。子孫へ漏らさないよう先に取る。
2128        let forced_h = FORCED_BLOCK_H.swap(-1, AtomicOrdering::Relaxed);
2129        self.apply_box_model_styles_with_base(containing_block.content.width);
2130
2131        let node = match &self.box_type {
2132            BoxType::GridNode(n) => *n,
2133            _ => return,
2134        };
2135        let avail_w = containing_block.content.width.max(0);
2136
2137        // box-sizing / margin:auto 適用(block と同じロジック)。
2138        let inner_non_content = self.dimensions.border.left
2139            + self.dimensions.border.right
2140            + self.dimensions.padding.left
2141            + self.dimensions.padding.right;
2142        let h_non_content =
2143            self.dimensions.margin.left + self.dimensions.margin.right + inner_non_content;
2144        let width_val = len_value(node, "width");
2145        let box_sizing = node.value_ref("box-sizing").unwrap_or("");
2146        let h_auto = margin_is_h_auto(node);
2147        let parsed_width = parse_length_value(width_val.as_deref());
2148        let is_intrinsic_w = matches!(
2149            parsed_width,
2150            Some(LengthValue::MinContent | LengthValue::MaxContent | LengthValue::FitContent | LengthValue::FitContentWith(_))
2151        );
2152        let explicit_w =
2153            !matches!(parsed_width, Some(LengthValue::Auto) | None);
2154        let mut content_w = {
2155            let prev_avail = GRID_INTRINSIC_AVAIL_W.swap(avail_w.max(0), AtomicOrdering::Relaxed);
2156            let w = match parsed_width {
2157                Some(LengthValue::Auto) | None => (avail_w - h_non_content).max(0),
2158                Some(LengthValue::Px(px)) => px.max(0),
2159                Some(LengthValue::Percent(pct)) => round_f32_to_i32(avail_w as f32 * pct).max(0),
2160                Some(LengthValue::MinContent) => {
2161                    let (minc, _maxc) = self.block_intrinsic_widths();
2162                    minc.max(0)
2163                }
2164                Some(LengthValue::MaxContent) => {
2165                    let (_minc, maxc) = self.block_intrinsic_widths();
2166                    maxc.max(0)
2167                }
2168                Some(LengthValue::FitContent) => {
2169                    let (minc, maxc) = self.block_intrinsic_widths();
2170                    let avail = (avail_w - h_non_content).max(0);
2171                    avail.min(maxc).max(minc).max(0)
2172                }
2173                Some(LengthValue::FitContentWith(lim_box)) => {
2174                    let avail = (avail_w - h_non_content).max(0);
2175                    let limit = resolve_length_value_with_font(*lim_box, avail, self.font_size())
2176                        .unwrap_or(avail);
2177                    let (minc, maxc) = self.block_intrinsic_widths();
2178                    maxc.min(limit.max(minc)).max(0)
2179                }
2180                Some(LengthValue::MathExpr(ref expr)) => {
2181                    crate::os_lib::css::eval_css_math_with_font(expr, avail_w, self.font_size())
2182                        .unwrap_or((avail_w - h_non_content).max(1))
2183                        .max(1)
2184                }
2185            };
2186            GRID_INTRINSIC_AVAIL_W.store(prev_avail, AtomicOrdering::Relaxed);
2187            w
2188        };
2189        // 【2026-09-26】border-box は明示幅のときだけ(auto 幅は既に padding を
2190        // 除いた残りなので、引くと二重に引かれる)。min/max-width も適用する
2191        // (従来は無視されており `max-width + margin:auto` の中央寄せが効かなかった)。
2192        if explicit_w && !is_intrinsic_w && box_sizing.trim() == "border-box" {
2193            content_w = (content_w - inner_non_content).max(0);
2194        }
2195        // min/max-width の長さは border-box なら padding+border を含む(`border_box_inner_w`)。
2196        let bb_inner = if box_sizing.trim() == "border-box" { inner_non_content } else { 0 };
2197        // min は max に勝つ(max → min の順で適用)。
2198        let max_val = len_value(node, "max-width");
2199        let max_w_px = self.resolve_sizing_value(max_val.as_deref(), avail_w).map(|v| {
2200            if is_length_sizing(max_val.as_deref()) { (v - bb_inner).max(0) } else { v }
2201        });
2202        if let Some(max_w) = max_w_px {
2203            content_w = content_w.min(max_w);
2204        }
2205        let min_val = len_value(node, "min-width");
2206        let min_w_px = self.resolve_sizing_value(min_val.as_deref(), avail_w).map(|v| {
2207            if is_length_sizing(min_val.as_deref()) { (v - bb_inner).max(0) } else { v }
2208        });
2209        if let Some(min_w) = min_w_px {
2210            content_w = content_w.max(min_w);
2211        }
2212        let content_w = content_w.max(0);
2213        self.dimensions.content.width = content_w;
2214        if h_auto {
2215            let free = (avail_w - content_w - inner_non_content).max(0);
2216            self.dimensions.margin.left = free / 2;
2217            self.dimensions.margin.right = free / 2;
2218        }
2219
2220        let flow_y = containing_block.content.y
2221            + containing_block.content.height
2222            + self.dimensions.margin.top;
2223        self.dimensions.content.x = containing_block.content.x
2224            + self.dimensions.margin.left
2225            + self.dimensions.border.left
2226            + self.dimensions.padding.left;
2227        self.dimensions.content.y =
2228            flow_y + self.dimensions.border.top + self.dimensions.padding.top;
2229
2230        // 行 gap の `%` は容器の高さ基準(高さ確定後に解決。未確定は 0)。列 gap は content 幅基準。
2231        let font_px_gap = self.font_size();
2232        let (mut row_gap, col_gap, row_gap_pct, row_gap_expr) = {
2233            let gpx = |s: &str| -> i32 {
2234                match parse_length_value(Some(s.trim())) {
2235                    Some(LengthValue::Px(p)) => p,
2236                    Some(LengthValue::Percent(pct)) => round_f32_to_i32(content_w as f32 * pct).max(0),
2237                    Some(LengthValue::MathExpr(ref e)) => {
2238                        crate::os_lib::css::eval_css_math_with_font(e, content_w, font_px_gap).unwrap_or(0).max(0)
2239                    }
2240                    _ => 0,
2241                }
2242            };
2243            let row_pct = |s: &str| -> Option<f32> {
2244                match parse_length_value(Some(s.trim())) {
2245                    Some(LengthValue::Percent(pct)) => Some(pct),
2246                    _ => None,
2247                }
2248            };
2249            let row_expr = |s: &str| -> Option<String> {
2250                match parse_length_value(Some(s.trim())) {
2251                    Some(LengthValue::MathExpr(e)) => Some(e),
2252                    _ => None,
2253                }
2254            };
2255            let (mut rg, mut cg, mut rpct, mut rexpr) = (0, 0, None, None);
2256            let gap_all = len_value(node, "gap").or_else(|| len_value(node, "grid-gap"));
2257            if let Some(ref gap_s) = gap_all {
2258                let toks = crate::os_lib::css::split_top_ws(gap_s);
2259                if let Some(&first) = toks.first() {
2260                    let second = toks.get(1).copied().unwrap_or(first);
2261                    rpct = row_pct(first);
2262                    rexpr = row_expr(first);
2263                    rg = if rpct.is_some() || rexpr.as_ref().is_some_and(|e| e.contains('%')) {
2264                        0
2265                    } else {
2266                        gpx(first)
2267                    };
2268                    cg = gpx(second);
2269                }
2270            }
2271            if let Some(v) = node.value_ref("row-gap").or_else(|| node.value_ref("grid-row-gap")) {
2272                rpct = row_pct(v);
2273                rexpr = row_expr(v);
2274                rg = if rpct.is_some() || rexpr.as_ref().is_some_and(|e| e.contains('%')) {
2275                    0
2276                } else {
2277                    gpx(v)
2278                };
2279            }
2280            if let Some(v) = node.value_ref("column-gap").or_else(|| node.value_ref("grid-column-gap")) {
2281                cg = gpx(v);
2282            }
2283            (rg, cg, rpct, rexpr)
2284        };
2285
2286        // ===== トラック定義・配置・トラックサイズ決定(grid.rs の CSS Grid §7/§8/§11 実装) =====
2287        let cur_world = crate::os_lib::css::CUR_WORLD.load(AtomicOrdering::Relaxed);
2288        let is_rtl_phys = box_is_rtl(self);
2289        // 縦書き世界 (cur_world != 0) では writing_mode.rs が world & 4 で RTL 反転を担うため、論理座標上は false。
2290        let is_rtl = if cur_world == 0 { is_rtl_phys } else { false };
2291        let t_cols = node.value_ref("grid-template-columns").unwrap_or("");
2292        let t_rows = node.value_ref("grid-template-rows").unwrap_or("");
2293        let template_areas =
2294            parse_grid_template_areas(node.value_ref("grid-template-areas").unwrap_or(""));
2295        let base_x = self.dimensions.content.x;
2296        let base_y = self.dimensions.content.y;
2297
2298        // 自分の高さが確定しているか(`%` トラック・auto-fill・fr 行の分配の基準)。
2299        let pct_base_h = PCT_BASE_H.load(AtomicOrdering::Relaxed);
2300        let vert_non = self.dimensions.border.top
2301            + self.dimensions.border.bottom
2302            + self.dimensions.padding.top
2303            + self.dimensions.padding.bottom;
2304        let is_bb = box_sizing.trim() == "border-box";
2305        let adj_h = |px: i32| if is_bb { (px - vert_non).max(0) } else { px.max(0) };
2306        let height_val = len_value(node, "height");
2307        let mut container_h_explicit: Option<i32> = if forced_h >= 0 {
2308            Some(forced_h)
2309        } else {
2310            match parse_length_value(height_val.as_deref()) {
2311            Some(LengthValue::Px(px)) => Some(adj_h(px)),
2312            Some(LengthValue::Percent(pct)) if pct_base_h >= 0 => {
2313                Some(adj_h(round_f32_to_i32(pct_base_h as f32 * pct)))
2314            }
2315            Some(LengthValue::MathExpr(e)) if pct_base_h >= 0 || !e.contains('%') => {
2316                crate::os_lib::css::eval_css_math_with_font(&e, pct_base_h.max(0), self.font_size())
2317                    .map(adj_h)
2318            }
2319            _ => None,
2320            }
2321        };
2322        let min_h_px = parse_length_value(len_value(node, "min-height").as_deref()).and_then(|v| match v {
2323            LengthValue::Px(px) => Some(adj_h(px)),
2324            LengthValue::Percent(pct) if pct_base_h >= 0 => Some(adj_h(round_f32_to_i32(pct_base_h as f32 * pct))),
2325            _ => None,
2326        });
2327        let max_h_px = parse_length_value(len_value(node, "max-height").as_deref()).and_then(|v| match v {
2328            LengthValue::Px(px) => Some(adj_h(px)),
2329            LengthValue::Percent(pct) if pct_base_h >= 0 => Some(adj_h(round_f32_to_i32(pct_base_h as f32 * pct))),
2330            _ => None,
2331        });
2332        if let Some(h) = container_h_explicit {
2333            let mut h = h;
2334            if let Some(mx) = max_h_px {
2335                h = h.min(mx);
2336            }
2337            if let Some(mn) = min_h_px {
2338                h = h.max(mn);
2339            }
2340            container_h_explicit = Some(h);
2341        }
2342
2343        if let Some(h) = container_h_explicit {
2344            if let Some(pct) = row_gap_pct {
2345                row_gap = round_f32_to_i32(h as f32 * pct).max(0);
2346            } else if let Some(ref expr) = row_gap_expr {
2347                if expr.contains('%') {
2348                    row_gap = crate::os_lib::css::eval_css_math_with_font(expr, h, font_px_gap)
2349                        .unwrap_or(0)
2350                        .max(0);
2351                }
2352            }
2353        }
2354        let is_grid_lanes = resolved_display(node).contains("grid-lanes");
2355        let is_row_lanes = if is_grid_lanes {
2356            let dir = node.value_ref("grid-lanes-direction").map(str::trim).unwrap_or("");
2357            if !dir.is_empty() && !dir.eq_ignore_ascii_case("normal") {
2358                dir.to_ascii_lowercase().starts_with("row")
2359            } else {
2360                let has_rows = !t_rows.trim().is_empty() && !t_rows.trim().eq_ignore_ascii_case("none");
2361                let has_cols = !t_cols.trim().is_empty() && !t_cols.trim().eq_ignore_ascii_case("none");
2362                has_rows && !has_cols
2363            }
2364        } else {
2365            false
2366        };
2367        let lanes_col_axis = is_grid_lanes && !is_row_lanes;
2368        let lanes_row_axis = is_grid_lanes && is_row_lanes;
2369        // 列の定義。subgrid は親グリッドから渡されたトラック幅を固定列として使う。
2370        let sub_ctx_cols = if is_subgrid(t_cols) { get_subgrid_ctx() } else { None };
2371        let col_gap = match &sub_ctx_cols {
2372            Some(c) => {
2373                let has_own_gap = node.value_ref("gap").is_some()
2374                    || node.value_ref("column-gap").is_some()
2375                    || node.value_ref("grid-column-gap").is_some();
2376                if has_own_gap { col_gap } else { c.col_gap }
2377            }
2378            None => col_gap,
2379        };
2380        let font_px = self.font_size();
2381        let col_est = if t_cols.contains("auto-fill") || t_cols.contains("auto-fit") {
2382            let it = self
2383                .children
2384                .iter()
2385                .filter(|c| !Self::child_is_out_of_flow(c))
2386                .map(|c| {
2387                    let (mn, mx, _, _, _) = Self::grid_col_contrib(c);
2388                    if lanes_col_axis {
2389                        if t_cols.contains("min-content") && !t_cols.contains("auto") && !t_cols.contains("max-content") {
2390                            mn
2391                        } else {
2392                            mx
2393                        }
2394                    } else {
2395                        mn
2396                    }
2397                })
2398                .filter(|&w| w > 0);
2399            if lanes_col_axis {
2400                it.max().unwrap_or(0) as f32
2401            } else {
2402                it.min().unwrap_or(0) as f32
2403            }
2404        } else {
2405            0.0
2406        };
2407        let col_tpl = match &sub_ctx_cols {
2408            Some(c) => Template {
2409                tracks: c
2410                    .col_widths
2411                    .iter()
2412                    .map(|&w| TrackDef { min: Sz::Px(w as f32), max: Sz::Px(w as f32) })
2413                    .collect(),
2414                names: alloc::vec![Vec::new(); c.col_widths.len() + 1],
2415                auto_rep: None,
2416            },
2417            None if is_subgrid(t_cols) => parse_template_with_font("", None, None, 0, font_px),
2418            None => {
2419                let (col_avail, col_min) = if is_intrinsic_w && max_w_px.is_none() && min_w_px.is_some() {
2420                    (None, min_w_px)
2421                } else {
2422                    (Some(content_w), None)
2423                };
2424                parse_template_with_font_est(t_cols, Some(content_w), col_avail, col_gap, font_px, col_est, col_min)
2425            }
2426        };
2427        let row_est = if t_rows.contains("auto-fill") || t_rows.contains("auto-fit") {
2428            if lanes_row_axis {
2429                let _pct_off = PctBaseHGuard::set(-1);
2430                let mut mx = 0.0f32;
2431                for child in self.children.iter_mut() {
2432                    if Self::child_is_out_of_flow(child) {
2433                        continue;
2434                    }
2435                    let cell_cb = Dimensions {
2436                        content: Rect { x: base_x, y: base_y, width: content_w, height: 0 },
2437                        ..Dimensions::default()
2438                    };
2439                    child.layout(cell_cb);
2440                    mx = mx.max(child.dimensions.margin_box().height as f32);
2441                }
2442                mx
2443            } else {
2444                self.children
2445                    .iter()
2446                    .filter(|c| !Self::child_is_out_of_flow(c))
2447                    .filter_map(|c| {
2448                        let h = match parse_length_value(box_style_value_ref(c, "height")) {
2449                            Some(LengthValue::Px(px)) => px.max(0),
2450                            _ => match parse_length_value(box_style_value_ref(c, "min-height")) {
2451                                Some(LengthValue::Px(px)) => px.max(0),
2452                                _ => return None,
2453                            },
2454                        };
2455                        Some(h as f32)
2456                    })
2457                    .filter(|&h| h > 0.0)
2458                    .fold(None::<f32>, |acc, h| Some(acc.map_or(h, |a| a.min(h))))
2459                    .unwrap_or(0.0)
2460            }
2461        } else {
2462            0.0
2463        };
2464        let row_tpl = if is_subgrid(t_rows) {
2465            parse_template_with_font("", None, None, 0, font_px)
2466        } else {
2467            // 高さ未確定でも max-height(min で下限)→ min-height から繰り返し数を決める。
2468            let row_avail = container_h_explicit.or_else(|| max_h_px.map(|mx| mx.max(min_h_px.unwrap_or(0))));
2469            let row_min = if row_avail.is_none() { min_h_px } else { None };
2470            parse_template_with_font_est(t_rows, container_h_explicit, row_avail, row_gap, font_px, row_est, row_min)
2471        };
2472        let n_exp_rows = row_tpl.tracks.len().max(template_areas.len());
2473        let n_exp_cols = col_tpl
2474            .tracks
2475            .len()
2476            .max(template_areas.iter().map(|r| r.len()).max().unwrap_or(0));
2477        let mut row_names = row_tpl.names.clone();
2478        let mut col_names = col_tpl.names.clone();
2479        row_names.resize(n_exp_rows + 1, Vec::new());
2480        col_names.resize(n_exp_cols + 1, Vec::new());
2481        if !template_areas.is_empty() {
2482            add_area_line_names(&template_areas, &mut row_names, &mut col_names);
2483        }
2484        let auto_tracks = |prop: &str, base: Option<i32>| -> Vec<TrackDef> {
2485            let t = parse_template_with_font(node.value_ref(prop).unwrap_or(""), base, None, 0, font_px);
2486            if t.tracks.is_empty() { alloc::vec![TrackDef::AUTO] } else { t.tracks }
2487        };
2488        let auto_cols = auto_tracks("grid-auto-columns", Some(content_w));
2489        let auto_rows = auto_tracks("grid-auto-rows", container_h_explicit);
2490
2491        // コンテナの justify-items(インライン=列軸)/ align-items(ブロック=行軸)。
2492        let justify_items = node.value_ref("justify-items").unwrap_or("normal").trim();
2493        let align_items = node.value_ref("align-items").unwrap_or("normal").trim();
2494
2495        // ---- 配置の解決 ----
2496        let n_children = self.children.len();
2497        let mut placement: Vec<Option<(usize, usize, usize, usize)>> = alloc::vec![None; n_children];
2498        let flow = node.value_ref("grid-auto-flow").unwrap_or("");
2499        let col_flow = flow.split_whitespace().any(|t| t == "column");
2500        let dense = flow.split_whitespace().any(|t| t == "dense");
2501        let mut item_ids: Vec<usize> = Vec::new();
2502        let mut place_in: Vec<PlaceIn> = Vec::new();
2503        for (idx, child) in self.children.iter().enumerate() {
2504            if Self::child_is_out_of_flow(child) {
2505                continue;
2506            }
2507            let (rs, re, cs, ce) = read_item_lines(child);
2508            item_ids.push(idx);
2509            place_in.push(PlaceIn {
2510                row: resolve_axis(&rs, &re, &row_names, n_exp_rows),
2511                col: resolve_axis(&cs, &ce, &col_names, n_exp_cols),
2512            });
2513        }
2514        let placed = place_items(&place_in, n_exp_rows, n_exp_cols, col_flow, dense);
2515        for (k, &idx) in item_ids.iter().enumerate() {
2516            placement[idx] = placed.pos.get(k).copied();
2517        }
2518        let n_cols = placed.n_cols.max(n_exp_cols).max(usize::from(!item_ids.is_empty() && n_exp_cols == 0));
2519        let n_rows = placed.n_rows.max(n_exp_rows);
2520        let neg_cols = placed.neg_cols;
2521        let neg_rows = placed.neg_rows;
2522
2523        let col_defs = grid_build_defs(&col_tpl, n_cols, neg_cols, &auto_cols);
2524        let row_defs = grid_build_defs(&row_tpl, n_rows, neg_rows, &auto_rows);
2525        // auto-fit: アイテムの無い繰り返しトラックは 0 に畳む。
2526        let collapse = |tpl: &Template, neg: usize, n_total: usize, axis_col: bool| -> Vec<bool> {
2527            let mut v = alloc::vec![false; n_total];
2528            if let Some((first, cnt, true)) = tpl.auto_rep {
2529                for t in first + neg..(first + neg + cnt).min(n_total) {
2530                    let used = placement.iter().flatten().any(|&(r, c, rs, cs)| {
2531                        if axis_col { t >= c && t < c + cs } else { t >= r && t < r + rs }
2532                    });
2533                    v[t] = !used;
2534                }
2535            }
2536            v
2537        };
2538        let col_collapsed = collapse(&col_tpl, neg_cols, n_cols, true);
2539        let row_collapsed = collapse(&row_tpl, neg_rows, n_rows, false);
2540
2541        // ---- 列のサイズ決定 ----
2542        let jc_mode = node.value_ref("justify-content").unwrap_or("").trim();
2543        let ac_mode = node.value_ref("align-content").unwrap_or("").trim();
2544        let stretches = |m: &str| matches!(m, "" | "normal" | "stretch");
2545        let col_sizes: Vec<f32> = if let Some(c) = &sub_ctx_cols {
2546            (0..n_cols).map(|i| c.col_widths.get(i).copied().unwrap_or(0) as f32).collect()
2547        } else {
2548            let mut items: Vec<SizeItem> = Vec::new();
2549            let mut item_k = 0usize;
2550            for (idx, child) in self.children.iter().enumerate() {
2551                let Some((_, c, _, cs)) = placement[idx] else { continue };
2552                let is_auto_col = lanes_col_axis
2553                    && place_in.get(item_k).is_some_and(|p| matches!(p.col, AxisRes::Auto { .. }));
2554                item_k += 1;
2555                let (mn, mx, am, edges, no_clamp) = Self::grid_col_contrib(child);
2556                if is_auto_col && n_cols >= cs {
2557                    for cc in 0..=(n_cols - cs) {
2558                        items.push(SizeItem {
2559                            start: cc,
2560                            end: cc + cs,
2561                            min_c: mn as f32,
2562                            max_c: mx as f32,
2563                            auto_min: am as f32,
2564                            edges: edges as f32,
2565                            no_auto_clamp: no_clamp,
2566                        });
2567                    }
2568                } else {
2569                    items.push(SizeItem {
2570                        start: c,
2571                        end: c + cs,
2572                        min_c: mn as f32,
2573                        max_c: mx as f32,
2574                        auto_min: am as f32,
2575                        edges: edges as f32,
2576                        no_auto_clamp: no_clamp,
2577                    });
2578                }
2579            }
2580            size_tracks(
2581                &col_defs,
2582                &items,
2583                FreeSpace::Definite(content_w as f32),
2584                col_gap as f32,
2585                &col_collapsed,
2586                stretches(jc_mode),
2587            )
2588        };
2589        let layout_axis = |sizes: &[f32], defs: &[TrackDef], collapsed: &[bool], gap: i32, mode: &str, avail: f32, rtl: bool| {
2590            let n_live = collapsed.iter().filter(|&&c| !c).count();
2591            let gaps = if n_live > 1 { (n_live - 1) as f32 * gap as f32 } else { 0.0 };
2592            let used: f32 = sizes.iter().sum::<f32>() + gaps;
2593            let (off, extra) = content_distribution(mode, avail - used, n_live, rtl);
2594            let mut pos: Vec<i32> = Vec::with_capacity(sizes.len());
2595            let mut size_i: Vec<i32> = Vec::with_capacity(sizes.len());
2596            let mut x = off;
2597            let mut live_left = n_live;
2598            for (i, &sz0) in sizes.iter().enumerate() {
2599                // fr の大きさは切り捨て(端数はトラックの外へ残す。従来の挙動と同じ)。
2600                let is_fr = defs.get(i).is_some_and(|d| matches!(d.max, Sz::Fr(_)));
2601                let sz = if is_fr { libm::floorf(sz0 + 0.01) } else { sz0 };
2602                let p = round_f32_to_i32(x);
2603                pos.push(p);
2604                // 内容で決まるトラックの端は四捨五入で隣と揃える。
2605                size_i.push((round_f32_to_i32(x + sz) - p).max(0));
2606                if !collapsed.get(i).copied().unwrap_or(false) {
2607                    live_left -= 1;
2608                    x += sz;
2609                    if live_left > 0 {
2610                        x += gap as f32 + extra;
2611                    }
2612                } else {
2613                    x += sz;
2614                }
2615            }
2616            (pos, size_i, round_f32_to_i32(gap as f32 + extra))
2617        };
2618        let jc_mode_phys = if cur_world != 0 && matches!(jc_mode, "left" | "right") {
2619            let flip_i = (cur_world & 4) != 0;
2620            match (jc_mode, flip_i) {
2621                ("left", false) | ("right", true) => "start",
2622                _ => "end",
2623            }
2624        } else {
2625            jc_mode
2626        };
2627        let (col_pos, col_w, col_gap_eff) =
2628            layout_axis(&col_sizes, &col_defs, &col_collapsed, col_gap, jc_mode_phys, content_w as f32, is_rtl);
2629        let span_w = |c: usize, cs: usize| -> i32 {
2630            let e = (c + cs).min(col_pos.len());
2631            if c >= e {
2632                return 0;
2633            }
2634            (col_pos[e - 1] + col_w[e - 1] - col_pos[c]).max(0)
2635        };
2636        // 論理(LTR)の相対 x から物理 x へ(RTL は左右反転)。
2637        let cell_x_of = |c: usize, cs: usize| -> i32 {
2638            let lx = col_pos.get(c).copied().unwrap_or(0);
2639            if is_rtl {
2640                base_x + content_w - (lx + span_w(c, cs))
2641            } else {
2642                base_x + lx
2643            }
2644        };
2645
2646        // ---- 行の測定(列幅基準の仮レイアウト)----
2647        let mut row_items: Vec<SizeItem> = Vec::new();
2648        let has_v_auto_margin = |ch: &LayoutBox| -> bool {
2649            let (mt, mb) = Self::v_auto_margins(ch);
2650            mt || mb
2651        };
2652        let mut bl_items: Vec<(usize, usize, bool, i32, i32)> = Vec::new();
2653        let _pct_off = PctBaseHGuard::set(-1);
2654        let mut item_rk = 0usize;
2655        for (idx, child) in self.children.iter_mut().enumerate() {
2656            if Self::child_is_out_of_flow(child) {
2657                continue;
2658            }
2659            let Some((r, c, rs, cs)) = placement[idx] else {
2660                continue;
2661            };
2662            let is_auto_row = lanes_row_axis
2663                && place_in.get(item_rk).is_some_and(|p| matches!(p.row, AxisRes::Auto { .. }));
2664            item_rk += 1;
2665            let cell_w = span_w(c, cs);
2666            let cell_cb = Dimensions {
2667                content: Rect { x: cell_x_of(c, cs), y: base_y, width: cell_w, height: 0 },
2668                ..Dimensions::default()
2669            };
2670            let sub_ctx = Self::prepare_child_subgrid_ctx(child, &col_w, col_gap_eff, c, cs, cell_w);
2671            let is_sub = sub_ctx.is_some();
2672            let prev_ctx = if is_sub { set_subgrid_ctx(sub_ctx) } else { None };
2673            child.layout(cell_cb.clone());
2674            if is_sub {
2675                set_subgrid_ctx(prev_ctx);
2676            }
2677            let j_fit = Self::grid_justify(child, "justify-self", justify_items, is_rtl);
2678            if let Some(fw) = Self::grid_fit_outer_width(child, cell_w, j_fit) {
2679                let mut cb = cell_cb;
2680                cb.content.width = fw;
2681                GRID_PCT_BASE_W.store(cell_w, AtomicOrdering::Relaxed);
2682                child.layout(cb);
2683                GRID_PCT_BASE_W.store(-1, AtomicOrdering::Relaxed);
2684            }
2685            if let Some((num, den)) = box_aspect_ratio(child) {
2686                if num > 0.0 && den > 0.0 && !box_has_explicit(child, "height") {
2687                    let w = child.dimensions.content.width as f32;
2688                    let h = round_f32_to_i32(w * den / num).max(1);
2689                    child.dimensions.content.height = h;
2690                }
2691            }
2692            let mb = child.dimensions.margin_box();
2693            let non_content = mb.height - child.dimensions.content.height;
2694            let h = mb.height as f32;
2695            let auto_min = Self::grid_row_auto_min(child, h, non_content);
2696            let raw_al = Self::grid_raw_align(child, align_items);
2697            if rs == 1
2698                && !has_v_auto_margin(child)
2699                && super::baseline::baseline_enabled()
2700                && super::baseline::is_baseline_align(raw_al)
2701            {
2702                let is_last = super::baseline::is_last_baseline_align(raw_al);
2703                bl_items.push((row_items.len(), r, is_last, child.item_grid_baseline(cur_world), mb.height));
2704            }
2705            let has_non_pct_h = |prop: &str| {
2706                box_style_value_ref(child, prop).is_some_and(|v| {
2707                    let t = v.trim();
2708                    !t.is_empty() && !t.eq_ignore_ascii_case("auto") && !calc_size_is_auto(t) && !t.contains('%')
2709                })
2710            };
2711            let no_clamp_h = has_non_pct_h("height") || has_non_pct_h("min-height");
2712            if is_auto_row && n_rows >= rs {
2713                for rr in 0..=(n_rows - rs) {
2714                    row_items.push(SizeItem {
2715                        start: rr,
2716                        end: rr + rs,
2717                        min_c: h,
2718                        max_c: h,
2719                        auto_min,
2720                        edges: non_content.max(0) as f32,
2721                        no_auto_clamp: no_clamp_h,
2722                    });
2723                }
2724            } else {
2725                row_items.push(SizeItem {
2726                    start: r,
2727                    end: r + rs,
2728                    min_c: h,
2729                    max_c: h,
2730                    auto_min,
2731                    edges: non_content.max(0) as f32,
2732                    no_auto_clamp: no_clamp_h,
2733                });
2734            }
2735        }
2736        drop(_pct_off);
2737        // ベースライン整列の項目: first baseline と last baseline を分けて集計。
2738        let mut row_asc: Vec<i32> = Vec::new();
2739        let mut row_last_desc: Vec<i32> = Vec::new();
2740        if !bl_items.is_empty() {
2741            let mut row_desc: Vec<i32> = Vec::new();
2742            let mut row_last_asc: Vec<i32> = Vec::new();
2743            for &(_, r, is_last, asc, h) in &bl_items {
2744                if row_asc.len() <= r {
2745                    row_asc.resize(r + 1, 0);
2746                    row_desc.resize(r + 1, 0);
2747                    row_last_asc.resize(r + 1, 0);
2748                    row_last_desc.resize(r + 1, 0);
2749                }
2750                if is_last {
2751                    row_last_asc[r] = row_last_asc[r].max(asc);
2752                    row_last_desc[r] = row_last_desc[r].max(h - asc);
2753                } else {
2754                    row_asc[r] = row_asc[r].max(asc);
2755                    row_desc[r] = row_desc[r].max(h - asc);
2756                }
2757            }
2758            for &(ri, r, is_last, _, _) in &bl_items {
2759                let t = if is_last {
2760                    (row_last_asc[r] + row_last_desc[r]) as f32
2761                } else {
2762                    (row_asc[r] + row_desc[r]) as f32
2763                };
2764                if t > row_items[ri].max_c {
2765                    row_items[ri].min_c = t;
2766                    row_items[ri].max_c = t;
2767                }
2768            }
2769        }
2770
2771        // ---- 行のサイズ決定 ----
2772        let size_rows = |free: FreeSpace| -> Vec<f32> {
2773            size_tracks(&row_defs, &row_items, free, row_gap as f32, &row_collapsed, stretches(ac_mode))
2774        };
2775        let mut row_sizes: Vec<f32> = match container_h_explicit {
2776            Some(h) => size_rows(FreeSpace::Definite(h as f32)),
2777            None => {
2778                let s = size_rows(FreeSpace::Max);
2779                let n_live = row_collapsed.iter().filter(|&&c| !c).count();
2780                let total = s.iter().sum::<f32>() + if n_live > 1 { (n_live - 1) as f32 * row_gap as f32 } else { 0.0 };
2781                let mut tgt: Option<i32> = None;
2782                if let Some(mn) = min_h_px {
2783                    if total < mn as f32 {
2784                        tgt = Some(mn);
2785                    }
2786                }
2787                if let Some(mx) = max_h_px {
2788                    if total > mx as f32 {
2789                        tgt = Some(mx);
2790                    }
2791                }
2792                match tgt {
2793                    Some(h) => size_rows(FreeSpace::Definite(h as f32)),
2794                    None => s,
2795                }
2796            }
2797        };
2798        if row_sizes.len() != n_rows {
2799            row_sizes.resize(n_rows, 0.0);
2800        }
2801        let avail_h = match container_h_explicit {
2802            Some(h) => h as f32,
2803            None => {
2804                let n_live = row_collapsed.iter().filter(|&&c| !c).count();
2805                let total = row_sizes.iter().sum::<f32>() + if n_live > 1 { (n_live - 1) as f32 * row_gap as f32 } else { 0.0 };
2806                let mut h = total;
2807                if let Some(mn) = min_h_px {
2808                    h = h.max(mn as f32);
2809                }
2810                if let Some(mx) = max_h_px {
2811                    h = h.min(mx as f32);
2812                }
2813                h
2814            }
2815        };
2816        let ac_mode_phys = match ac_mode {
2817            "left" | "right" => "start",
2818            _ => ac_mode,
2819        };
2820        let (row_pos, row_h, _) =
2821            layout_axis(&row_sizes, &row_defs, &row_collapsed, row_gap, ac_mode_phys, avail_h, false);
2822        if let Some(out) = resolved_out {
2823            if !is_subgrid(t_cols) {
2824                out.0 = serialize_resolved_track_list(&col_sizes, &col_tpl.names, &col_collapsed, neg_cols);
2825            }
2826            if !is_subgrid(t_rows) {
2827                out.1 = serialize_resolved_track_list(&row_sizes, &row_tpl.names, &row_collapsed, neg_rows);
2828            }
2829            return;
2830        }
2831        let row_span_h = |r: usize, rs: usize| -> i32 {
2832            let e = (r + rs).min(row_pos.len());
2833            if r >= e {
2834                return 0;
2835            }
2836            (row_pos[e - 1] + row_h[e - 1] - row_pos[r]).max(0)
2837        };
2838
2839        // コンテナ高さを先に確定し、子孫の abspos/fixed が正しい包含ブロックを参照できるようにする。
2840        let natural_h = {
2841            let n_live = row_collapsed.iter().filter(|&&c| !c).count();
2842            let total = row_sizes.iter().sum::<f32>() + if n_live > 1 { (n_live - 1) as f32 * row_gap as f32 } else { 0.0 };
2843            round_f32_to_i32(total).max(0)
2844        };
2845        let mut final_h = container_h_explicit.unwrap_or(natural_h);
2846        if container_h_explicit.is_none() {
2847            if let Some(mx) = max_h_px {
2848                final_h = final_h.min(mx);
2849            }
2850            if let Some(mn) = min_h_px {
2851                final_h = final_h.max(mn);
2852            }
2853        }
2854        self.dimensions.content.height = final_h;
2855        let saved_abs_cb = self.establish_abs_cb();
2856
2857        // ---- 確定した位置で再レイアウト(整列・stretch)----
2858        struct AlignInfo {
2859            r: usize,
2860            c: usize,
2861            cell_w: i32,
2862            cell_h: i32,
2863            j: &'static str,
2864            a: &'static str,
2865            j_floor: i32,
2866            a_floor: i32,
2867            ml_auto: bool,
2868            mr_auto: bool,
2869            mt_auto: bool,
2870            mb_auto: bool,
2871            v_auto: bool,
2872            is_bl: bool,
2873            is_last_bl: bool,
2874            is_col_bl: bool,
2875            col_grp: u8,
2876            col_bl: i32,
2877        }
2878        let mut align_infos: Vec<Option<AlignInfo>> = (0..self.children.len()).map(|_| None).collect();
2879        let mut col_asc_0: Vec<i32> = Vec::new();
2880        let mut col_asc_1: Vec<i32> = Vec::new();
2881        for (idx, child) in self.children.iter_mut().enumerate() {
2882            if Self::child_is_out_of_flow(child) {
2883                // out-of-flow(absolute/fixed)はセルを消費しない。サイズ確定のため
2884                // レイアウトのみ行い、最終位置は apply_positioned_offsets で確定する。
2885                let oof_cb = Dimensions {
2886                    content: Rect { x: base_x, y: base_y, width: content_w, height: 0 },
2887                    ..Dimensions::default()
2888                };
2889                child.layout(oof_cb);
2890                continue;
2891            }
2892            let Some((r, c, rs, cs)) = placement[idx] else {
2893                continue;
2894            };
2895            let cell_w = span_w(c, cs);
2896            let cell_x = cell_x_of(c, cs);
2897            let cell_y = base_y + row_pos.get(r).copied().unwrap_or(0);
2898            let cell_h = row_span_h(r, rs);
2899
2900            // アイテムの整列を解決(justify=列/インライン軸、align=行/ブロック軸)。
2901            let (ml_auto, mr_auto) = Self::h_auto_margins(child);
2902            let j = if ml_auto || mr_auto {
2903                "start"
2904            } else {
2905                resolve_grid_axis_align(child, "justify-self", justify_items, cur_world, is_rtl_phys, true)
2906            };
2907            let raw_al = Self::grid_raw_align(child, align_items);
2908            let (mt_auto, mb_auto) = Self::v_auto_margins(child);
2909            let v_auto = mt_auto || mb_auto;
2910            let is_bl = rs == 1
2911                && !v_auto
2912                && (!row_asc.is_empty() || !row_last_desc.is_empty())
2913                && super::baseline::is_baseline_align(raw_al);
2914            let is_last_bl = is_bl && super::baseline::is_last_baseline_align(raw_al);
2915            let a = if is_bl || v_auto {
2916                "start"
2917            } else {
2918                resolve_grid_axis_align(child, "align-self", align_items, cur_world, is_rtl_phys, false)
2919            };
2920            let raw_j = match box_style_value_ref(child, "justify-self").map(str::trim) {
2921                Some(v) if !v.is_empty() && !v.eq_ignore_ascii_case("auto") => v,
2922                _ => justify_items.trim(),
2923            };
2924            let is_col_bl = cs == 1
2925                && !ml_auto
2926                && !mr_auto
2927                && super::baseline::baseline_enabled()
2928                && super::baseline::is_baseline_align(raw_j);
2929            // `safe` 指定がなければ溢れたときも負のオフセットで整列する(unsafe 相当)。
2930            let j_floor = if is_safe_align(raw_j) { 0 } else { i32::MIN };
2931            let a_floor = if is_safe_align(raw_al) { 0 } else { i32::MIN };
2932
2933            let cell_cb = Dimensions {
2934                content: Rect { x: cell_x, y: cell_y, width: cell_w, height: 0 },
2935                ..Dimensions::default()
2936            };
2937            let pct_h = Self::has_pct_height(child);
2938            if child.can_memo_subtree() && !pct_h && !subtree_has_pct_h_or_oof(child) {
2939                // 測定パスで同一の (cell_x, cell_w, height=0, subgrid_ctx, aspect-ratio) で
2940                // 既に base_y を起点にレイアウト済みのため、y 方向の平行移動のみで確定する。
2941                child.translate_y(cell_y - base_y);
2942            } else {
2943                let sub_ctx = Self::prepare_child_subgrid_ctx(child, &col_w, col_gap_eff, c, cs, cell_w);
2944                let is_sub = sub_ctx.is_some();
2945                let prev_ctx = if is_sub { set_subgrid_ctx(sub_ctx) } else { None };
2946                // `height:%` のアイテムはグリッドエリアの高さが基準(§6.2)。
2947                let _pct = PctBaseHGuard::set(if pct_h { cell_h } else { -1 });
2948                child.layout(cell_cb.clone());
2949                if is_sub {
2950                    set_subgrid_ctx(prev_ctx);
2951                }
2952                if let Some(fw) = Self::grid_fit_outer_width(child, cell_w, j) {
2953                    let mut cb = cell_cb;
2954                    cb.content.width = fw;
2955                    GRID_PCT_BASE_W.store(cell_w, AtomicOrdering::Relaxed);
2956                    child.layout(cb);
2957                    GRID_PCT_BASE_W.store(-1, AtomicOrdering::Relaxed);
2958                    if fw == 0 {
2959                        child.dimensions.content.width = 0;
2960                    }
2961                }
2962                if let Some((num, den)) = box_aspect_ratio(child) {
2963                    if num > 0.0 && den > 0.0 && !box_has_explicit(child, "height") {
2964                        let w = child.dimensions.content.width as f32;
2965                        let h = round_f32_to_i32(w * den / num).max(1);
2966                        child.dimensions.content.height = h;
2967                    }
2968                }
2969            }
2970            if j == "stretch"
2971                && matches!(child.box_type, BoxType::InlineBlockNode(_))
2972                && !box_has_explicit(child, "width")
2973                && box_aspect_ratio(child).is_none()
2974            {
2975                let non_c = child.h_non_content();
2976                child.dimensions.content.width = (cell_w - non_c).max(0);
2977            }
2978
2979            // align:stretch かつ高さ未指定なら、セル高さへ伸ばす(aspect-ratio 指定要素は除く)。
2980            if a == "stretch" && !box_has_explicit(child, "height") && box_aspect_ratio(child).is_none() {
2981                let mb = child.dimensions.margin_box();
2982                let non_content = mb.height - child.dimensions.content.height;
2983                let mut new_h = (cell_h - non_content).max(0);
2984                if let Some(LengthValue::Px(mx)) = parse_length_value(box_style_value_ref(child, "max-height")) {
2985                    let inner = if box_style_value_ref(child, "box-sizing").is_some_and(|v| v.trim() == "border-box") {
2986                        let d = &child.dimensions;
2987                        d.padding.top + d.padding.bottom + d.border.top + d.border.bottom
2988                    } else {
2989                        0
2990                    };
2991                    new_h = new_h.min((mx - inner).max(0));
2992                }
2993                child.dimensions.content.height = new_h;
2994            }
2995
2996            let (col_grp, col_bl) = if is_col_bl {
2997                let (grp, bl) = child.item_col_baseline(cur_world);
2998                if col_asc_0.len() <= c {
2999                    col_asc_0.resize(c + 1, 0);
3000                    col_asc_1.resize(c + 1, 0);
3001                }
3002                if grp == 1 {
3003                    col_asc_1[c] = col_asc_1[c].max(bl);
3004                } else {
3005                    col_asc_0[c] = col_asc_0[c].max(bl);
3006                }
3007                (grp, bl)
3008            } else {
3009                (0, 0)
3010            };
3011            align_infos[idx] = Some(AlignInfo {
3012                r,
3013                c,
3014                cell_w,
3015                cell_h,
3016                j,
3017                a,
3018                j_floor,
3019                a_floor,
3020                ml_auto,
3021                mr_auto,
3022                mt_auto,
3023                mb_auto,
3024                v_auto,
3025                is_bl,
3026                is_last_bl,
3027                is_col_bl,
3028                col_grp,
3029                col_bl,
3030            });
3031        }
3032
3033        // 第2段階: セル内整列(インライン軸=justify/列baseline, ブロック軸=align/行baseline)。
3034        for (idx, child) in self.children.iter_mut().enumerate() {
3035            let Some(inf) = align_infos[idx].take() else {
3036                continue;
3037            };
3038            let mb = child.dimensions.margin_box();
3039            let dx = if inf.ml_auto || inf.mr_auto {
3040                0
3041            } else if inf.is_col_bl {
3042                if inf.col_grp == 1 {
3043                    (inf.cell_w - mb.width) - (col_asc_1.get(inf.c).copied().unwrap_or(0) - inf.col_bl)
3044                } else {
3045                    (col_asc_0.get(inf.c).copied().unwrap_or(0) - inf.col_bl).max(0)
3046                }
3047            } else if inf.j == "stretch" {
3048                0
3049            } else {
3050                let free = (inf.cell_w - mb.width).max(inf.j_floor);
3051                match inf.j {
3052                    "center" => free / 2,
3053                    "end" => free,
3054                    _ => 0, // start
3055                }
3056            };
3057            let dy = if inf.is_last_bl {
3058                let desc = mb.height - child.item_grid_baseline(cur_world);
3059                let free = (inf.cell_h - mb.height).max(0);
3060                (free - (row_last_desc.get(inf.r).copied().unwrap_or(0) - desc)).max(0)
3061            } else if inf.is_bl {
3062                (row_asc.get(inf.r).copied().unwrap_or(0) - child.item_grid_baseline(cur_world)).max(0)
3063            } else if inf.v_auto {
3064                let free = (inf.cell_h - mb.height).max(0);
3065                match (inf.mt_auto, inf.mb_auto) {
3066                    (true, true) => free / 2,
3067                    (true, false) => free,
3068                    _ => 0,
3069                }
3070            } else if inf.a == "stretch" {
3071                0
3072            } else {
3073                let free = (inf.cell_h - mb.height).max(inf.a_floor);
3074                match inf.a {
3075                    "center" => free / 2,
3076                    "end" => free,
3077                    _ => 0, // start
3078                }
3079            };
3080            // RTL では物理 x がセルの右端起点になるので、start/end を入れ替える(列 baseline 時は自前方向を使う)。
3081            let dx = if inf.ml_auto || inf.mr_auto {
3082                // auto margin が余白を吸収する(左 auto なら右へ、両方 auto なら中央)。
3083                // ブロック配置は片側 auto でも左右均等に割り当てるので、非 auto 側の基礎マージンをスタイルから取り直す。
3084                let (style_l, style_r) = match &child.box_type {
3085                    BoxType::BlockNode(cn)
3086                    | BoxType::InlineNode(cn)
3087                    | BoxType::InlineBlockNode(cn)
3088                    | BoxType::FlexNode(cn)
3089                    | BoxType::GridNode(cn)
3090                    | BoxType::TableNode(cn)
3091                    | BoxType::TableRowGroupNode(cn)
3092                    | BoxType::TableRowNode(cn)
3093                    | BoxType::TableCellNode(cn) => {
3094                        let (m, _, _) = style_box_edges(cn, inf.cell_w, &Dimensions::default());
3095                        (m.left, m.right)
3096                    }
3097                    BoxType::AnonymousBlock => (0, 0),
3098                };
3099                let d = &mut child.dimensions;
3100                let cur_l = d.margin.left;
3101                let base_l = if inf.ml_auto { 0 } else { style_l };
3102                let base_r = if inf.mr_auto { 0 } else { style_r };
3103                let outer = d.content.width + d.padding.left + d.padding.right + d.border.left + d.border.right + base_l + base_r;
3104                let free = (inf.cell_w - outer).max(0);
3105                let (add_l, add_r) = match (inf.ml_auto, inf.mr_auto) {
3106                    (true, true) => (free / 2, free - free / 2),
3107                    (true, false) => (free, 0),
3108                    _ => (0, free),
3109                };
3110                d.margin.left = base_l + add_l;
3111                d.margin.right = base_r + add_r;
3112                d.margin.left - cur_l
3113            } else if is_rtl && !inf.is_col_bl {
3114                let free = (inf.cell_w - mb.width).max(inf.j_floor);
3115                free - dx
3116            } else {
3117                dx
3118            };
3119            if dx != 0 || dy != 0 {
3120                shift_layout_box(child, dx, dy);
3121            }
3122        }
3123
3124        // positioned 子要素の配置(grid コンテナを包含ブロック起点にできる)。
3125        // grid コンテナが absolute / fixed の包含ブロックなら、子の grid-row/column が指す
3126        // グリッドエリアが包含ブロックになる(CSS Grid §9.1。線が auto/範囲外の辺は padding 端)。
3127        let mut abs_areas: Vec<Option<(i32, i32, i32, i32)>> = Vec::new();
3128        let est_abs = box_establishes_abs_cb(self);
3129        let est_fixed = box_establishes_fixed_cb(self);
3130        if (est_abs && self.children.iter().any(|c| box_position(c) == "absolute"))
3131            || (est_fixed && self.children.iter().any(|c| box_position(c) == "fixed"))
3132        {
3133            let pb = self.dimensions.padding_box();
3134            let n_c = col_pos.len();
3135            let n_r = row_pos.len();
3136            // 線 k の x(論理)。start 辺は k 番目トラックの先頭、end 辺は k-1 番目トラックの末尾。
3137            let col_line_start = |k: usize| -> i32 {
3138                if k < n_c { col_pos[k] } else { col_pos.get(n_c.wrapping_sub(1)).map_or(0, |p| p + col_w[n_c - 1]) }
3139            };
3140            let col_line_end = |k: usize| -> i32 {
3141                if let Some(j) = (0..k.min(n_c)).rfind(|&idx| !col_collapsed.get(idx).copied().unwrap_or(false)) {
3142                    col_pos[j] + col_w[j]
3143                } else {
3144                    col_pos.first().copied().unwrap_or(0)
3145                }
3146            };
3147            let row_line_start = |k: usize| -> i32 {
3148                if k < n_r { row_pos[k] } else { row_pos.get(n_r.wrapping_sub(1)).map_or(0, |p| p + row_h[n_r - 1]) }
3149            };
3150            let row_line_end = |k: usize| -> i32 {
3151                if let Some(j) = (0..k.min(n_r)).rfind(|&idx| !row_collapsed.get(idx).copied().unwrap_or(false)) {
3152                    row_pos[j] + row_h[j]
3153                } else {
3154                    row_pos.first().copied().unwrap_or(0)
3155                }
3156            };
3157            abs_areas = self
3158                .children
3159                .iter()
3160                .map(|child| {
3161                    let pos = box_position(child);
3162                    if !((pos == "absolute" && est_abs) || (pos == "fixed" && est_fixed)) {
3163                        return None;
3164                    }
3165                    let (rs, re, cs, ce) = read_item_lines(child);
3166                    let (cl0, cl1) = abspos_lines(&cs, &ce, &col_names, n_exp_cols, neg_cols, n_c);
3167                    let (rl0, rl1) = abspos_lines(&rs, &re, &row_names, n_exp_rows, neg_rows, n_r);
3168                    // 論理 x → 物理 x。
3169                    let phys = |lx0: i32, lx1: i32| -> (i32, i32) {
3170                        if is_rtl {
3171                            (base_x + content_w - lx1, base_x + content_w - lx0)
3172                        } else {
3173                            (base_x + lx0, base_x + lx1)
3174                        }
3175                    };
3176                    let (mut left, mut right) = (pb.x, pb.x + pb.width);
3177                    match (cl0, cl1) {
3178                        (Some(a), Some(b)) => {
3179                            let (l, r) = phys(col_line_start(a), col_line_end(b));
3180                            left = l;
3181                            right = r;
3182                        }
3183                        (Some(a), None) => {
3184                            let (l, r) = phys(col_line_start(a), col_line_start(a));
3185                            if is_rtl { right = r } else { left = l }
3186                        }
3187                        (None, Some(b)) => {
3188                            let (l, r) = phys(col_line_end(b), col_line_end(b));
3189                            if is_rtl { left = l } else { right = r }
3190                        }
3191                        (None, None) => {}
3192                    }
3193                    let top = rl0.map(row_line_start).map_or(pb.y, |v| base_y + v);
3194                    let bottom = rl1.map(row_line_end).map_or(pb.y + pb.height, |v| base_y + v);
3195                    Some((left, top, (right - left).max(0), (bottom - top).max(0)))
3196                })
3197                .collect();
3198        }
3199        let rel_cells: Vec<Option<(i32, i32)>> = placement
3200            .iter()
3201            .map(|p| p.map(|(r, c, rs, cs)| (span_w(c, cs), row_span_h(r, rs))))
3202            .collect();
3203        self.apply_positioned_offsets_grid(
3204            if abs_areas.is_empty() { None } else { Some(&abs_areas) },
3205            Some(&rel_cells),
3206            true,
3207        );
3208        Self::restore_abs_cb(saved_abs_cb);
3209    }
3210
3211    /// グリッドアイテムの列軸の寄与 (min-content, max-content, 自動最小, 外縁, 自動最小クランプ禁止)。
3212    fn grid_col_contrib(child: &LayoutBox) -> (i32, i32, i32, i32, bool) {
3213        let explicit = match parse_length_value(box_style_value_ref(child, "width")) {
3214            Some(LengthValue::Px(px)) => Some(px.max(0)),
3215            _ => None,
3216        };
3217        let (mut cmin, cmax) = explicit.map(|w| (w, w)).unwrap_or_else(|| child.block_intrinsic_widths());
3218        if explicit.is_none()
3219            && is_replaced_element(child)
3220            && box_style_value_ref(child, "max-width").is_some_and(|v| v.contains('%'))
3221        {
3222            cmin = 0;
3223        }
3224        let (cmin, cmax) = clamp_contribution(child, cmin, cmax, explicit.is_none());
3225        let edges = intrinsic_h_edges(child, explicit.is_some());
3226        let node_ref = match &child.box_type {
3227            BoxType::BlockNode(n)
3228            | BoxType::InlineNode(n)
3229            | BoxType::InlineBlockNode(n)
3230            | BoxType::FlexNode(n)
3231            | BoxType::GridNode(n)
3232            | BoxType::TableNode(n)
3233            | BoxType::TableRowGroupNode(n)
3234            | BoxType::TableRowNode(n)
3235            | BoxType::TableCellNode(n) => Some(*n),
3236            BoxType::AnonymousBlock => None,
3237        };
3238        let inner = border_box_inner_w(child);
3239        let mut cmin = cmin;
3240        let mut auto_min = cmin;
3241        if let Some(n) = node_ref {
3242            let scroll_container = ["overflow", "overflow-x"]
3243                .iter()
3244                .any(|k| n.value_ref(k).is_some_and(|v| matches!(v.trim(), "hidden" | "scroll" | "auto")));
3245            if let Some(LengthValue::Px(mw)) = parse_length_value(box_style_value_ref(child, "min-width")) {
3246                // 明示的な width がある項目の最小寄与は min-content 寄与(= その width)で、
3247                // min-width では置き換えない。
3248                auto_min = if explicit.is_some() { cmin } else { (mw - inner).max(0) };
3249                // 明示的な width が無い場合のみ min-width を min-content 寄与の下限/上書きに使う
3250                if explicit.is_none() {
3251                    cmin = cmin.max(auto_min);
3252                }
3253            } else if scroll_container {
3254                auto_min = 0;
3255            } else if let Some(w) = explicit {
3256                auto_min = auto_min.min(w);
3257            }
3258            if let Some(LengthValue::Px(mx)) = parse_length_value(box_style_value_ref(child, "max-width")) {
3259                auto_min = auto_min.min((mx - inner).max(0));
3260            }
3261        }
3262        let has_non_pct = |prop: &str| {
3263            box_style_value_ref(child, prop).is_some_and(|v| {
3264                let t = v.trim();
3265                !t.is_empty() && !t.eq_ignore_ascii_case("auto") && !calc_size_is_auto(t) && !t.contains('%')
3266            })
3267        };
3268        let no_auto_clamp = has_non_pct("width") || has_non_pct("min-width");
3269        (cmin + edges, cmax + edges, auto_min + edges, edges, no_auto_clamp)
3270    }
3271
3272    /// 行軸の自動最小(スクロールコンテナは 0、`min-height` の指定があればそれ)。
3273    fn grid_row_auto_min(child: &LayoutBox, h: f32, non_content: i32) -> f32 {
3274        let scroll_container = match &child.box_type {
3275            BoxType::BlockNode(n) | BoxType::FlexNode(n) | BoxType::GridNode(n) | BoxType::InlineBlockNode(n) => {
3276                ["overflow", "overflow-y"]
3277                    .iter()
3278                    .any(|k| n.value_ref(k).is_some_and(|v| matches!(v.trim(), "hidden" | "scroll" | "auto")))
3279            }
3280            _ => false,
3281        };
3282        if box_has_explicit(child, "height") {
3283            return h.max(0.0);
3284        }
3285        if let Some(LengthValue::Px(mh)) = parse_length_value(box_style_value_ref(child, "min-height")) {
3286            let inner = if box_style_value_ref(child, "box-sizing").is_some_and(|v| v.trim() == "border-box") {
3287                0
3288            } else {
3289                non_content
3290            };
3291            return ((mh + inner) as f32).min(h.max(0.0)).max(0.0);
3292        }
3293        if scroll_container { non_content.max(0) as f32 } else { h }
3294    }
3295
3296    /// 現在の世界 `CUR_WORLD` における論理辺ペアの `margin` が `auto` か。
3297    /// `logical_x = true`: `(left, right)`, `false`: `(top, bottom)`。
3298    fn logical_auto_margins(child: &LayoutBox, logical_x: bool) -> (bool, bool) {
3299        let cur_world = crate::os_lib::css::CUR_WORLD.load(AtomicOrdering::Relaxed);
3300        let toks: Vec<&str> = box_style_value_ref(child, "margin").unwrap_or("").split_whitespace().collect();
3301        let n = toks.len();
3302        let short_for_phys = |phys_side: usize| -> Option<usize> {
3303            match (n, phys_side) {
3304                (0, _) => None,
3305                (1, _) => Some(0),
3306                (2, 0 | 2) => Some(0),
3307                (2, _) => Some(1),
3308                (3, 0) => Some(0),
3309                (3, 2) => Some(2),
3310                (3, _) => Some(1),
3311                (_, s) => Some(s.min(n - 1)),
3312            }
3313        };
3314        let is_auto = |log_prop: &str, log_side: usize| -> bool {
3315            match box_style_value_ref(child, log_prop) {
3316                Some(v) => v.trim().eq_ignore_ascii_case("auto"),
3317                None => {
3318                    let phys = crate::os_lib::css::world_phys_side(cur_world, log_side);
3319                    short_for_phys(phys).is_some_and(|i| toks[i].eq_ignore_ascii_case("auto"))
3320                }
3321            }
3322        };
3323        if logical_x {
3324            (is_auto("margin-left", 3), is_auto("margin-right", 1))
3325        } else {
3326            (is_auto("margin-top", 0), is_auto("margin-bottom", 2))
3327        }
3328    }
3329
3330    /// 論理左右(インライン軸)の `margin` が `auto` か。
3331    fn h_auto_margins(child: &LayoutBox) -> (bool, bool) {
3332        Self::logical_auto_margins(child, true)
3333    }
3334
3335    /// 論理上下(ブロック軸)の `margin` が `auto` か。
3336    fn v_auto_margins(child: &LayoutBox) -> (bool, bool) {
3337        Self::logical_auto_margins(child, false)
3338    }
3339
3340    /// `justify-self` / `justify-items` の解決。
3341    fn grid_justify(child: &LayoutBox, self_prop: &str, items_default: &str, rtl: bool) -> &'static str {
3342        let (ml, mr) = Self::h_auto_margins(child);
3343        if ml || mr {
3344            return "start";
3345        }
3346        let cur_world = crate::os_lib::css::CUR_WORLD.load(AtomicOrdering::Relaxed);
3347        resolve_grid_axis_align(child, self_prop, items_default, cur_world, rtl, true)
3348    }
3349
3350    /// アイテムの `align-self`(auto/未指定ならコンテナの `align-items`)の生の値。
3351    fn grid_raw_align<'b>(child: &LayoutBox<'b>, items_default: &'b str) -> &'b str {
3352        match box_style_value_ref(child, "align-self").map(str::trim) {
3353            Some(v) if !v.is_empty() && !v.eq_ignore_ascii_case("auto") => v,
3354            _ => items_default,
3355        }
3356    }
3357
3358    /// `height` / `min-height` / `max-height` に `%` を使っているか。
3359    fn has_pct_height(child: &LayoutBox) -> bool {
3360        ["height", "min-height", "max-height"]
3361            .iter()
3362            .any(|p| box_style_value_ref(child, p).is_some_and(|v| v.contains('%')))
3363    }
3364
3365    fn layout_table(&mut self, containing_block: Dimensions) {
3366        self.apply_box_model_styles_with_base(containing_block.content.width);
3367
3368        let h_non_content = self.dimensions.margin.left
3369            + self.dimensions.margin.right
3370            + self.dimensions.border.left
3371            + self.dimensions.border.right
3372            + self.dimensions.padding.left
3373            + self.dimensions.padding.right;
3374        let avail = (containing_block.content.width - h_non_content).max(1);
3375
3376        // テーブル幅: width 指定があれば尊重、なければ利用幅
3377        let table_width = match &self.box_type {
3378            BoxType::TableNode(node) => match parse_length_value(len_value(node, "width")) {
3379                Some(LengthValue::Px(px)) => px.max(1).min(avail),
3380                Some(LengthValue::Percent(pct)) => round_f32_to_i32(avail as f32 * pct).max(1),
3381                _ => avail,
3382            },
3383            _ => avail,
3384        };
3385
3386        // 位置 (block と同じ規約)
3387        let flow_y = containing_block.content.y
3388            + containing_block.content.height
3389            + self.dimensions.margin.top;
3390        self.dimensions.content.x = containing_block.content.x
3391            + self.dimensions.margin.left
3392            + self.dimensions.border.left
3393            + self.dimensions.padding.left;
3394        self.dimensions.content.y =
3395            flow_y + self.dimensions.border.top + self.dimensions.padding.top;
3396        self.dimensions.content.width = table_width;
3397
3398        let base_x = self.dimensions.content.x;
3399
3400        // border-collapse: collapse 時は隣接セルの境界を 1px 重ねて二重線を解消する。
3401        let collapse = match &self.box_type {
3402            BoxType::TableNode(node) => node
3403                .value_ref("border-collapse")
3404                .map(|v| v.trim().eq_ignore_ascii_case("collapse"))
3405                .unwrap_or(false),
3406            _ => false,
3407        };
3408        let collapse_px: i32 = if collapse { 1 } else { 0 };
3409
3410        // table-layout: fixed 時は最初の行の各セルの明示 width のみで列幅を決定し、
3411        // 内容の計測(intrinsic_inline_size)を行わない(仕様通り、パフォーマンス目的の機能)。
3412        // 未指定の列は auto 列として残りの利用可能幅を均等に分け合う。
3413        let table_layout_fixed = match &self.box_type {
3414            BoxType::TableNode(node) => node
3415                .value_ref("table-layout")
3416                .map(|v| v.trim().eq_ignore_ascii_case("fixed"))
3417                .unwrap_or(false),
3418            _ => false,
3419        };
3420
3421        // border-spacing: セル間の隙間(px)。border-collapse:collapse では無効。
3422        // `10px`(水平・垂直共通)/ `10px 5px`(水平 垂直)の2形式に対応。
3423        let (h_spacing, v_spacing): (i32, i32) = if collapse {
3424            (0, 0)
3425        } else {
3426            match &self.box_type {
3427                BoxType::TableNode(node) => match node.value_ref("border-spacing") {
3428                    Some(v) => {
3429                        let px = |s: &str| -> i32 {
3430                            match parse_length_value(Some(s)) {
3431                                Some(LengthValue::Px(px)) => px.max(0),
3432                                _ => 0,
3433                            }
3434                        };
3435                        let mut it = v.split_whitespace();
3436                        match (it.next(), it.next()) {
3437                            (Some(h), None) => (px(h), px(h)),
3438                            (Some(h), Some(w)) => (px(h), px(w)),
3439                            _ => (0, 0),
3440                        }
3441                    }
3442                    // UA 既定 `table { border-spacing: 2px }`(HTML §15.3.10。以前は 0)。
3443                    None => (2, 2),
3444                },
3445                _ => (0, 0),
3446            }
3447        };
3448
3449        // caption (<caption>) は既定でテーブル本体の上に積むが、`caption-side:bottom` なら
3450        // 本体の下へ配置する。後者は行の高さが確定してから配置する必要があるため、
3451        // 先頭 caption 自身の caption-side を見て分岐する。
3452        let caption_indices: Vec<usize> = (0..self.children.len())
3453            .filter(|&i| box_tag_name(&self.children[i]) == Some("caption"))
3454            .collect();
3455        let caption_side_bottom = caption_indices
3456            .first()
3457            .and_then(|&ci| box_style_value_ref(&self.children[ci], "caption-side"))
3458            .map(|v| v.trim().eq_ignore_ascii_case("bottom"))
3459            .unwrap_or(false);
3460        let mut top_offset = 0i32;
3461        if !caption_side_bottom {
3462            let y = self.dimensions.content.y;
3463            top_offset = self.layout_captions_at(&caption_indices, base_x, y, table_width);
3464        }
3465        let rows_top = self.dimensions.content.y + top_offset;
3466
3467        // 行 (tr) を抽出。セルは行の children。
3468        // `visibility:collapse` の行は display:none 相当に扱い、他の行を詰めて配置する
3469        // (実ブラウザは列幅の再計算まではしない簡略実装だが、行自体を除去する点は同じ)。
3470        let row_indices: Vec<usize> = (0..self.children.len())
3471            .filter(|&i| {
3472                matches!(self.children[i].box_type, BoxType::TableRowNode(_))
3473                    && box_style_value_ref(&self.children[i], "visibility")
3474                        .map(|v| !v.trim().eq_ignore_ascii_case("collapse"))
3475                        .unwrap_or(true)
3476            })
3477            .collect();
3478        let nrows = row_indices.len();
3479
3480        // --- グリッド構築: colspan/rowspan を解決して各セルの (列, 行, span) を確定 ---
3481        struct CellPlace {
3482            row_ord: usize,
3483            cell_ord: usize,
3484            col: usize,
3485            colspan: usize,
3486            rowspan: usize,
3487        }
3488        let mut occ: Vec<Vec<bool>> = Vec::new();
3489        let mut places: Vec<CellPlace> = Vec::new();
3490        let mut ncols = 0usize;
3491        for (row_ord, &ri) in row_indices.iter().enumerate() {
3492            let ncells = self.children[ri].children.len();
3493            let mut c = 0usize;
3494            for cell_ord in 0..ncells {
3495                // rowspan で先行行から占有されている列を読み飛ばす
3496                while occ_is(&occ, row_ord, c) {
3497                    c += 1;
3498                }
3499                let (cs, rs) = cell_spans(&self.children[ri].children[cell_ord]);
3500                let rs = rs.min(nrows - row_ord); // テーブル末尾を超える rowspan はクランプ
3501                for rr in row_ord..(row_ord + rs) {
3502                    for cc in c..(c + cs) {
3503                        occ_mark(&mut occ, rr, cc);
3504                    }
3505                }
3506                places.push(CellPlace {
3507                    row_ord,
3508                    cell_ord,
3509                    col: c,
3510                    colspan: cs,
3511                    rowspan: rs.max(1),
3512                });
3513                c += cs;
3514                ncols = ncols.max(c);
3515            }
3516        }
3517
3518        if ncols == 0 {
3519            if caption_side_bottom {
3520                let y = self.dimensions.content.y + top_offset;
3521                top_offset += self.layout_captions_at(&caption_indices, base_x, y, table_width);
3522            }
3523            self.dimensions.content.height = top_offset;
3524            return;
3525        }
3526
3527        // --- 列幅: まず colspan==1 のセルで基礎幅、次に colspan>1 の不足分を分配 ---
3528        let mut col_w = alloc::vec![0i32; ncols];
3529        let mut is_fixed_col = alloc::vec![false; ncols];
3530        // 列幅にはセル自身の左右の padding・border を足す(以前は「既定 padding 4px*2 + 余裕」の決め打ち 24 だった)。
3531        let cell_h_edges = |cell: &LayoutBox| -> i32 {
3532            match &cell.box_type {
3533                BoxType::TableCellNode(n) => {
3534                    let (_, p, b) = style_box_edges(n, table_width, &Dimensions::default());
3535                    (p.left + p.right + b.left + b.right).max(0)
3536                }
3537                _ => 0,
3538            }
3539        };
3540        // border-spacing は列の間だけでなく、表の縁と端の列の間にも入る(CSS 2.1 §17.6.1)。
3541        let usable_width = (table_width - h_spacing * (ncols as i32 + 1)).max(1);
3542
3543        if table_layout_fixed {
3544            // table-layout:fixed: 最初の行(row_ord==0)の colspan==1 セルの明示 width のみで
3545            // 列幅を決定し、内容の計測は一切行わない(仕様通り、パフォーマンス目的の機能)。
3546            for p in &places {
3547                if p.row_ord != 0 || p.colspan != 1 {
3548                    continue;
3549                }
3550                let cell = &self.children[row_indices[p.row_ord]].children[p.cell_ord];
3551                if let Some(w) = box_style_value_ref(cell, "width") {
3552                    match parse_length_value(Some(w)) {
3553                        Some(LengthValue::Px(px)) => {
3554                            col_w[p.col] = px.max(1);
3555                            is_fixed_col[p.col] = true;
3556                        }
3557                        Some(LengthValue::Percent(pct)) => {
3558                            col_w[p.col] = round_f32_to_i32(usable_width as f32 * pct).max(1);
3559                            is_fixed_col[p.col] = true;
3560                        }
3561                        _ => {}
3562                    }
3563                }
3564            }
3565            // auto 列(明示 width の無い列)は、固定列を除いた残り幅を均等に分け合う。
3566            let fixed_sum: i32 = (0..ncols).filter(|&c| is_fixed_col[c]).map(|c| col_w[c]).sum();
3567            let auto_cols: alloc::vec::Vec<usize> =
3568                (0..ncols).filter(|&c| !is_fixed_col[c]).collect();
3569            if !auto_cols.is_empty() {
3570                let remaining = (usable_width - fixed_sum).max(0);
3571                let auto_w = (remaining / auto_cols.len() as i32).max(1);
3572                let mut assigned = 0i32;
3573                for (i, &c) in auto_cols.iter().enumerate() {
3574                    if i == auto_cols.len() - 1 {
3575                        col_w[c] = (remaining - assigned).max(1);
3576                    } else {
3577                        col_w[c] = auto_w;
3578                        assigned += auto_w;
3579                    }
3580                }
3581            }
3582        } else {
3583            for p in &places {
3584                if p.colspan != 1 {
3585                    continue;
3586                }
3587                let cell = &self.children[row_indices[p.row_ord]].children[p.cell_ord];
3588                let (cw, _) = cell.intrinsic_inline_size(table_width);
3589                col_w[p.col] = col_w[p.col].max(cw + cell_h_edges(cell));
3590            }
3591            for p in &places {
3592                if p.colspan <= 1 {
3593                    continue;
3594                }
3595                let cell = &self.children[row_indices[p.row_ord]].children[p.cell_ord];
3596                let (cw, _) = cell.intrinsic_inline_size(table_width);
3597                let need = cw + cell_h_edges(cell);
3598                let cur: i32 = col_w[p.col..p.col + p.colspan].iter().sum();
3599                if need > cur {
3600                    let deficit = need - cur;
3601                    let add = deficit / p.colspan as i32;
3602                    for cc in p.col..p.col + p.colspan {
3603                        col_w[cc] += add;
3604                    }
3605                    col_w[p.col] += deficit - add * p.colspan as i32; // 端数は先頭列へ
3606                }
3607            }
3608
3609            // 総和を利用可能幅に合わせる (超過→比例縮小 / 不足→均等加算、端数補正込み)。
3610            let total: i32 = col_w.iter().sum::<i32>().max(1);
3611            if total > usable_width {
3612                let mut assigned = 0i32;
3613                for (c, w) in col_w.iter_mut().enumerate() {
3614                    if c == ncols - 1 {
3615                        *w = (usable_width - assigned).max(1);
3616                    } else {
3617                        let scaled = ((*w as i64 * usable_width as i64) / total as i64).max(1) as i32;
3618                        *w = scaled;
3619                        assigned += scaled;
3620                    }
3621                }
3622            } else if total < usable_width {
3623                // 余りは本当の合計から出す(`total` は割り算用に 1 以上へ丸めてあり、全列 0 だと 1px ずれた)。
3624                let diff = usable_width - col_w.iter().sum::<i32>();
3625                let add = diff / ncols as i32;
3626                let mut distributed = 0i32;
3627                for c in 0..ncols {
3628                    if c == ncols - 1 {
3629                        col_w[c] += diff - distributed;
3630                    } else {
3631                        col_w[c] += add;
3632                        distributed += add;
3633                    }
3634                }
3635            }
3636        }
3637        // 列開始 x オフセット(列間に border-spacing を挿入)
3638        let mut col_x = alloc::vec![0i32; ncols];
3639        let mut acc = h_spacing;
3640        for c in 0..ncols {
3641            col_x[c] = acc;
3642            acc += col_w[c];
3643            if c + 1 < ncols {
3644                acc += h_spacing;
3645            }
3646        }
3647        let span_w = |col: usize, colspan: usize| -> i32 {
3648            col_w[col..(col + colspan).min(ncols)].iter().sum::<i32>()
3649                + h_spacing * colspan.saturating_sub(1) as i32
3650        };
3651
3652        // --- 高さ計測パス: 各セルを確定列幅でレイアウトして外形高さを得る ---
3653        let mut place_h = alloc::vec![0i32; places.len()];
3654        for (pi, p) in places.iter().enumerate() {
3655            let cw_total = span_w(p.col, p.colspan);
3656            let cell = &mut self.children[row_indices[p.row_ord]].children[p.cell_ord];
3657            let mut cb = Dimensions::default();
3658            cb.content.x = base_x + col_x[p.col];
3659            cb.content.y = rows_top;
3660            cb.content.height = 0;
3661            cb.content.width = cw_total;
3662            cell.layout(cb);
3663            place_h[pi] = cell.dimensions.margin_box().height;
3664        }
3665        // 行高さ: rowspan==1 で確定、rowspan>1 は不足分を最終行へ加算
3666        let mut row_h = alloc::vec![0i32; nrows];
3667        for (pi, p) in places.iter().enumerate() {
3668            if p.rowspan == 1 {
3669                row_h[p.row_ord] = row_h[p.row_ord].max(place_h[pi]);
3670            }
3671        }
3672        for (pi, p) in places.iter().enumerate() {
3673            if p.rowspan <= 1 {
3674                continue;
3675            }
3676            let end = (p.row_ord + p.rowspan).min(nrows);
3677            let cur: i32 = row_h[p.row_ord..end].iter().sum();
3678            if place_h[pi] > cur {
3679                row_h[end - 1] += place_h[pi] - cur;
3680            }
3681        }
3682        // 行 y 先頭オフセット (テーブル本体内の相対、行間に border-spacing を挿入)
3683        let mut row_y = alloc::vec![0i32; nrows];
3684        let mut accy = v_spacing;
3685        for r in 0..nrows {
3686            row_y[r] = accy;
3687            accy += row_h[r];
3688            if r + 1 < nrows {
3689                accy += v_spacing;
3690            }
3691        }
3692        let rows_total = if nrows > 0 { accy + v_spacing } else { 0 };
3693
3694        // --- 確定パス: 各セルを最終位置で再レイアウトし、列幅・スパン行高さに合わせる ---
3695        for p in places.iter() {
3696            let cw_total = span_w(p.col, p.colspan);
3697            let end_r = (p.row_ord + p.rowspan).min(nrows);
3698            let span_h: i32 = row_h[p.row_ord..end_r].iter().sum();
3699            let x0 = base_x + col_x[p.col] - collapse_px * p.col as i32;
3700            let y0 = rows_top + row_y[p.row_ord] - collapse_px * p.row_ord as i32;
3701            let cell = &mut self.children[row_indices[p.row_ord]].children[p.cell_ord];
3702            if cell.can_memo_subtree() {
3703                // 高さ計測パスで (base_x + col_x[p.col], rows_top, cw_total, height=0) にて
3704                // レイアウト済みのため、最終位置への平行移動のみで確定する。
3705                cell.translate(x0 - (base_x + col_x[p.col]), y0 - rows_top);
3706            } else {
3707                let mut cb = Dimensions::default();
3708                cb.content.x = x0;
3709                cb.content.y = y0;
3710                cb.content.height = 0;
3711                cb.content.width = cw_total;
3712                cell.layout(cb); // 子要素を最終位置で配置し直す
3713            }
3714            let w_extra = cell.dimensions.padding.left
3715                + cell.dimensions.padding.right
3716                + cell.dimensions.border.left
3717                + cell.dimensions.border.right;
3718            let h_extra = cell.dimensions.padding.top
3719                + cell.dimensions.padding.bottom
3720                + cell.dimensions.border.top
3721                + cell.dimensions.border.bottom;
3722            // vertical-align: middle/bottom — 行がセルの自然な高さより高い場合、
3723            // 余った縦方向の空間分だけ子孫全体を下へ平行移動する(既定/top/baseline は無移動)。
3724            let natural_h = cell.dimensions.content.height;
3725            let target_h = (span_h - h_extra).max(natural_h);
3726            let extra_space = (target_h - natural_h).max(0);
3727            if extra_space > 0 {
3728                let va = match &cell.box_type {
3729                    BoxType::TableCellNode(node) => node.value_ref("vertical-align").unwrap_or(""),
3730                    _ => "",
3731                };
3732                let dy = match va.trim() {
3733                    "middle" | "center" => extra_space / 2,
3734                    "bottom" => extra_space,
3735                    _ => 0, // top / baseline(簡略化) / 未指定
3736                };
3737                // セル自身の box(背景・境界)は行の先頭に留め、中身(子要素)だけを下げる。
3738                for child in &mut cell.children {
3739                    child.translate_y(dy);
3740                }
3741            }
3742            cell.dimensions.content.width = (cw_total - w_extra).max(1);
3743            cell.dimensions.content.height = target_h;
3744        }
3745
3746        // 行ボックスの寸法を設定 (背景・境界の整列用)
3747        for (row_ord, &ri) in row_indices.iter().enumerate() {
3748            let row = &mut self.children[ri];
3749            row.dimensions.content.x = base_x;
3750            row.dimensions.content.y = rows_top + row_y[row_ord] - collapse_px * row_ord as i32;
3751            row.dimensions.content.width = table_width;
3752            row.dimensions.content.height = row_h[row_ord];
3753            // セル(行の直下子)の relative/absolute/fixed オフセット + transform を適用。
3754            // 行を包含ブロックとして共有後処理を流用する。
3755            let saved_row_cb = row.establish_abs_cb();
3756            row.apply_positioned_offsets();
3757            Self::restore_abs_cb(saved_row_cb);
3758        }
3759
3760        // collapse 時は重ね合わせぶん全体が縮む
3761        let collapse_shrink = collapse_px * (nrows.saturating_sub(1)) as i32;
3762        let rows_height = (rows_total - collapse_shrink).max(0);
3763        if caption_side_bottom {
3764            let y = self.dimensions.content.y + top_offset + rows_height;
3765            top_offset += self.layout_captions_at(&caption_indices, base_x, y, table_width);
3766        }
3767        self.dimensions.content.height = top_offset + rows_height;
3768
3769        // positioned 直下子要素の配置(table を包含ブロック起点にできる)。
3770        // 通常フローのセル/行はすでに配置済み。relative オフセットや、table が
3771        // positioned のときの子孫 absolute 解決のため共有後処理を適用する。
3772        let saved_abs_cb = self.establish_abs_cb();
3773        self.apply_positioned_offsets();
3774        Self::restore_abs_cb(saved_abs_cb);
3775    }
3776
3777    fn layout_flex(&mut self, containing_block: Dimensions) {
3778        let forced_h = FORCED_BLOCK_H.swap(-1, AtomicOrdering::Relaxed);
3779        self.apply_box_model_styles_with_base(containing_block.content.width);
3780        let pct_base_h = PCT_BASE_H.load(AtomicOrdering::Relaxed);
3781
3782        let (width_val, min_width_val, max_width_val, height_val, box_sizing, h_auto, min_height_val, max_height_val) =
3783            match &self.box_type {
3784                BoxType::FlexNode(node) => (
3785                    len_value(node, "width"),
3786                    len_value(node, "min-width"),
3787                    len_value(node, "max-width"),
3788                    len_value(node, "height"),
3789                    node.value_ref("box-sizing").unwrap_or(""),
3790                    margin_is_h_auto(node),
3791                    len_value(node, "min-height"),
3792                    len_value(node, "max-height"),
3793                ),
3794                _ => return,
3795            };
3796        // padding + border のみ(box-sizing:border-box / margin:auto センタリング用)。
3797        let inner_non_content = self.dimensions.border.left
3798            + self.dimensions.border.right
3799            + self.dimensions.padding.left
3800            + self.dimensions.padding.right;
3801
3802        let horizontal_non_content = self.dimensions.margin.left
3803            + self.dimensions.margin.right
3804            + self.dimensions.border.left
3805            + self.dimensions.border.right
3806            + self.dimensions.padding.left
3807            + self.dimensions.padding.right;
3808        let available_width = containing_block.content.width.max(0);
3809        let parsed_width = parse_length_value(width_val.as_deref());
3810        let explicit_width =
3811            !matches!(parsed_width, Some(LengthValue::Auto) | None);
3812
3813        // `<button style="display:flex">` は幅 auto のとき shrink-to-fit(ブロックのように広がらない)。
3814        let is_button = matches!(&self.box_type, BoxType::FlexNode(n)
3815            if matches!(&n.node.node_type, NodeType::Element { tag_name, .. } if tag_name.eq_ignore_ascii_case("button")));
3816        let mut content_width = match parsed_width {
3817            Some(LengthValue::Auto) | None if is_button => {
3818                let (minc, maxc) = self.block_intrinsic_widths();
3819                let avail = (available_width - horizontal_non_content).max(0);
3820                avail.min(maxc).max(minc)
3821            }
3822            Some(LengthValue::Auto) | None => (available_width - horizontal_non_content).max(0),
3823            Some(LengthValue::Px(px)) => px.max(1),
3824            Some(LengthValue::Percent(pct)) => {
3825                round_f32_to_i32(available_width as f32 * pct).max(1)
3826            }
3827            Some(LengthValue::MinContent) => {
3828                let (minc, _maxc) = self.block_intrinsic_widths();
3829                minc.max(1)
3830            }
3831            Some(LengthValue::MaxContent) => {
3832                let (_minc, maxc) = self.block_intrinsic_widths();
3833                maxc.max(1)
3834            }
3835            Some(LengthValue::FitContent) => {
3836                let (minc, maxc) = self.block_intrinsic_widths();
3837                let avail = (available_width - horizontal_non_content).max(0);
3838                avail.min(maxc).max(minc).max(1)
3839            }
3840            Some(LengthValue::FitContentWith(lim_box)) => {
3841                let avail = (available_width - horizontal_non_content).max(0);
3842                let limit = resolve_length_value_with_font(*lim_box, avail, self.font_size())
3843                    .unwrap_or(avail);
3844                let (minc, maxc) = self.block_intrinsic_widths();
3845                maxc.min(limit.max(minc)).max(1)
3846            }
3847            Some(LengthValue::MathExpr(expr)) => {
3848                crate::os_lib::css::eval_css_math_with_font(&expr, available_width, self.font_size())
3849                    .unwrap_or((available_width - horizontal_non_content).max(1))
3850                    .max(1)
3851            }
3852        };
3853        // box-sizing: border-box → 指定 width は border-box 全体(layout_block と同じ)。
3854        if explicit_width && box_sizing.trim() == "border-box" {
3855            content_width = (content_width - inner_non_content).max(1);
3856        }
3857
3858        let bb_inner_f = if box_sizing.trim() == "border-box" { inner_non_content } else { 0 };
3859        if let Some(max_width) = self.resolve_sizing_value(max_width_val.as_deref(), available_width) {
3860            let mw = if is_length_sizing(max_width_val.as_deref()) { (max_width - bb_inner_f).max(0) } else { max_width };
3861            content_width = content_width.min(mw);
3862        }
3863        if let Some(min_width) = self.resolve_sizing_value(min_width_val.as_deref(), available_width) {
3864            let mw = if is_length_sizing(min_width_val.as_deref()) { (min_width - bb_inner_f).max(0) } else { min_width };
3865            content_width = content_width.max(mw);
3866        }
3867        self.dimensions.content.width = content_width.max(0);
3868
3869        // margin: auto(左右)→ 水平センタリング(layout_block と同じ。
3870        // 実サイトの `.container{max-width:..;margin:0 auto}` + `display:flex` がこれ)。
3871        if h_auto {
3872            let free = (available_width - self.dimensions.content.width - inner_non_content).max(0);
3873            self.dimensions.margin.left = free / 2;
3874            self.dimensions.margin.right = free / 2;
3875        }
3876
3877        let flow_y = containing_block.content.y
3878            + containing_block.content.height
3879            + self.dimensions.margin.top;
3880        self.dimensions.content.x = containing_block.content.x
3881            + self.dimensions.margin.left
3882            + self.dimensions.border.left
3883            + self.dimensions.padding.left;
3884        self.dimensions.content.y =
3885            flow_y + self.dimensions.border.top + self.dimensions.padding.top;
3886
3887        // 高さ(content 高)。px に加え calc()/vh 等も解決し、min/max-height を掛ける(CSS 2.1 §10.7)。
3888        // 【2026-10-24】従来は px の明示値しか見ず、calc() の高さも min/max-height も無視していた
3889        // (YouTube の `#full-bleed-container{display:flex;height:calc(var(--r)*100vw);min-height:480px}`
3890        // が高さ 0 になり、動画が見えなかった)。
3891        let v_non_content = self.dimensions.border.top
3892            + self.dimensions.border.bottom
3893            + self.dimensions.padding.top
3894            + self.dimensions.padding.bottom;
3895        let border_box = box_sizing.trim() == "border-box";
3896        let to_content_h = |h: i32| if border_box { (h - v_non_content).max(0) } else { h.max(0) };
3897        let resolve_h = |v: Option<&str>| -> Option<i32> {
3898            match parse_length_value(v) {
3899                None | Some(LengthValue::Auto) => None,
3900                Some(LengthValue::Percent(pct)) => {
3901                    if pct_base_h >= 0 {
3902                        Some(round_f32_to_i32(pct_base_h as f32 * pct).max(0))
3903                    } else {
3904                        None
3905                    }
3906                }
3907                Some(other) => resolve_length_value(other, containing_block.content.height.max(0)),
3908            }
3909        };
3910        let max_h = resolve_h(max_height_val.as_deref()).map(to_content_h);
3911        let min_h = resolve_h(min_height_val.as_deref()).map(|h| h.max(0));
3912        let clamp_h = |h: i32| -> i32 {
3913            let h = match max_h {
3914                Some(mx) => h.min(mx),
3915                None => h,
3916            };
3917            match min_h {
3918                Some(mn) => h.max(mn),
3919                None => h,
3920            }
3921        };
3922        let explicit_h: Option<i32> = if forced_h >= 0 {
3923            Some(forced_h)
3924        } else {
3925            self.explicit_content_height_px(height_val.as_deref())
3926                .or_else(|| resolve_h(height_val.as_deref()).map(to_content_h))
3927                .map(clamp_h)
3928        };
3929        // 子の `height:%` の基準(確定した高さのみ)。
3930        let definite_h = explicit_h.unwrap_or(-1);
3931        let _pct_h_guard = PctBaseHGuard::set(definite_h);
3932
3933        let (flex_dir, justify_content, align_items, align_content, row_gap, col_gap, flex_wrap) =
3934            match &self.box_type {
3935                BoxType::FlexNode(node) => {
3936                    let (rg, cg) = parse_flex_gap(node, self.dimensions.content.width);
3937                    (
3938                        node.value_ref("flex-direction")
3939                            .unwrap_or("row")
3940                            .trim(),
3941                        node.value_ref("justify-content")
3942                            .unwrap_or("flex-start")
3943                            .trim(),
3944                        node.value_ref("align-items")
3945                            .unwrap_or("stretch")
3946                            .trim(),
3947                        node.value_ref("align-content")
3948                            .unwrap_or("stretch")
3949                            .trim(),
3950                        rg,
3951                        cg,
3952                        node.value_ref("flex-wrap")
3953                            .unwrap_or("nowrap")
3954                            .trim(),
3955                    )
3956                }
3957                _ => return,
3958            };
3959
3960        // row / row-reverse は主軸が水平。column / column-reverse は垂直。
3961        let is_row = flex_dir.eq_ignore_ascii_case("row") || flex_dir.eq_ignore_ascii_case("row-reverse");
3962        let is_reverse = flex_dir.eq_ignore_ascii_case("row-reverse") || flex_dir.eq_ignore_ascii_case("column-reverse");
3963        // flex-wrap: wrap / wrap-reverse のとき複数行へ折り返す。
3964        let do_wrap = flex_wrap.eq_ignore_ascii_case("wrap") || flex_wrap.eq_ignore_ascii_case("wrap-reverse");
3965        // 主軸方向の gap(row なら列間=column-gap、column なら行間=row-gap)。
3966        let gap_main = if is_row { col_gap } else { row_gap };
3967        // 交差軸方向の gap(行間)。
3968        let gap_cross = if is_row { row_gap } else { col_gap };
3969
3970        if do_wrap {
3971            self.layout_flex_wrapped(
3972                is_row,
3973                is_reverse,
3974                flex_wrap.eq_ignore_ascii_case("wrap-reverse"),
3975                justify_content,
3976                align_items,
3977                align_content,
3978                gap_main,
3979                gap_cross,
3980                height_val.as_deref(),
3981                explicit_h,
3982                min_h,
3983                max_h,
3984            );
3985            return;
3986        }
3987
3988        // Layout all children as if they were inline-blocks (or blocks) with 0 initial x/y to measure them
3989        let mut total_main = 0;
3990        let mut max_cross = 0;
3991        let mut flex_base_w: Vec<Option<i32>> = alloc::vec![None; self.children.len()];
3992        // 列方向の自動最小サイズ(`min-height:auto`)。高さ auto のアイテムの内容高さ。
3993        let mut col_auto_min: Vec<i32> = alloc::vec![0; self.children.len()];
3994        // out-of-flow(absolute/fixed)はフレックスラインに参加しない。サイズ確定のため
3995        // レイアウトはするが、主軸合計・交差軸最大・justify の item 数には数えない。
3996        let oof: Vec<bool> = self
3997            .children
3998            .iter()
3999            .map(|c| Self::child_is_out_of_flow(c))
4000            .collect();
4001        let n = oof.iter().filter(|&&b| !b).count();
4002
4003        // flex-basis の % 解決基準(コンテナ主軸長)。row は content 幅、column は明示高さ。
4004        let basis_main_ref = if is_row {
4005            self.dimensions.content.width
4006        } else {
4007            match parse_length_value(height_val.as_deref()) {
4008                Some(LengthValue::Px(px)) => px,
4009                _ => 0,
4010            }
4011        };
4012
4013        for (ci, child) in self.children.iter_mut().enumerate() {
4014            let mut cb = self.dimensions.clone();
4015            cb.content.x = 0;
4016            cb.content.y = 0;
4017            cb.content.height = 0; // unlimited
4018            child.layout_fg_item(cb);
4019            if oof.get(ci).copied().unwrap_or(false) {
4020                continue;
4021            }
4022            // flex アイテムの主軸 auto margin は flex 側で処理する。layout_block が
4023            // margin:auto を「ブロック水平センタリング」として margin.left/right の両方へ
4024            // free/2 を入れてしまうため、主軸 auto margin がある辺方向の両端 margin を
4025            // 0 へ戻す(margin_box を実サイズに戻し、flex の auto 分配へ委ねる)。
4026            {
4027                let (lead, trail) = box_main_auto_margins(child, is_row);
4028                if lead || trail {
4029                    if is_row {
4030                        child.dimensions.margin.left = 0;
4031                        child.dimensions.margin.right = 0;
4032                    } else {
4033                        child.dimensions.margin.top = 0;
4034                        child.dimensions.margin.bottom = 0;
4035                    }
4036                }
4037            }
4038            if !is_row
4039                && !box_has_explicit(child, "height")
4040                && box_style_value_ref(child, "min-height").is_none_or(|v| v.trim() == "auto")
4041                && !box_style_value_ref(child, "overflow").is_some_and(|v| matches!(v.trim(), "hidden" | "scroll" | "auto" | "clip"))
4042                && !box_style_value_ref(child, "overflow-y").is_some_and(|v| matches!(v.trim(), "hidden" | "scroll" | "auto" | "clip"))
4043            {
4044                col_auto_min[ci] = child.dimensions.content.height.max(0);
4045            }
4046            // flex-basis 指定があれば主軸 content サイズを basis へ上書き(grow/shrink の基準)。
4047            if let Some(basis) = box_flex_basis(child, basis_main_ref).filter(|_| is_row || explicit_h.is_some() || !box_flex_basis_is_percentage(child)) {
4048                if is_row {
4049                    let b = (basis - border_box_inner_w(child)).max(0);
4050                    // 単一行・高さ確定のコンテナで stretch される項目は、交差軸の高さが確定(§9.8)。
4051                    let stretched_h = if do_wrap || box_has_explicit(child, "height") || box_aspect_ratio(child).is_some() {
4052                        None
4053                    } else {
4054                        explicit_h.and_then(|eh| {
4055                            let (ca, cb) = box_main_auto_margins(child, false);
4056                            let self_a = box_align_self(child);
4057                            let eff = self_a.as_deref().unwrap_or(align_items);
4058                            let is_st = !matches!(
4059                                eff.trim(),
4060                                "flex-start" | "start" | "self-start" | "flex-end" | "end" | "self-end" | "center"
4061                                    | "baseline" | "first baseline" | "last baseline"
4062                            );
4063                            if !ca && !cb && is_st {
4064                                let non_c = (child.dimensions.margin_box().height - child.dimensions.content.height).max(0);
4065                                Some((eh - non_c).max(0))
4066                            } else {
4067                                None
4068                            }
4069                        })
4070                    };
4071                    let nw = child.basis_with_auto_min_h(b, stretched_h);
4072                    // 伸びない項目は basis の幅がそのまま最終の幅に近いので、高さ(auto)をその幅で測り直す
4073                    // (内容の折り返しが変わる。WPT text-as-flexitem-size-001: `flex: 0 0 30px` で 35px でなく 45px)。
4074                    if nw != child.dimensions.content.width
4075                        && box_flex_grow_f32(child) <= 0.0
4076                        && !box_has_explicit(child, "height")
4077                        && matches!(child.box_type, BoxType::BlockNode(_) | BoxType::FlexNode(_) | BoxType::GridNode(_))
4078                    {
4079                        let mut cb2 = self.dimensions.clone();
4080                        cb2.content.x = 0;
4081                        cb2.content.y = 0;
4082                        cb2.content.width = nw + child.h_non_content();
4083                        cb2.content.height = 0;
4084                        child.layout_fg_item(cb2);
4085                    }
4086                    child.dimensions.content.width = nw;
4087                } else {
4088                    let b = (basis - border_box_inner_h(child)).max(0);
4089                    let nb = if box_flex_grow_f32(child) > 0.0 { b } else { b.max(col_auto_min[ci]) };
4090                    if nb != child.dimensions.content.height
4091                        && matches!(child.box_type, BoxType::BlockNode(_) | BoxType::FlexNode(_) | BoxType::GridNode(_))
4092                        && subtree_has_pct_h_or_oof(child)
4093                    {
4094                        let mb0 = child.dimensions.margin_box();
4095                        FORCED_BLOCK_H.store(nb, AtomicOrdering::Relaxed);
4096                        let cb = Dimensions {
4097                            content: Rect { x: mb0.x, y: mb0.y, width: mb0.width, height: 0 },
4098                            ..Default::default()
4099                        };
4100                        child.layout(cb);
4101                        FORCED_BLOCK_H.store(-1, AtomicOrdering::Relaxed);
4102                    }
4103                    child.dimensions.content.height = nb;
4104                }
4105            } else if child.is_replaced_inline() || box_intrinsic_ratio(child).is_some() {
4106                // 固有比率を持つ置換要素(img/canvas 等):
4107                // 1) flex base size は min/max-width を無視したサイズ(CSS Flexbox §9.2)。
4108                // 2) 交差軸の min/max 制約を主軸へ転送し、主軸自身の min/max 制約で仮サイズを決める。
4109                let cw = self.dimensions.content.width;
4110                let ch = explicit_h.unwrap_or(0);
4111                let inner_w = border_box_inner_w(child);
4112                let inner_h = border_box_inner_h(child);
4113                let nat_sz = child.styled_node().and_then(box_natural_size).unwrap_or((300, 150));
4114                if is_row {
4115                    let base_w = if let Some(sw) = box_len(child, "width", cw) {
4116                        (sw - inner_w).max(0)
4117                    } else if let Some((rw, rh)) = box_intrinsic_ratio(child) {
4118                        if let Some(sh) = box_len(child, "height", ch) {
4119                            round_f32_to_i32((sh - inner_h).max(0) as f32 * rw / rh).max(0)
4120                        } else {
4121                            nat_sz.0
4122                        }
4123                    } else {
4124                        nat_sz.0
4125                    };
4126                    flex_base_w[ci] = Some(base_w);
4127                }
4128                if is_row && !box_has_explicit(child, "width") && !box_has_explicit(child, "height") {
4129                    if let Some((rw, rh)) = box_intrinsic_ratio(child) {
4130                        let mut w = nat_sz.0 as f32;
4131                        if let Some(mn_h) = box_len(child, "min-height", ch) {
4132                            w = w.max((mn_h - inner_h).max(0) as f32 * rw / rh);
4133                        }
4134                        if let Some(mx_h) = box_len(child, "max-height", ch) {
4135                            w = w.min((mx_h - inner_h).max(0) as f32 * rw / rh);
4136                        }
4137                        if let Some(mx_w) = box_len(child, "max-width", cw) {
4138                            w = w.min((mx_w - inner_w).max(0) as f32);
4139                        }
4140                        if let Some(mn_w) = box_len(child, "min-width", cw) {
4141                            w = w.max((mn_w - inner_w).max(0) as f32);
4142                        }
4143                        child.dimensions.content.width = round_f32_to_i32(w).max(0);
4144                    }
4145                } else if !is_row && !box_has_explicit(child, "height") && !box_has_explicit(child, "width") {
4146                    if let Some((rw, rh)) = box_intrinsic_ratio(child) {
4147                        let mut h = nat_sz.1 as f32;
4148                        if let Some(mn_w) = box_len(child, "min-width", cw) {
4149                            h = h.max((mn_w - inner_w).max(0) as f32 * rh / rw);
4150                        }
4151                        if let Some(mx_w) = box_len(child, "max-width", cw) {
4152                            h = h.min((mx_w - inner_w).max(0) as f32 * rh / rw);
4153                        }
4154                        if let Some(mx_h) = box_len(child, "max-height", ch) {
4155                            h = h.min((mx_h - inner_h).max(0) as f32);
4156                        }
4157                        if let Some(mn_h) = box_len(child, "min-height", ch) {
4158                            h = h.max((mn_h - inner_h).max(0) as f32);
4159                        }
4160                        child.dimensions.content.height = round_f32_to_i32(h).max(0);
4161                    }
4162                }
4163            }
4164            if is_row
4165                && box_flex_basis(child, basis_main_ref).is_none()
4166                && !box_has_explicit(child, "width")
4167                && !child.is_replaced_inline()
4168                && box_intrinsic_ratio(child).is_none()
4169            {
4170                // 単一行・確定高さの flex コンテナで stretch されるアイテムは、交差軸高さが確定(definite)
4171                // となるため、子の `height:%` + `aspect-ratio` の横方向転嫁を反映した max-content を計算する。
4172                let stretched_h_opt = if !do_wrap {
4173                    explicit_h.and_then(|eh| {
4174                        let (ca, cb) = box_main_auto_margins(child, false);
4175                        let self_a = box_align_self(child);
4176                        let eff = self_a.as_deref().unwrap_or(align_items);
4177                        let is_st = !matches!(
4178                            eff.trim(),
4179                            "flex-start" | "start" | "self-start" | "flex-end" | "end" | "self-end" | "center"
4180                                | "baseline" | "first baseline" | "last baseline"
4181                        );
4182                        if !box_has_explicit(child, "height") && box_aspect_ratio(child).is_none() && !ca && !cb && is_st {
4183                            let non_c = (child.dimensions.margin_box().height - child.dimensions.content.height).max(0);
4184                            Some((eh - non_c).max(0))
4185                        } else {
4186                            None
4187                        }
4188                    })
4189                } else {
4190                    None
4191                };
4192                let raw_max_content = if let Some(sh) = stretched_h_opt {
4193                    child.block_intrinsic_widths_with_h(Some(sh)).1
4194                } else {
4195                    child.block_intrinsic_widths().1
4196                };
4197                flex_base_w[ci] = Some(raw_max_content);
4198                let mut max_content = raw_max_content;
4199                let container_w = self.dimensions.content.width;
4200                let inner = border_box_inner_w(child);
4201                if let Some(mw) = box_len(child, "max-width", container_w) {
4202                    max_content = max_content.min((mw - inner).max(0));
4203                }
4204                if let Some(mw) = box_len(child, "min-width", container_w) {
4205                    max_content = max_content.max((mw - inner).max(0));
4206                }
4207                let no_in_flow = child.children.iter().all(|c| Self::child_is_out_of_flow(c));
4208                let shrink_to_zero = max_content == 0 && !child.subtree_has_text_or_replaced();
4209                if (max_content > 0 || no_in_flow || shrink_to_zero) && max_content != child.dimensions.content.width {
4210                    let mut cb2 = self.dimensions.clone();
4211                    cb2.content.x = 0;
4212                    cb2.content.y = 0;
4213                    cb2.content.width = max_content + child.h_non_content();
4214                    cb2.content.height = 0;
4215                    if let Some(sh) = stretched_h_opt {
4216                        let _g = PctBaseHGuard::set(sh);
4217                        FORCED_BLOCK_H.store(sh, AtomicOrdering::Relaxed);
4218                        child.layout_fg_item(cb2);
4219                        FORCED_BLOCK_H.store(-1, AtomicOrdering::Relaxed);
4220                    } else {
4221                        child.layout_fg_item(cb2);
4222                    }
4223                    child.dimensions.content.width = max_content;
4224                }
4225            }
4226            let child_w = child.dimensions.margin_box().width;
4227            let child_h = child.dimensions.margin_box().height;
4228            if is_row {
4229                total_main += child_w;
4230                max_cross = max_cross.max(child_h);
4231            } else {
4232                total_main += child_h;
4233                max_cross = max_cross.max(child_w);
4234            }
4235        }
4236        // アイテム間の gap を主軸合計に加える(n-1 箇所)。
4237        if n > 1 {
4238            total_main += gap_main * (n as i32 - 1);
4239        }
4240
4241        let container_main = if is_row {
4242            self.dimensions.content.width
4243        } else {
4244            explicit_h.unwrap_or_else(|| clamp_h(total_main))
4245        };
4246
4247        let mut container_cross = if is_row {
4248            explicit_h.unwrap_or_else(|| clamp_h(max_cross))
4249        } else {
4250            self.dimensions.content.width
4251        };
4252
4253        if !is_row {
4254            self.dimensions.content.height = container_main;
4255        } else {
4256            self.dimensions.content.height = container_cross;
4257        }
4258
4259        // flex-grow / flex:N: grower を flex-basis 0 扱いにし、主軸の残余空間を grow 比で分配。
4260        // grower が無ければ何もしない(従来挙動を完全維持)。
4261        let grows: Vec<f32> = self
4262            .children
4263            .iter()
4264            .enumerate()
4265            .map(|(i, c)| {
4266                if oof.get(i).copied().unwrap_or(false) {
4267                    0.0
4268                } else {
4269                    box_flex_grow_f32(c)
4270                }
4271            })
4272            .collect();
4273        let total_grow: f32 = grows.iter().sum();
4274        if total_grow > 0.0 {
4275            // 余白は各アイテムの基準サイズ(`flex-basis`。`auto` なら中身の幅)を足した残り
4276            // (CSS Flexbox L1 §9.7)。【2026-11-01】従来は grower の基準を 0 とみなしていた。
4277            let raw_free = container_main - total_main;
4278            let free = if total_grow < 1.0 {
4279                round_f32_to_i32(raw_free as f32 * total_grow)
4280            } else {
4281                raw_free
4282            };
4283            if free > 0 {
4284                // 配分後の大きさが中身の幅(`min-width: auto` の自動最小サイズ)を下回るアイテムは下限で止める。
4285                let items: Vec<(i32, i32, i32)> = self
4286                    .children
4287                    .iter()
4288                    .enumerate()
4289                    .map(|(i, c)| {
4290                        let g = grows.get(i).copied().unwrap_or(0.0);
4291                        let g_scaled = round_f32_to_i32(g * 1000.0).max(0);
4292                        let base = if is_row { c.dimensions.content.width } else { c.dimensions.content.height };
4293                        let min = if is_row && g > 0.0 { c.grow_auto_min() } else { 0 };
4294                        (g_scaled, (min - base).max(0), base)
4295                    })
4296                    .collect();
4297                let grown: Vec<(i32, i32)> = items.iter().map(|x| (x.0, x.1)).collect();
4298                let sizes = crate::os_lib::layout::flex_min::distribute_grow(free, &grown);
4299                let cw = self.dimensions.content.width;
4300                let ch = explicit_h.unwrap_or(0);
4301                let mut used_grow = 0i32;
4302                for (i, child) in self.children.iter_mut().enumerate() {
4303                    let Some(&(g, _, base)) = items.get(i) else { continue };
4304                    if g <= 0 {
4305                        continue;
4306                    }
4307                    let mut s = (base + sizes.get(i).copied().unwrap_or(0)).max(0);
4308                    if is_row {
4309                        if let Some(mx) = box_len(child, "max-width", cw) {
4310                            s = s.min((mx - border_box_inner_w(child)).max(0));
4311                        }
4312                        if let Some(mn) = box_len(child, "min-width", cw) {
4313                            s = s.max((mn - border_box_inner_w(child)).max(0));
4314                        }
4315                        child.dimensions.content.width = s;
4316                    } else {
4317                        if let Some(mx) = box_len(child, "max-height", ch) {
4318                            s = s.min((mx - border_box_inner_h(child)).max(0));
4319                        }
4320                        if let Some(mn) = box_len(child, "min-height", ch) {
4321                            s = s.max((mn - border_box_inner_h(child)).max(0));
4322                        }
4323                        if explicit_h.is_some()
4324                            && matches!(child.box_type, BoxType::BlockNode(_) | BoxType::FlexNode(_) | BoxType::GridNode(_))
4325                            && subtree_has_pct_h_or_oof(child)
4326                        {
4327                            let mb0 = child.dimensions.margin_box();
4328                            FORCED_BLOCK_H.store(s, AtomicOrdering::Relaxed);
4329                            let cb = Dimensions {
4330                                content: Rect { x: mb0.x, y: mb0.y, width: mb0.width, height: 0 },
4331                                ..Default::default()
4332                            };
4333                            child.layout_fg_item(cb);
4334                            FORCED_BLOCK_H.store(-1, AtomicOrdering::Relaxed);
4335                        }
4336                        child.dimensions.content.height = s;
4337                    }
4338                    used_grow += s - base;
4339                }
4340                // 下限で止めたアイテムがあると container を超えることがある。
4341                total_main += used_grow;
4342            }
4343        }
4344
4345        // flex-shrink: 主軸がコンテナを超過する場合、shrink 係数に比例して各アイテムを縮める。
4346        // grower がいた(既に container にフィット)場合はスキップ。
4347        let overflow = total_main - container_main;
4348        if overflow > 0 {
4349            let shrinks: Vec<f32> = self
4350                .children
4351                .iter()
4352                .enumerate()
4353                .map(|(i, c)| {
4354                    if oof.get(i).copied().unwrap_or(false) {
4355                        0.0
4356                    } else {
4357                        box_flex_shrink_f32(c)
4358                    }
4359                })
4360                .collect();
4361            let total_shrink: f32 = shrinks.iter().sum();
4362            if total_shrink > 0.0 {
4363                let n_ch = self.children.len();
4364                let mut bases: Vec<i32> = alloc::vec![0; n_ch];
4365                let mut mins: Vec<i32> = alloc::vec![0; n_ch];
4366                let mut maxs: Vec<i32> = alloc::vec![i32::MAX; n_ch];
4367                let mut fixed_sum = 0i32;
4368                let mut frozen = alloc::vec![false; n_ch];
4369                for (i, c) in self.children.iter().enumerate() {
4370                    if oof.get(i).copied().unwrap_or(false) {
4371                        frozen[i] = true;
4372                        continue;
4373                    }
4374                    let base = if is_row {
4375                        flex_base_w[i].unwrap_or(c.dimensions.content.width).max(0)
4376                    } else {
4377                        c.dimensions.content.height.max(0)
4378                    };
4379                    bases[i] = base;
4380                    let min = if is_row {
4381                        if let Some(mw) = box_len(c, "min-width", container_main) {
4382                            (mw - border_box_inner_w(c)).max(0)
4383                        } else if box_style_value_ref(c, "overflow").is_some_and(|v| matches!(v.trim(), "hidden" | "scroll" | "auto"))
4384                            || box_style_value_ref(c, "overflow-x").is_some_and(|v| matches!(v.trim(), "hidden" | "scroll" | "auto"))
4385                        {
4386                            0
4387                        } else if c.is_replaced_inline() {
4388                            if let Some((rw, rh)) = box_intrinsic_ratio(c) {
4389                                let cw = self.dimensions.content.width;
4390                                let ch_opt = explicit_h;
4391                                let spec_w = box_len(c, "width", cw).map(|w| (w - border_box_inner_w(c)).max(0));
4392                                let cross_explicit = box_len(c, "height", ch_opt.unwrap_or(0)).map(|h| (h - border_box_inner_h(c)).max(0));
4393                                let stretch_h = if cross_explicit.is_none()
4394                                    && ch_opt.is_some()
4395                                    && box_align_self(c).as_deref().unwrap_or(align_items).eq_ignore_ascii_case("stretch")
4396                                {
4397                                    ch_opt.map(|h| (h - border_box_inner_h(c)).max(0))
4398                                } else {
4399                                    None
4400                                };
4401                                let nat_w = c.styled_node().and_then(box_natural_size).map(|(w, _)| w).unwrap_or(300);
4402                                let mut content_w = if let Some(h) = cross_explicit.or(stretch_h) {
4403                                    round_f32_to_i32(h as f32 * rw / rh).max(0)
4404                                } else {
4405                                    nat_w
4406                                };
4407                                if let Some(mx_h) = box_len(c, "max-height", ch_opt.unwrap_or(0)) {
4408                                    content_w = content_w.min(round_f32_to_i32((mx_h - border_box_inner_h(c)).max(0) as f32 * rw / rh));
4409                                }
4410                                if let Some(mn_h) = box_len(c, "min-height", ch_opt.unwrap_or(0)) {
4411                                    content_w = content_w.max(round_f32_to_i32((mn_h - border_box_inner_h(c)).max(0) as f32 * rw / rh));
4412                                }
4413                                match spec_w {
4414                                    Some(sw) => sw.min(content_w),
4415                                    None => content_w,
4416                                }
4417                            } else {
4418                                c.block_intrinsic_widths().0
4419                            }
4420                        } else {
4421                            c.block_intrinsic_widths().0
4422                        }
4423                    } else if let Some(mh) = box_len(c, "min-height", container_main) {
4424                        mh.max(0)
4425                    } else if c.is_replaced_inline() {
4426                        if let Some((rw, rh)) = box_intrinsic_ratio(c) {
4427                            let cw = self.dimensions.content.width;
4428                            let spec_h = box_len(c, "height", container_main).map(|h| (h - border_box_inner_h(c)).max(0));
4429                            let cross_explicit = box_len(c, "width", cw).map(|w| (w - border_box_inner_w(c)).max(0));
4430                            let stretch_w = if cross_explicit.is_none()
4431                                && box_align_self(c).as_deref().unwrap_or(align_items).eq_ignore_ascii_case("stretch")
4432                            {
4433                                Some((cw - c.h_non_content()).max(0))
4434                            } else {
4435                                None
4436                            };
4437                            let nat_h = c.styled_node().and_then(box_natural_size).map(|(_, h)| h).unwrap_or(150);
4438                            let mut content_h = if let Some(w) = cross_explicit.or(stretch_w) {
4439                                round_f32_to_i32(w as f32 * rh / rw).max(0)
4440                            } else {
4441                                nat_h
4442                            };
4443                            if let Some(mx_w) = box_len(c, "max-width", cw) {
4444                                content_h = content_h.min(round_f32_to_i32((mx_w - border_box_inner_w(c)).max(0) as f32 * rh / rw));
4445                            }
4446                            if let Some(mn_w) = box_len(c, "min-width", cw) {
4447                                content_h = content_h.max(round_f32_to_i32((mn_w - border_box_inner_w(c)).max(0) as f32 * rh / rw));
4448                            }
4449                            match spec_h {
4450                                Some(sh) => sh.min(content_h),
4451                                None => content_h,
4452                            }
4453                        } else {
4454                            let spec_h = box_len(c, "height", container_main).map(|h| (h - border_box_inner_h(c)).max(0));
4455                            let nat_h = c.styled_node().and_then(box_natural_size).map(|(_, h)| h).unwrap_or(150);
4456                            match spec_h {
4457                                Some(sh) => sh.min(nat_h),
4458                                None => 0,
4459                            }
4460                        }
4461                    } else {
4462                        col_auto_min[i]
4463                    };
4464                    mins[i] = min.clamp(0, base);
4465                    if is_row {
4466                        if let Some(mw) = box_len(c, "max-width", container_main) {
4467                            maxs[i] = (mw - border_box_inner_w(c)).max(mins[i]);
4468                        }
4469                    }
4470                    let sk = shrinks[i];
4471                    if sk <= 0.0 {
4472                        let s = base.clamp(mins[i], maxs[i]);
4473                        frozen[i] = true;
4474                        fixed_sum += s + if is_row { c.h_non_content() } else { c.dimensions.margin_box().height - c.dimensions.content.height };
4475                    }
4476                }
4477                let gaps = if n > 1 { gap_main * (n as i32 - 1) } else { 0 };
4478                let mut final_sizes = bases.clone();
4479                let mut ok = true;
4480                for _iter in 0..=n_ch {
4481                    let un_base: i32 = (0..n_ch)
4482                        .filter(|&i| !frozen[i])
4483                        .map(|i| bases[i] + if is_row { self.children[i].h_non_content() } else { self.children[i].dimensions.margin_box().height - self.children[i].dimensions.content.height })
4484                        .sum();
4485                    let raw_ov = (fixed_sum + un_base + gaps) - container_main;
4486                    if raw_ov <= 0 {
4487                        for i in 0..n_ch {
4488                            if !frozen[i] {
4489                                final_sizes[i] = bases[i].clamp(mins[i], maxs[i]);
4490                            }
4491                        }
4492                        break;
4493                    }
4494                    let un_sk: f32 = (0..n_ch).filter(|&i| !frozen[i]).map(|i| shrinks[i]).sum();
4495                    if un_sk <= 0.0 {
4496                        break;
4497                    }
4498                    let eff_ov = if un_sk < 1.0 { round_f32_to_i32(raw_ov as f32 * un_sk) } else { raw_ov };
4499                    let items: Vec<crate::os_lib::layout::flex_min::ShrinkItem> = (0..n_ch)
4500                        .map(|i| {
4501                            if frozen[i] {
4502                                crate::os_lib::layout::flex_min::ShrinkItem { base: 0, min: 0, shrink: 0 }
4503                            } else {
4504                                let sk = shrinks[i];
4505                                let scaled = round_f32_to_i32(sk * (bases[i].max(1) as f32)).max(1);
4506                                crate::os_lib::layout::flex_min::ShrinkItem {
4507                                    base: bases[i],
4508                                    min: mins[i],
4509                                    shrink: scaled,
4510                                }
4511                            }
4512                        })
4513                        .collect();
4514                    match crate::os_lib::layout::flex_min::distribute_shrink(&items, eff_ov.max(0)) {
4515                        Ok(sizes) => {
4516                            let mut any_clamped = false;
4517                            for i in 0..n_ch {
4518                                if frozen[i] {
4519                                    continue;
4520                                }
4521                                let s = sizes[i];
4522                                if s > maxs[i] {
4523                                    final_sizes[i] = maxs[i];
4524                                    frozen[i] = true;
4525                                    fixed_sum += maxs[i] + if is_row { self.children[i].h_non_content() } else { self.children[i].dimensions.margin_box().height - self.children[i].dimensions.content.height };
4526                                    any_clamped = true;
4527                                } else {
4528                                    final_sizes[i] = s;
4529                                }
4530                            }
4531                            if !any_clamped {
4532                                break;
4533                            }
4534                        }
4535                        Err(_) => {
4536                            ok = false;
4537                            break;
4538                        }
4539                    }
4540                }
4541                if ok {
4542                    for (i, child) in self.children.iter_mut().enumerate() {
4543                        if oof.get(i).copied().unwrap_or(false) {
4544                            continue;
4545                        }
4546                        let s = final_sizes[i];
4547                        if is_row {
4548                            child.dimensions.content.width = s;
4549                        } else {
4550                            child.dimensions.content.height = s;
4551                        }
4552                    }
4553                    if is_row {
4554                        for (i, child) in self.children.iter_mut().enumerate() {
4555                            if oof.get(i).copied().unwrap_or(false) {
4556                                continue;
4557                            }
4558                            let s = final_sizes[i];
4559                            let base = bases[i];
4560                            if s >= base {
4561                                continue;
4562                            }
4563                            let mut cb = self.dimensions.clone();
4564                            cb.content.x = 0;
4565                            cb.content.y = 0;
4566                            cb.content.width = s + child.h_non_content();
4567                            cb.content.height = 0;
4568                            child.layout_fg_item(cb);
4569                            child.dimensions.content.width = s;
4570                        }
4571                    }
4572                    total_main = final_sizes
4573                        .iter()
4574                        .enumerate()
4575                        .filter(|&(i, _)| !oof.get(i).copied().unwrap_or(false))
4576                        .map(|(i, &s)| s + if is_row { self.children[i].h_non_content() } else { self.children[i].dimensions.margin_box().height - self.children[i].dimensions.content.height })
4577                        .sum::<i32>()
4578                        + gaps;
4579                }
4580            }
4581        }
4582
4583        // flex アイテムの aspect-ratio による交差軸寸法の自動計算:
4584        // is_row 時: アイテムの高さが auto で aspect-ratio を持つ場合、主軸幅から高さを算出
4585        // !is_row 時: アイテムの幅が auto で aspect-ratio を持つ場合、主軸高さから幅を算出
4586        for (ci, child) in self.children.iter_mut().enumerate() {
4587            if oof.get(ci).copied().unwrap_or(false) {
4588                continue;
4589            }
4590            if let Some((num, den)) = box_aspect_ratio(child).or_else(|| box_intrinsic_ratio(child)) {
4591                if num > 0.0 && den > 0.0 {
4592                    if is_row && !box_has_explicit(child, "height") {
4593                        let w = child.dimensions.content.width as f32;
4594                        let mut h = round_f32_to_i32(w * den / num).max(1);
4595                        let ch = explicit_h.unwrap_or(0);
4596                        let inner_h = border_box_inner_h(child);
4597                        if let Some(mx_h) = box_len(child, "max-height", ch) {
4598                            h = h.min((mx_h - inner_h).max(0));
4599                        }
4600                        if let Some(mn_h) = box_len(child, "min-height", ch) {
4601                            h = h.max((mn_h - inner_h).max(0));
4602                        }
4603                        child.dimensions.content.height = h;
4604                    } else if !is_row && !box_has_explicit(child, "width") {
4605                        let h = child.dimensions.content.height as f32;
4606                        let mut w = round_f32_to_i32(h * num / den).max(1);
4607                        let cw = self.dimensions.content.width;
4608                        let inner_w = border_box_inner_w(child);
4609                        if let Some(mx_w) = box_len(child, "max-width", cw) {
4610                            w = w.min((mx_w - inner_w).max(0));
4611                        }
4612                        if let Some(mn_w) = box_len(child, "min-width", cw) {
4613                            w = w.max((mn_w - inner_w).max(0));
4614                        }
4615                        child.dimensions.content.width = w;
4616                    }
4617                }
4618            }
4619        }
4620
4621        // 【2026-09-05】縮小で子を組み直したら、**親の高さも計算し直す**。
4622        //
4623        // 交差軸のサイズ(横並びなら高さ)は縮小より前に確定していた。
4624        // 縮小した子はその幅で組み直すので行数が増えることがあり、
4625        // 高さが 1 行ぶんのまま取り残されて**次の要素と重なる**。
4626        // 実サイト `forms.htm` の目次で、2 行に折り返した項目が
4627        // 次の項目に重なって出ていた。
4628        //
4629        // 高さが明示されている場合は指定を尊重する(伸ばさない)。
4630        if is_row && explicit_h.is_none() {
4631            let mut recomputed = 0;
4632            for (ci, child) in self.children.iter().enumerate() {
4633                if oof.get(ci).copied().unwrap_or(false) {
4634                    continue;
4635                }
4636                recomputed = recomputed.max(child.dimensions.margin_box().height);
4637            }
4638            // ベースライン整列の項目は、最大の ascent と最大の descent の和ぶんの高さが要る。
4639            if let Some((_, _, total)) = self.flex_baseline_layout(&oof, align_items) {
4640                recomputed = recomputed.max(total);
4641            }
4642            let recomputed = clamp_h(recomputed);
4643            if recomputed > container_cross {
4644                container_cross = recomputed;
4645                self.dimensions.content.height = container_cross;
4646            }
4647        }
4648
4649        // align-items: stretch(既定値): 交差軸サイズ未指定の子をコンテナ交差幅へ伸ばす。
4650        // ただし align-self が明示された子は除外(個別指定を尊重)。
4651        // aspect-ratio を持つアイテムも主軸から交差軸サイズが定まるため除外。
4652        if align_items.eq_ignore_ascii_case("stretch") {
4653            let cross_prop = if is_row { "height" } else { "width" };
4654            for (ci, child) in self.children.iter_mut().enumerate() {
4655                if oof.get(ci).copied().unwrap_or(false) {
4656                    continue;
4657                }
4658                let (ca, cb) = box_main_auto_margins(child, !is_row);
4659                if ca || cb || box_has_explicit(child, cross_prop) || box_aspect_ratio(child).is_some() {
4660                    continue;
4661                }
4662                // align-self が stretch 以外で指定されていれば stretch しない。
4663                if let Some(s) = box_align_self(child) {
4664                    if s != "stretch" {
4665                        continue;
4666                    }
4667                }
4668                let mb = child.dimensions.margin_box();
4669                let (cur_cross, cur_content) = if is_row {
4670                    (mb.height, child.dimensions.content.height)
4671                } else {
4672                    (mb.width, child.dimensions.content.width)
4673                };
4674                let non_content = cur_cross - cur_content; // padding/border/margin 分
4675                let mut new_content = (container_cross - non_content).max(0);
4676                let cw = self.dimensions.content.width;
4677                let ch = explicit_h.unwrap_or(0);
4678                if is_row {
4679                    if let Some(mx_h) = box_len(child, "max-height", ch) {
4680                        new_content = new_content.min((mx_h - border_box_inner_h(child)).max(0));
4681                    }
4682                    if let Some(mn_h) = box_len(child, "min-height", ch) {
4683                        new_content = new_content.max((mn_h - border_box_inner_h(child)).max(0));
4684                    }
4685                } else {
4686                    if let Some(mx_w) = box_len(child, "max-width", cw) {
4687                        new_content = new_content.min((mx_w - border_box_inner_w(child)).max(0));
4688                    }
4689                    if let Some(mn_w) = box_len(child, "min-width", cw) {
4690                        new_content = new_content.max((mn_w - border_box_inner_w(child)).max(0));
4691                    }
4692                }
4693                if is_row {
4694                    // 伸ばした高さに子の絶対配置(top+bottom)や `height:%` が依存するブロックは、
4695                    // その高さを確定させて組み直す(【2026-10-24】YouTube の
4696                    // `#player-full-bleed-container{position:relative;flex:1}` の中の
4697                    // `#player-container{position:absolute;inset:0}` が高さ 0 のままだった)。
4698                    let depends = matches!(child.box_type, BoxType::BlockNode(_) | BoxType::FlexNode(_) | BoxType::GridNode(_))
4699                        && subtree_has_pct_h_or_oof(child);
4700                    if depends {
4701                        let mb0 = child.dimensions.margin_box();
4702                        FORCED_BLOCK_H.store(new_content, AtomicOrdering::Relaxed);
4703                        let cb = Dimensions {
4704                            content: Rect { x: mb0.x, y: mb0.y, width: mb0.width, height: 0 },
4705                            ..Default::default()
4706                        };
4707                        child.layout(cb);
4708                        FORCED_BLOCK_H.store(-1, AtomicOrdering::Relaxed);
4709                    }
4710                    child.dimensions.content.height = new_content;
4711                    if let Some((num, den)) = box_intrinsic_ratio(child) {
4712                        // 伸びて決まった主軸の大きさは stretch で変えない(§9.4 手順 11)。比率から幅を出し直すのは、コンテナの高さが確定していて
4713                        // 伸縮の前に交差の大きさが決まる場合と、伸びない項目だけ(WPT flexitem-stretch-image: 伸びた 255px の画像が 345px に戻っていた。
4714                        // 伸びない項目は min/max-height を比率で移した幅をここで得る: flex-aspect-ratio-img-column-011)。
4715                        if num > 0.0 && den > 0.0 && (explicit_h.is_some() || box_flex_grow_f32(child) <= 0.0) && !box_has_explicit(child, "width") && box_flex_basis(child, basis_main_ref).is_none() {
4716                            let mut w = round_f32_to_i32(new_content as f32 * num / den).max(0);
4717                            if let Some(mx_w) = box_len(child, "max-width", cw) {
4718                                w = w.min((mx_w - border_box_inner_w(child)).max(0));
4719                            }
4720                            if let Some(mn_w) = box_len(child, "min-width", cw) {
4721                                w = w.max((mn_w - border_box_inner_w(child)).max(0));
4722                            }
4723                            child.dimensions.content.width = w;
4724                        }
4725                    }
4726                } else {
4727                    child.dimensions.content.width = new_content;
4728                    if let Some((num, den)) = box_intrinsic_ratio(child) {
4729                        if num > 0.0 && den > 0.0 && !box_has_explicit(child, "height") && box_flex_basis(child, basis_main_ref).is_none() {
4730                            let mut h = round_f32_to_i32(new_content as f32 * den / num).max(1);
4731                            if let Some(mx_h) = box_len(child, "max-height", ch) {
4732                                h = h.min((mx_h - border_box_inner_h(child)).max(0));
4733                            }
4734                            if let Some(mn_h) = box_len(child, "min-height", ch) {
4735                                h = h.max((mn_h - border_box_inner_h(child)).max(0));
4736                            }
4737                            child.dimensions.content.height = h;
4738                        }
4739                    }
4740                }
4741            }
4742        }
4743
4744        // Justify Content (Main Axis)
4745        let main_free_space = container_main - total_main;
4746
4747        // flex 主軸 auto margin: 主軸方向に auto margin を持つアイテムがあれば、
4748        // 余剰空間を全 auto margin 辺で均等分配する(justify-content より優先)。
4749        let mut total_auto_margins = 0i32;
4750        for (ci, child) in self.children.iter().enumerate() {
4751            if oof.get(ci).copied().unwrap_or(false) {
4752                continue;
4753            }
4754            let (a, b) = box_main_auto_margins(child, is_row);
4755            total_auto_margins += a as i32 + b as i32;
4756        }
4757        let auto_margin_unit = if total_auto_margins > 0 && main_free_space > 0 {
4758            main_free_space / total_auto_margins
4759        } else {
4760            0
4761        };
4762        let use_auto_margins = total_auto_margins > 0 && main_free_space > 0;
4763
4764        let is_rtl = box_is_rtl(self);
4765        let phys_reverse = is_reverse ^ (is_row && is_rtl);
4766        let eff_jc = match (is_reverse, justify_content.trim()) {
4767            (true, "start") => "flex-end",
4768            (true, "end") => "flex-start",
4769            _ => justify_content,
4770        };
4771        let eff_jc = if is_row && (eff_jc.eq_ignore_ascii_case("left") || eff_jc.eq_ignore_ascii_case("right")) {
4772            let want_right = eff_jc.eq_ignore_ascii_case("right");
4773            if want_right == phys_reverse { "flex-start" } else { "flex-end" }
4774        } else {
4775            eff_jc
4776        };
4777        let main_offset = if use_auto_margins {
4778            0
4779        } else if eff_jc.eq_ignore_ascii_case("flex-end") || eff_jc.eq_ignore_ascii_case("end") {
4780            main_free_space
4781        } else if eff_jc.eq_ignore_ascii_case("center") {
4782            main_free_space / 2
4783        } else if eff_jc.eq_ignore_ascii_case("space-around") && n > 0 {
4784            main_free_space / (n as i32 * 2)
4785        } else if eff_jc.eq_ignore_ascii_case("space-evenly") && n > 0 {
4786            main_free_space / (n as i32 + 1)
4787        } else {
4788            // flex-start / start / space-between(ループで処理)/ space-around・space-evenly(n==0)
4789            0
4790        };
4791
4792        let spacing = if use_auto_margins {
4793            0
4794        } else if eff_jc.eq_ignore_ascii_case("space-between") && n > 1 {
4795            main_free_space / (n as i32 - 1)
4796        } else if eff_jc.eq_ignore_ascii_case("space-around") && n > 0 {
4797            main_free_space / (n as i32)
4798        } else if eff_jc.eq_ignore_ascii_case("space-evenly") && n > 0 {
4799            main_free_space / (n as i32 + 1)
4800        } else {
4801            0
4802        };
4803
4804        // 主軸の配置。phys_reverse なら主軸終端から DOM 順に詰める。
4805        // order: アイテムを order 昇順(同値は DOM 順)に並べ替えて配置する。
4806        let mut order_idx: Vec<usize> = (0..self.children.len()).collect();
4807        order_idx.sort_by_key(|&i| (box_order(&self.children[i]), i));
4808        let baseline_offsets = if is_row { self.flex_baseline_layout(&oof, align_items) } else { None };
4809        let mut cursor = main_offset;
4810        for &ci in &order_idx {
4811            // out-of-flow はフロー配置をスキップ(cursor を進めない)。後段で配置する。
4812            if oof.get(ci).copied().unwrap_or(false) {
4813                continue;
4814            }
4815            // 主軸 auto margin: 先頭辺ぶんを cursor へ加算(アイテムを後方へ押す)。
4816            let (lead_auto, trail_auto) = if use_auto_margins {
4817                let (a, b) = box_main_auto_margins(&self.children[ci], is_row);
4818                if phys_reverse { (b, a) } else { (a, b) }
4819            } else {
4820                (false, false)
4821            };
4822            if lead_auto {
4823                cursor += auto_margin_unit;
4824            }
4825            let child_w = self.children[ci].dimensions.margin_box().width;
4826            let child_h = self.children[ci].dimensions.margin_box().height;
4827            let child_main = if is_row { child_w } else { child_h };
4828
4829            let cross_free_space = container_cross - if is_row { child_h } else { child_w };
4830            // align-self が指定されていればそれを優先、無ければ align-items。
4831            let self_align_opt = box_align_self(&self.children[ci]);
4832            let effective_align = self_align_opt.as_deref().unwrap_or(align_items);
4833            let (ca, cb) = box_main_auto_margins(&self.children[ci], !is_row);
4834            let cross_offset = if (ca || cb) && cross_free_space > 0 {
4835                match (ca, cb) {
4836                    (true, true) => cross_free_space / 2,
4837                    (true, false) => cross_free_space,
4838                    (false, true) => 0,
4839                    (false, false) => 0,
4840                }
4841            } else if let Some(off) = baseline_offsets
4842                .as_ref()
4843                .and_then(|(o, _, _)| o.get(ci).copied())
4844                .filter(|&o| o >= 0)
4845            {
4846                off
4847            } else if !is_row && is_rtl {
4848                if effective_align.eq_ignore_ascii_case("flex-end")
4849                    || effective_align.eq_ignore_ascii_case("end")
4850                    || effective_align.eq_ignore_ascii_case("self-end")
4851                {
4852                    0
4853                } else if effective_align.eq_ignore_ascii_case("center") {
4854                    cross_free_space / 2
4855                } else {
4856                    cross_free_space
4857                }
4858            } else if effective_align.eq_ignore_ascii_case("flex-end")
4859                || effective_align.eq_ignore_ascii_case("end")
4860                || effective_align.eq_ignore_ascii_case("self-end")
4861            {
4862                cross_free_space
4863            } else if effective_align.eq_ignore_ascii_case("center") {
4864                cross_free_space / 2
4865            } else {
4866                0 // flex-start / start / stretch
4867            };
4868
4869            // 主軸開始位置(コンテナ content 原点からの相対)。phys_reverse は終端から逆算。
4870            let main_start = if phys_reverse {
4871                container_main - cursor - child_main
4872            } else {
4873                cursor
4874            };
4875
4876            // Recursively update positions relative to container
4877            let start_x = self.dimensions.content.x;
4878            let start_y = self.dimensions.content.y;
4879
4880            let target_x = if is_row {
4881                start_x + main_start
4882            } else {
4883                start_x + cross_offset
4884            };
4885            let target_y = if is_row {
4886                start_y + cross_offset
4887            } else {
4888                start_y + main_start
4889            };
4890
4891            let shift_x = target_x - self.children[ci].dimensions.margin_box().x;
4892            let shift_y = target_y - self.children[ci].dimensions.margin_box().y;
4893
4894            shift_layout_box(&mut self.children[ci], shift_x, shift_y);
4895
4896            cursor += child_main + spacing + gap_main;
4897            if trail_auto {
4898                cursor += auto_margin_unit;
4899            }
4900        }
4901
4902        // positioned 子要素の配置(flex コンテナを包含ブロック起点にできる)。
4903        // フロー内アイテムは上で配置済み。out-of-flow の abspos には静的位置(単体配置)を算出する。
4904        let is_rtl = box_is_rtl(self);
4905        let start_x = self.dimensions.content.x;
4906        let start_y = self.dimensions.content.y;
4907        for (ci, child) in self.children.iter_mut().enumerate() {
4908            if !oof.get(ci).copied().unwrap_or(false) || box_position(child) != "absolute" {
4909                continue;
4910            }
4911            let mb = child.dimensions.margin_box();
4912            let child_main = if is_row { mb.width } else { mb.height };
4913            let child_cross = if is_row { mb.height } else { mb.width };
4914            let free_m = container_main - child_main;
4915            let j_off = if justify_content.eq_ignore_ascii_case("flex-end") {
4916                free_m
4917            } else if justify_content.eq_ignore_ascii_case("center")
4918                || justify_content.eq_ignore_ascii_case("space-around")
4919                || justify_content.eq_ignore_ascii_case("space-evenly")
4920            {
4921                free_m / 2
4922            } else if justify_content.eq_ignore_ascii_case("end") {
4923                if is_reverse { 0 } else { free_m }
4924            } else {
4925                0
4926            };
4927            let mut main_pos = if is_reverse { container_main - j_off - child_main } else { j_off };
4928            if is_row && is_rtl {
4929                main_pos = container_main - main_pos - child_main;
4930            }
4931            let self_align_opt = box_align_self(child);
4932            let eff_a = self_align_opt.as_deref().unwrap_or(align_items);
4933            let free_c = container_cross - child_cross;
4934            let mut cross_pos = if eff_a.eq_ignore_ascii_case("flex-end") {
4935                free_c
4936            } else if eff_a.eq_ignore_ascii_case("center") {
4937                free_c / 2
4938            } else if eff_a.eq_ignore_ascii_case("end") || eff_a.eq_ignore_ascii_case("self-end") {
4939                if !is_row && is_rtl { 0 } else { free_c }
4940            } else if (eff_a.eq_ignore_ascii_case("start") || eff_a.eq_ignore_ascii_case("self-start")) && !is_row && is_rtl {
4941                free_c
4942            } else {
4943                0
4944            };
4945            if !is_row && is_rtl && (eff_a.eq_ignore_ascii_case("flex-start") || eff_a.eq_ignore_ascii_case("flex-end") || eff_a.eq_ignore_ascii_case("stretch") || eff_a.eq_ignore_ascii_case("normal") || eff_a.is_empty()) {
4946                cross_pos = container_cross - cross_pos - child_cross;
4947            }
4948            let (tx, ty) = if is_row {
4949                (start_x + main_pos, start_y + cross_pos)
4950            } else {
4951                (start_x + cross_pos, start_y + main_pos)
4952            };
4953            shift_layout_box(child, tx - mb.x, ty - mb.y);
4954        }
4955        let saved_abs_cb = self.establish_abs_cb();
4956        self.apply_positioned_offsets_with(None, true);
4957        Self::restore_abs_cb(saved_abs_cb);
4958    }
4959
4960    /// flex-wrap: wrap / wrap-reverse のレイアウト。
4961    /// 子を主軸に沿って並べ、コンテナ主軸長を超えたら次の行へ折り返す。
4962    /// 各行ごとに justify-content(主軸)と align-items / align-self(交差軸)を適用する。
4963    #[allow(clippy::too_many_arguments)]
4964    fn layout_flex_wrapped(
4965        &mut self,
4966        is_row: bool,
4967        is_reverse: bool,
4968        wrap_reverse: bool,
4969        justify_content: &str,
4970        align_items: &str,
4971        align_content: &str,
4972        gap_main: i32,
4973        gap_cross: i32,
4974        height_val: Option<&str>,
4975        explicit_h: Option<i32>,
4976        min_h: Option<i32>,
4977        max_h: Option<i32>,
4978    ) {
4979        let n = self.children.len();
4980        if n == 0 {
4981            if let Some(eh) = explicit_h {
4982                self.dimensions.content.height = eh;
4983            }
4984            return;
4985        }
4986
4987        // 各子を測定(main/cross サイズ)。out-of-flow(absolute/fixed)は
4988        // フレックスラインに参加しないため flow_idx から除外する(サイズ確定のため
4989        // layout は行う)。最終配置は末尾の apply_positioned_offsets が行う。
4990        let oof: Vec<bool> = self
4991            .children
4992            .iter()
4993            .map(|c| Self::child_is_out_of_flow(c))
4994            .collect();
4995        // flex-basis の % 解決基準(コンテナ主軸長)。row は content 幅、column は明示高さ。
4996        let basis_main_ref = if is_row {
4997            self.dimensions.content.width
4998        } else {
4999            match parse_length_value(height_val) {
5000                Some(LengthValue::Px(px)) => px,
5001                _ => 0,
5002            }
5003        };
5004
5005        let mut sizes: Vec<(i32, i32)> = Vec::with_capacity(n); // (main, cross)
5006        for (ci, child) in self.children.iter_mut().enumerate() {
5007            let mut cb = self.dimensions.clone();
5008            cb.content.x = 0;
5009            cb.content.y = 0;
5010            cb.content.height = 0;
5011            child.layout_fg_item(cb);
5012            if oof.get(ci).copied().unwrap_or(false) {
5013                let w = child.dimensions.margin_box().width;
5014                let h = child.dimensions.margin_box().height;
5015                if is_row {
5016                    sizes.push((w, h));
5017                } else {
5018                    sizes.push((h, w));
5019                }
5020                continue;
5021            }
5022
5023            // 縦並び(column)の折り返しでは、項目の交差軸(幅)は auto なら内容幅(fit-content)で測り、
5024            // 行の交差サイズ(最も広い項目)まで後で伸ばす(§9.4・§9.6)。
5025            if !is_row && !box_has_explicit(child, "width") {
5026                let cw = self.dimensions.content.width;
5027                if let Some(fit) = Self::grid_fit_outer_width(child, cw, "start") {
5028                    let mut cb2 = self.dimensions.clone();
5029                    cb2.content.x = 0;
5030                    cb2.content.y = 0;
5031                    cb2.content.width = fit;
5032                    cb2.content.height = 0;
5033                    child.layout_fg_item(cb2);
5034                }
5035            }
5036
5037            // 主軸 auto margin のリセット(flex 側で按分するため)
5038            {
5039                let (lead, trail) = box_main_auto_margins(child, is_row);
5040                if lead || trail {
5041                    if is_row {
5042                        child.dimensions.margin.left = 0;
5043                        child.dimensions.margin.right = 0;
5044                    } else {
5045                        child.dimensions.margin.top = 0;
5046                        child.dimensions.margin.bottom = 0;
5047                    }
5048                }
5049            }
5050
5051            // flex-basis 指定があれば主軸 content サイズを basis へ上書き
5052            if let Some(basis) = box_flex_basis(child, basis_main_ref).filter(|_| is_row || explicit_h.is_some() || !box_flex_basis_is_percentage(child)) {
5053                if is_row {
5054                    child.dimensions.content.width = child.basis_with_auto_min(basis);
5055                } else {
5056                    child.dimensions.content.height = basis;
5057                }
5058                // 行分割は「仮の主軸サイズ」(flex base size を min/max で挟んだ値)で行う(CSS Flexbox §9.3 手順 5・§9.2 手順 3E)。
5059                // `flex: 1; min-width: 400px` の項目が基準 0 のまま並べられ、600px の行に 4 個入っていた(WPT multiline-min-max)。
5060                if is_row {
5061                    let cw = self.dimensions.content.width;
5062                    let inner = border_box_inner_w(child);
5063                    let mut w = child.dimensions.content.width;
5064                    if let Some(mx) = box_len(child, "max-width", cw) {
5065                        w = w.min((mx - inner).max(0));
5066                    }
5067                    if let Some(mn) = box_len(child, "min-width", cw) {
5068                        w = w.max((mn - inner).max(0));
5069                    }
5070                    child.dimensions.content.width = w;
5071                } else {
5072                    let ch = explicit_h.unwrap_or(0);
5073                    let pct_ok = explicit_h.is_some();
5074                    let inner = border_box_inner_h(child);
5075                    let mut h = child.dimensions.content.height;
5076                    let is_pct = |p: &str| box_style_value_ref(child, p).is_some_and(|v| v.contains('%'));
5077                    if pct_ok || !is_pct("max-height") {
5078                        if let Some(mx) = box_len(child, "max-height", ch) {
5079                            h = h.min((mx - inner).max(0));
5080                        }
5081                    }
5082                    if pct_ok || !is_pct("min-height") {
5083                        if let Some(mn) = box_len(child, "min-height", ch) {
5084                            h = h.max((mn - inner).max(0));
5085                        }
5086                    }
5087                    child.dimensions.content.height = h;
5088                }
5089            }
5090
5091            // 幅指定が無い flex アイテムの基準幅は自身の max-content 幅
5092            if is_row
5093                && box_flex_basis(child, basis_main_ref).is_none()
5094                && !box_has_explicit(child, "width")
5095                && box_intrinsic_ratio(child).is_none()
5096            {
5097                let mut max_content = child.block_intrinsic_widths().1;
5098                let container_w = self.dimensions.content.width;
5099                let inner = border_box_inner_w(child);
5100                if let Some(mw) = box_len(child, "max-width", container_w) {
5101                    max_content = max_content.min((mw - inner).max(0));
5102                }
5103                if let Some(mw) = box_len(child, "min-width", container_w) {
5104                    max_content = max_content.max((mw - inner).max(0));
5105                }
5106                let no_in_flow = child.children.iter().all(|c| Self::child_is_out_of_flow(c));
5107                let shrink_to_zero = max_content == 0 && !child.subtree_has_text_or_replaced();
5108                if (max_content > 0 || no_in_flow || shrink_to_zero) && max_content != child.dimensions.content.width {
5109                    let mut cb2 = self.dimensions.clone();
5110                    cb2.content.x = 0;
5111                    cb2.content.y = 0;
5112                    cb2.content.width = max_content + child.h_non_content();
5113                    cb2.content.height = 0;
5114                    child.layout_fg_item(cb2);
5115                    child.dimensions.content.width = max_content;
5116                }
5117            }
5118
5119            let w = child.dimensions.margin_box().width;
5120            let h = child.dimensions.margin_box().height;
5121            if is_row {
5122                sizes.push((w, h));
5123            } else {
5124                sizes.push((h, w));
5125            }
5126        }
5127        // フロー参加インデックス(DOM 順)。以降のライン分割・配置はこの並びで行う。
5128        let flow_idx: Vec<usize> = (0..n).filter(|&i| !oof[i]).collect();
5129
5130        let col_max_h = if is_row { None } else { max_h };
5131        let container_main = if is_row {
5132            self.dimensions.content.width
5133        } else {
5134            let mut h = explicit_h.or(col_max_h).unwrap_or(i32::MAX / 4);
5135            if let Some(mn) = min_h {
5136                if explicit_h.is_none() {
5137                    h = h.max(mn);
5138                }
5139            }
5140            h
5141        };
5142
5143        // 行分割: 主軸長がコンテナを超えたら改行。インデックスは flow_idx の位置(pos)。
5144        let fln = flow_idx.len();
5145        let mut lines: Vec<(usize, usize, i32, i32)> = Vec::new(); // (start_pos, end_pos_excl, main_used, cross_max)
5146        let mut line_start = 0usize;
5147        let mut line_main = 0i32;
5148        let mut line_cross = 0i32;
5149        for pos in 0..fln {
5150            let (m, c) = sizes[flow_idx[pos]];
5151            let add = if pos == line_start { m } else { m + gap_main };
5152            if pos > line_start && line_main + add > container_main {
5153                lines.push((line_start, pos, line_main, line_cross));
5154                line_start = pos;
5155                line_main = m;
5156                line_cross = c;
5157            } else {
5158                line_main += add;
5159                line_cross = line_cross.max(c);
5160            }
5161        }
5162        lines.push((line_start, fln, line_main, line_cross));
5163        // ベースライン整列: 行ごとの (最大 ascent) と、ascent + descent による行の交差サイズ。
5164        let mut line_ascent: Vec<i32> = alloc::vec![0; lines.len()];
5165        if is_row && super::baseline::baseline_enabled() {
5166            for (li, line) in lines.iter_mut().enumerate() {
5167                let items: Vec<usize> = (line.0..line.1).map(|p| flow_idx[p]).collect();
5168                if let Some((_, asc, total)) = self.flex_baseline_layout_of(&items, align_items) {
5169                    line_ascent[li] = asc;
5170                    line.3 = line.3.max(total);
5171                }
5172            }
5173        }
5174
5175        // flex-grow: 各行の余りを、grow を持つ項目へ係数比で配る(CSS Flexbox §9.7)。
5176        if is_row || container_main < i32::MAX / 8 {
5177            for line in lines.iter_mut() {
5178                let (st, en, used, _) = *line;
5179                let free = container_main - used;
5180                if free <= 0 {
5181                    continue;
5182                }
5183                let total_grow: i32 = (st..en).map(|p| box_flex_grow(&self.children[flow_idx[p]])).sum();
5184                if total_grow <= 0 {
5185                    continue;
5186                }
5187                // 伸び幅を §9.7 の「凍結」で決める: 上限(max-width/max-height)に当たった項目は上限で止め、
5188                // 残りの空きを他の項目へ配り直す(WPT multiline-min-max: `flex:1 1 600px; max-width:300px` の隣が 145px)。
5189                let shares = {
5190                    let cw = self.dimensions.content.width;
5191                    let ch = explicit_h.unwrap_or(0);
5192                    let items: Vec<(usize, i32, i32, Option<i32>)> = (st..en)
5193                        .map(|p| {
5194                            let ci = flow_idx[p];
5195                            let c = &self.children[ci];
5196                            let g = box_flex_grow(c);
5197                            let (base, mx) = if is_row {
5198                                let inner = border_box_inner_w(c);
5199                                (c.dimensions.content.width, box_len(c, "max-width", cw).map(|m| (m - inner).max(0)))
5200                            } else {
5201                                let inner = border_box_inner_h(c);
5202                                let pct = box_style_value_ref(c, "max-height").is_some_and(|v| v.contains('%'));
5203                                let mx = if pct && explicit_h.is_none() { None } else { box_len(c, "max-height", ch) };
5204                                (c.dimensions.content.height, mx.map(|m| (m - inner).max(0)))
5205                            };
5206                            (ci, g, base, mx)
5207                        })
5208                        .collect();
5209                    let mut frozen: Vec<bool> = items.iter().map(|it| it.1 <= 0 || it.3.is_some_and(|m| m <= it.2)).collect();
5210                    let mut out: Vec<i32> = alloc::vec![0; items.len()];
5211                    let mut remaining = free;
5212                    loop {
5213                        let gsum: i32 = items.iter().zip(frozen.iter()).filter(|(_, f)| !**f).map(|(it, _)| it.1).sum();
5214                        if gsum <= 0 || remaining <= 0 {
5215                            break;
5216                        }
5217                        let mut left = remaining;
5218                        let mut gl = gsum;
5219                        let mut trial: Vec<i32> = alloc::vec![0; items.len()];
5220                        for (k, it) in items.iter().enumerate() {
5221                            if frozen[k] {
5222                                continue;
5223                            }
5224                            let s = left * it.1 / gl;
5225                            left -= s;
5226                            gl -= it.1;
5227                            trial[k] = s;
5228                        }
5229                        let mut clamped_any = false;
5230                        for (k, it) in items.iter().enumerate() {
5231                            if frozen[k] {
5232                                continue;
5233                            }
5234                            if let Some(mx) = it.3 {
5235                                let room = mx - it.2 - out[k];
5236                                if trial[k] > room {
5237                                    out[k] += room.max(0);
5238                                    remaining -= room.max(0);
5239                                    frozen[k] = true;
5240                                    clamped_any = true;
5241                                }
5242                            }
5243                        }
5244                        if !clamped_any {
5245                            for (k, t) in trial.iter().enumerate() {
5246                                if !frozen[k] {
5247                                    out[k] += *t;
5248                                }
5249                            }
5250                            break;
5251                        }
5252                    }
5253                    items.iter().map(|it| it.0).zip(out).collect::<Vec<(usize, i32)>>()
5254                };
5255                let granted: i32 = shares.iter().map(|s| s.1.max(0)).sum();
5256                for (ci, share) in shares {
5257                    if share <= 0 {
5258                        continue;
5259                    }
5260                    let child = &mut self.children[ci];
5261                    if is_row {
5262                        child.dimensions.content.width += share;
5263                    } else {
5264                        let new_h = (child.dimensions.content.height + share).max(0);
5265                        if explicit_h.is_some()
5266                            && matches!(child.box_type, BoxType::BlockNode(_) | BoxType::FlexNode(_) | BoxType::GridNode(_))
5267                            && subtree_has_pct_h_or_oof(child)
5268                        {
5269                            let mb0 = child.dimensions.margin_box();
5270                            FORCED_BLOCK_H.store(new_h, AtomicOrdering::Relaxed);
5271                            let cb = Dimensions {
5272                                content: Rect { x: mb0.x, y: mb0.y, width: mb0.width, height: 0 },
5273                                ..Default::default()
5274                            };
5275                            child.layout_fg_item(cb);
5276                            FORCED_BLOCK_H.store(-1, AtomicOrdering::Relaxed);
5277                        }
5278                        child.dimensions.content.height = new_h;
5279                    }
5280                    sizes[ci].0 += share;
5281                }
5282                line.2 = used + granted;
5283            }
5284        }
5285
5286        // wrap-reverse は交差軸の向きが逆(行は交差軸の終端側から積まれる)。通常と同じ順で
5287        // 位置を決めてから、最後に交差軸方向へ鏡映する。
5288
5289        // コンテナ交差軸長を確定。
5290        let total_cross: i32 =
5291            lines.iter().map(|l| l.3).sum::<i32>() + gap_cross * (lines.len() as i32 - 1).max(0);
5292        let container_cross = if is_row {
5293            explicit_h.unwrap_or(total_cross)
5294        } else {
5295            self.dimensions.content.width
5296        };
5297
5298        if is_row {
5299            self.dimensions.content.height = container_cross;
5300        } else {
5301            // column: 高さは主軸の長さ(明示の高さ、無ければ最も長い行の主軸合計に min/max-height を適用)。
5302            let longest = lines.iter().map(|l| l.2).max().unwrap_or(0);
5303            self.dimensions.content.height = if explicit_h.is_some() {
5304                container_main
5305            } else {
5306                let mut h = longest.min(container_main);
5307                if let Some(mx) = max_h {
5308                    h = h.min(mx);
5309                }
5310                if let Some(mn) = min_h {
5311                    h = h.max(mn);
5312                }
5313                h
5314            };
5315        }
5316
5317        let base_x = self.dimensions.content.x;
5318        let base_y = self.dimensions.content.y;
5319
5320        // align-content: 複数行ブロックを交差軸方向にどう配置するか。
5321        // 余剰交差空間 = container_cross - total_cross(行の自然交差合計)。
5322        // line_cross_start[i] = 各行の交差軸開始位置、line_cross_size[i] = 各行の交差軸高さ
5323        // (stretch では余剰を均等に各行へ加算)。
5324        let nlines = lines.len() as i32;
5325        let cross_free = container_cross - total_cross;
5326        let mut line_cross_f: Vec<f32> = lines.iter().map(|l| l.3 as f32).collect();
5327        // stretch: 余剰を各行へ均等分配。単一行でもコンテナ全体へ伸ばす。
5328        if (align_content.eq_ignore_ascii_case("stretch") || align_content.is_empty() || align_content.eq_ignore_ascii_case("normal"))
5329            && cross_free > 0
5330            && nlines > 0
5331        {
5332            let per = cross_free as f32 / nlines as f32;
5333            for sz in line_cross_f.iter_mut() {
5334                *sz += per;
5335            }
5336        }
5337        // 各行の開始オフセットと行間スペースを align-content から決める。
5338        let cf = cross_free as f32;
5339        let nl = nlines as f32;
5340        // wrap-reverse は交差軸を鏡映して配置するので、物理の start/end(flex-start/flex-end ではない)は入れ替える。
5341        let ac = match (wrap_reverse, align_content.trim()) {
5342            (true, "start") => "flex-end",
5343            (true, "end") => "flex-start",
5344            (_, a) => a,
5345        };
5346        let (ac_offset, ac_spacing): (f32, f32) = if ac.eq_ignore_ascii_case("flex-end") || ac.eq_ignore_ascii_case("end") {
5347            (cf, 0.0)
5348        } else if ac.eq_ignore_ascii_case("center") {
5349            (cf / 2.0, 0.0)
5350        } else if ac.eq_ignore_ascii_case("space-between") && nlines > 1 {
5351            if cf > 0.0 { (0.0, cf / (nl - 1.0)) } else { (0.0, 0.0) }
5352        } else if ac.eq_ignore_ascii_case("space-around") && nlines > 0 {
5353            if cf > 0.0 { (cf / (nl * 2.0), cf / nl) } else { (0.0, 0.0) }
5354        } else if ac.eq_ignore_ascii_case("space-evenly") && nlines > 0 {
5355            if cf > 0.0 { (cf / (nl + 1.0), cf / (nl + 1.0)) } else { (0.0, 0.0) }
5356        } else {
5357            // flex-start / start / stretch(余剰は行サイズ側で消費済み)
5358            (0.0, 0.0)
5359        };
5360        let mut line_cross_start: Vec<i32> = Vec::with_capacity(lines.len());
5361        let mut line_cross_size: Vec<i32> = Vec::with_capacity(lines.len());
5362        let mut ccf = ac_offset;
5363        for sz in &line_cross_f {
5364            let st = round_f32_to_i32(ccf);
5365            line_cross_start.push(st);
5366            line_cross_size.push((round_f32_to_i32(ccf + sz) - st).max(0));
5367            ccf += sz + gap_cross as f32 + ac_spacing;
5368        }
5369        let cross_total = if is_row { self.dimensions.content.height } else { self.dimensions.content.width };
5370
5371        for (li, &(start, end_excl, line_main_used, _line_cross_nat)) in lines.iter().enumerate() {
5372            let count = end_excl - start;
5373            let main_free = container_main - line_main_used;
5374            let line_cross = line_cross_size.get(li).copied().unwrap_or(0);
5375            let cross_cursor = line_cross_start.get(li).copied().unwrap_or(0);
5376
5377            // 行内の主軸 auto margins を集計(CSS Flexbox §9.7: justify-content より優先)。
5378            let mut total_auto_margins = 0i32;
5379            for p in start..end_excl {
5380                let ci = flow_idx[p];
5381                let (a, b) = box_main_auto_margins(&self.children[ci], is_row);
5382                total_auto_margins += a as i32 + b as i32;
5383            }
5384            let use_auto_margins = total_auto_margins > 0 && main_free > 0;
5385            let auto_margin_unit = if use_auto_margins {
5386                main_free / total_auto_margins
5387            } else {
5388                0
5389            };
5390
5391            // justify-content(主軸)。`end` は `flex-end` の別名(単一行側と同じ修正)。
5392            let is_rtl = box_is_rtl(self);
5393            let main_phys_reverse = is_reverse ^ (is_row && is_rtl);
5394            let cross_phys_reverse = wrap_reverse ^ (!is_row && is_rtl);
5395            let eff_jc = match (is_reverse, justify_content.trim()) {
5396                (true, "start") => "flex-end",
5397                (true, "end") => "flex-start",
5398                _ => justify_content,
5399            };
5400            let eff_jc = if is_row && (eff_jc.eq_ignore_ascii_case("left") || eff_jc.eq_ignore_ascii_case("right")) {
5401                let want_right = eff_jc.eq_ignore_ascii_case("right");
5402                if want_right == main_phys_reverse { "flex-start" } else { "flex-end" }
5403            } else {
5404                eff_jc
5405            };
5406            let mut main_offset = if use_auto_margins {
5407                0
5408            } else if eff_jc.eq_ignore_ascii_case("flex-end") || eff_jc.eq_ignore_ascii_case("end") {
5409                main_free
5410            } else if eff_jc.eq_ignore_ascii_case("center") {
5411                main_free / 2
5412            } else if eff_jc.eq_ignore_ascii_case("space-around") && count > 0 {
5413                main_free / (count as i32 * 2)
5414            } else if eff_jc.eq_ignore_ascii_case("space-evenly") && count > 0 {
5415                main_free / (count as i32 + 1)
5416            } else {
5417                0
5418            };
5419            let spacing = if use_auto_margins {
5420                0
5421            } else if eff_jc.eq_ignore_ascii_case("space-between") && count > 1 {
5422                main_free / (count as i32 - 1)
5423            } else if eff_jc.eq_ignore_ascii_case("space-around") && count > 0 {
5424                main_free / (count as i32)
5425            } else if eff_jc.eq_ignore_ascii_case("space-evenly") && count > 0 {
5426                main_free / (count as i32 + 1)
5427            } else {
5428                0
5429            };
5430
5431            // 行内の配置順。main_phys_reverse 時も DOM 順で終端側から積む(main_start で反転)。
5432            let pos_list: Vec<usize> = (start..end_excl).collect();
5433
5434            for &pos in &pos_list {
5435                let ci = flow_idx[pos];
5436                let (lead_auto, trail_auto) = if use_auto_margins {
5437                    let (a, b) = box_main_auto_margins(&self.children[ci], is_row);
5438                    if main_phys_reverse { (b, a) } else { (a, b) }
5439                } else {
5440                    (false, false)
5441                };
5442                if lead_auto {
5443                    main_offset += auto_margin_unit;
5444                }
5445                let (m, c) = sizes[ci];
5446                let self_align_opt = box_align_self(&self.children[ci]);
5447                let effective_align = self_align_opt.as_deref().unwrap_or(align_items);
5448                let (ca, cb) = box_main_auto_margins(&self.children[ci], !is_row);
5449                // align-items: stretch(既定): 交差軸サイズが auto の項目は行の交差サイズまで伸ばす。
5450                let mut c = c;
5451                let is_stretch = !matches!(
5452                    effective_align.trim(),
5453                    "flex-start" | "start" | "self-start" | "flex-end" | "end" | "self-end" | "center" | "baseline"
5454                        | "first baseline" | "last baseline"
5455                );
5456                let cross_prop = if is_row { "height" } else { "width" };
5457                if is_stretch
5458                    && !ca && !cb
5459                    && !oof[ci]
5460                    && !box_has_explicit(&self.children[ci], cross_prop)
5461                    && box_aspect_ratio(&self.children[ci]).is_none()
5462                {
5463                    let child = &mut self.children[ci];
5464                    let new_c = if is_row {
5465                        let nc = (line_cross - (child.dimensions.margin_box().height - child.dimensions.content.height)).max(0);
5466                        let depends = matches!(child.box_type, BoxType::BlockNode(_) | BoxType::FlexNode(_) | BoxType::GridNode(_))
5467                            && subtree_has_pct_h_or_oof(child);
5468                        if depends {
5469                            let mb0 = child.dimensions.margin_box();
5470                            FORCED_BLOCK_H.store(nc, AtomicOrdering::Relaxed);
5471                            let cb = Dimensions {
5472                                content: Rect { x: mb0.x, y: mb0.y, width: mb0.width, height: 0 },
5473                                ..Default::default()
5474                            };
5475                            child.layout(cb);
5476                            FORCED_BLOCK_H.store(-1, AtomicOrdering::Relaxed);
5477                        }
5478                        child.dimensions.content.height = nc;
5479                        line_cross
5480                    } else {
5481                        if line_cross > c {
5482                            child.dimensions.content.width += line_cross - c;
5483                            line_cross
5484                        } else {
5485                            c
5486                        }
5487                    };
5488                    c = new_c;
5489                }
5490                let cross_free_item = line_cross - c;
5491                let mut cross_pos = if (ca || cb) && cross_free_item > 0 {
5492                    let phys_off = match (ca, cb) {
5493                        (true, true) => cross_free_item / 2,
5494                        (true, false) => cross_free_item,
5495                        (false, true) => 0,
5496                        (false, false) => 0,
5497                    };
5498                    if cross_phys_reverse {
5499                        (cross_total - cross_cursor - line_cross) + phys_off
5500                    } else {
5501                        cross_cursor + phys_off
5502                    }
5503                } else {
5504                    let effective_align = match (wrap_reverse, effective_align.trim()) {
5505                        (true, "start" | "self-start") => "flex-end",
5506                        (true, "end" | "self-end") => "flex-start",
5507                        (_, a) => a,
5508                    };
5509                    let is_baseline_item = is_row
5510                        && super::baseline::baseline_enabled()
5511                        && super::baseline::is_baseline_align(effective_align);
5512                    let cross_in_line = if is_baseline_item && cross_phys_reverse {
5513                        // wrap-reverse: 行の交差始端は物理の下端。ベースラインをそろえた組を下端へ寄せ、組の中の
5514                        // ずれは保つ(鏡映すると組の中のずれまで逆になる。WPT alignment/multiline-align-self)。
5515                        let asc = line_ascent[li];
5516                        let group_h = (start..end_excl)
5517                            .map(|p| &self.children[flow_idx[p]])
5518                            .filter(|it| {
5519                                let a = box_align_self(it);
5520                                super::baseline::is_baseline_align(a.as_deref().unwrap_or(align_items))
5521                            })
5522                            .map(|it| asc - it.item_baseline_from_margin_top() + it.dimensions.margin_box().height)
5523                            .max()
5524                            .unwrap_or(c);
5525                        let off = (asc - self.children[ci].item_baseline_from_margin_top()).max(0);
5526                        // 後の鏡映(cp = cross_total - cp - c)で「下端 - 組の高さ + off」になるよう逆算する。
5527                        (line_cross - (line_cross - group_h + off) - c).max(0)
5528                    } else if is_baseline_item {
5529                        (line_ascent[li] - self.children[ci].item_baseline_from_margin_top()).max(0)
5530                    } else if !is_row
5531                        && super::baseline::baseline_enabled()
5532                        && super::baseline::is_baseline_align(effective_align)
5533                    {
5534                        // 縦並び: 項目(横書き)のベースラインは交差軸(行内方向)と直交するので、行内始端の border 辺から
5535                        // 合成したベースラインでそろえる(CSS Align 3 §9.1)。組の中で最も大きい始端 margin に border 辺を合わせる
5536                        // (WPT alignment/multiline-align-self: `margin-inline-start: 5px` の隣の項目が x=5)。
5537                        // 位置は物理(行の左端から)で求めてから、後の鏡映(cross_phys_reverse)の分を逆算する。
5538                        // 組は行の交差始端へ寄せる。wrap-reverse では交差始端が行内始端の反対側になる。
5539                        let lead = |it: &LayoutBox| if is_rtl { it.dimensions.margin.right } else { it.dimensions.margin.left };
5540                        let group: Vec<(i32, i32)> = (start..end_excl)
5541                            .map(|p| &self.children[flow_idx[p]])
5542                            .filter(|it| {
5543                                let a = box_align_self(it);
5544                                super::baseline::is_baseline_align(a.as_deref().unwrap_or(align_items))
5545                            })
5546                            .map(|it| (lead(it), it.dimensions.margin_box().width))
5547                            .collect();
5548                        let group_lead = group.iter().map(|g| g.0).max().unwrap_or(0);
5549                        let group_ext = group.iter().map(|g| group_lead - g.0 + g.1).max().unwrap_or(c);
5550                        let own_lead = lead(&self.children[ci]);
5551                        let d = if wrap_reverse {
5552                            line_cross - group_ext + (group_lead - own_lead)
5553                        } else {
5554                            group_lead - own_lead
5555                        };
5556                        let phys = if is_rtl { line_cross - d - c } else { d };
5557                        if cross_phys_reverse { line_cross - phys - c } else { phys }
5558                    } else if effective_align.eq_ignore_ascii_case("flex-end")
5559                        || effective_align.eq_ignore_ascii_case("end")
5560                        || effective_align.eq_ignore_ascii_case("self-end")
5561                    {
5562                        cross_free_item
5563                    } else if effective_align.eq_ignore_ascii_case("center") {
5564                        cross_free_item / 2
5565                    } else {
5566                        0 // flex-start / start / stretch
5567                    };
5568                    let mut cp = cross_cursor + cross_in_line;
5569                    if cross_phys_reverse {
5570                        cp = cross_total - cp - c;
5571                    }
5572                    cp
5573                };
5574                let _ = &mut cross_pos;
5575
5576                let main_start = if main_phys_reverse {
5577                    container_main - main_offset - m
5578                } else {
5579                    main_offset
5580                };
5581                let (target_x, target_y) = if is_row {
5582                    (base_x + main_start, base_y + cross_pos)
5583                } else {
5584                    (base_x + cross_pos, base_y + main_start)
5585                };
5586
5587                let shift_x = target_x - self.children[ci].dimensions.margin_box().x;
5588                let shift_y = target_y - self.children[ci].dimensions.margin_box().y;
5589                shift_layout_box(&mut self.children[ci], shift_x, shift_y);
5590
5591                main_offset += m + spacing + gap_main;
5592                if trail_auto {
5593                    main_offset += auto_margin_unit;
5594                }
5595            }
5596        }
5597
5598        // positioned 子要素の配置(out-of-flow の abspos 静的位置も Flexbox §4.1 で配置)。
5599        let is_rtl = box_is_rtl(self);
5600        let container_cross_w = cross_total;
5601        for (ci, child) in self.children.iter_mut().enumerate() {
5602            if !oof.get(ci).copied().unwrap_or(false) || box_position(child) != "absolute" {
5603                continue;
5604            }
5605            let mb = child.dimensions.margin_box();
5606            let child_main = if is_row { mb.width } else { mb.height };
5607            let child_cross = if is_row { mb.height } else { mb.width };
5608            let free_m = container_main - child_main;
5609            let j_off = if justify_content.eq_ignore_ascii_case("flex-end") {
5610                free_m
5611            } else if justify_content.eq_ignore_ascii_case("center")
5612                || justify_content.eq_ignore_ascii_case("space-around")
5613                || justify_content.eq_ignore_ascii_case("space-evenly")
5614            {
5615                free_m / 2
5616            } else if justify_content.eq_ignore_ascii_case("end") {
5617                if is_reverse { 0 } else { free_m }
5618            } else {
5619                0
5620            };
5621            let mut main_pos = if is_reverse { container_main - j_off - child_main } else { j_off };
5622            if is_row && is_rtl {
5623                main_pos = container_main - main_pos - child_main;
5624            }
5625            let self_align_opt = box_align_self(child);
5626            let eff_a = self_align_opt.as_deref().unwrap_or(align_items);
5627            let free_c = container_cross_w - child_cross;
5628            let mut cross_pos = if eff_a.eq_ignore_ascii_case("flex-end") {
5629                free_c
5630            } else if eff_a.eq_ignore_ascii_case("center") {
5631                free_c / 2
5632            } else if eff_a.eq_ignore_ascii_case("end") || eff_a.eq_ignore_ascii_case("self-end") {
5633                if !is_row && is_rtl { 0 } else { free_c }
5634            } else if (eff_a.eq_ignore_ascii_case("start") || eff_a.eq_ignore_ascii_case("self-start")) && !is_row && is_rtl {
5635                free_c
5636            } else {
5637                0
5638            };
5639            if wrap_reverse && !(eff_a.eq_ignore_ascii_case("start") || eff_a.eq_ignore_ascii_case("self-start") || eff_a.eq_ignore_ascii_case("end") || eff_a.eq_ignore_ascii_case("self-end")) {
5640                cross_pos = container_cross_w - cross_pos - child_cross;
5641            }
5642            if !is_row && is_rtl && (eff_a.eq_ignore_ascii_case("flex-start") || eff_a.eq_ignore_ascii_case("flex-end") || eff_a.eq_ignore_ascii_case("stretch") || eff_a.eq_ignore_ascii_case("normal") || eff_a.is_empty()) {
5643                cross_pos = container_cross_w - cross_pos - child_cross;
5644            }
5645            let (tx, ty) = if is_row {
5646                (base_x + main_pos, base_y + cross_pos)
5647            } else {
5648                (base_x + cross_pos, base_y + main_pos)
5649            };
5650            shift_layout_box(child, tx - mb.x, ty - mb.y);
5651        }
5652        let saved_abs_cb = self.establish_abs_cb();
5653        self.apply_positioned_offsets_with(None, true);
5654        Self::restore_abs_cb(saved_abs_cb);
5655    }
5656
5657    fn layout_block(&mut self, containing_block: Dimensions, is_fg_item: bool) {
5658        // 外から確定させた高さ(絶対配置の top+bottom。`FORCED_BLOCK_H`)。子孫へ漏らさないよう先に取る。
5659        let forced_h = FORCED_BLOCK_H.swap(-1, AtomicOrdering::Relaxed);
5660        let edge_cb_w = match box_position(self) {
5661            "absolute" => abs_cb_get().2,
5662            "fixed" => fixed_cb_get()
5663                .filter(|&(_, _, _, h)| h > 0)
5664                .map(|(_, _, w, _)| w)
5665                .unwrap_or_else(|| VIEWPORT_HINT_W.load(AtomicOrdering::Relaxed)),
5666            _ => containing_block.content.width,
5667        };
5668        self.apply_box_model_styles_with_base(edge_cb_w);
5669        // 自分の `height:%` の基準(包含ブロックの確定高さ。未確定なら -1)。下で子のために
5670        // 差し替える前に読む。
5671        let pct_base_h = PCT_BASE_H.load(AtomicOrdering::Relaxed);
5672
5673        // テーブル系 (row-group/row/cell) も table 経由で block としてレイアウトされるため
5674        // ここで styled node を取り出せるようにする。取り出せない型のみ早期 return。
5675        let (
5676            width_val,
5677            min_width_val,
5678            max_width_val,
5679            height_val,
5680            min_height_val,
5681            max_height_val,
5682            box_sizing,
5683            h_auto,
5684            aspect_ratio_val,
5685        ) = match &self.box_type {
5686            BoxType::BlockNode(node)
5687            | BoxType::TableRowGroupNode(node)
5688            | BoxType::TableRowNode(node)
5689            | BoxType::TableCellNode(node) => (
5690                len_value(node, "width"),
5691                len_value(node, "min-width"),
5692                len_value(node, "max-width"),
5693                len_value(node, "height"),
5694                len_value(node, "min-height"),
5695                len_value(node, "max-height"),
5696                node.value_ref("box-sizing").unwrap_or(""),
5697                margin_is_h_auto(node),
5698                node.value_ref("aspect-ratio"),
5699            ),
5700            _ => return,
5701        };
5702
5703        let horizontal_non_content = self.dimensions.margin.left
5704            + self.dimensions.margin.right
5705            + self.dimensions.border.left
5706            + self.dimensions.border.right
5707            + self.dimensions.padding.left
5708            + self.dimensions.padding.right;
5709        let available_width = containing_block.content.width.max(0);
5710        // padding + border のみ(box-sizing:border-box / margin:auto センタリング用)。
5711        let inner_non_content = self.dimensions.border.left
5712            + self.dimensions.border.right
5713            + self.dimensions.padding.left
5714            + self.dimensions.padding.right;
5715
5716        // Calculate width
5717        let parsed_width = parse_length_value(width_val.as_deref());
5718        let explicit_width = !matches!(parsed_width, Some(LengthValue::Auto) | None);
5719        let mut content_width = match parsed_width {
5720            Some(LengthValue::Auto) | None => (available_width - horizontal_non_content).max(0),
5721            Some(LengthValue::Px(px)) => px.max(0),
5722            Some(LengthValue::Percent(pct)) => {
5723                round_f32_to_i32(available_width as f32 * pct).max(0)
5724            }
5725            // 内容ベースのキーワード: min/max/fit-content。子コンテンツを計測して解決。
5726            Some(LengthValue::MinContent) => {
5727                let (minc, _maxc) = self.block_intrinsic_widths();
5728                minc.max(0)
5729            }
5730            Some(LengthValue::MaxContent) => {
5731                let (_minc, maxc) = self.block_intrinsic_widths();
5732                maxc.max(0)
5733            }
5734            Some(LengthValue::FitContent) => {
5735                // fit-content = clamp(min-content, available, max-content)
5736                let avail = (available_width - horizontal_non_content).max(0);
5737                let (minc, maxc) = self.block_intrinsic_widths();
5738                maxc.min(avail).max(minc).max(0)
5739            }
5740            Some(LengthValue::FitContentWith(lim_box)) => {
5741                // fit-content(length) = min(max-content, max(min-content, length))
5742                let avail = (available_width - horizontal_non_content).max(0);
5743                let limit = resolve_length_value_with_font(*lim_box, avail, self.font_size())
5744                    .unwrap_or(avail);
5745                let (minc, maxc) = self.block_intrinsic_widths();
5746                maxc.min(limit.max(minc)).max(0)
5747            }
5748            Some(LengthValue::MathExpr(expr)) => {
5749                crate::os_lib::css::eval_css_math_with_font(&expr, available_width, self.font_size())
5750                    .unwrap_or((available_width - horizontal_non_content).max(0))
5751                    .max(0)
5752            }
5753        };
5754        // box-sizing: border-box → 指定 width は border-box 全体なので content は padding+border を引く。
5755        // 【2026-09-26 バグ修正】auto 幅は既に padding/border を除いた残りなので対象外
5756        // (従来は `*{box-sizing:border-box}` の全ブロックで padding が二重に引かれていた)。
5757        if explicit_width && box_sizing.trim() == "border-box" {
5758            content_width = (content_width - inner_non_content).max(0);
5759        }
5760
5761        // min-width / max-width。px/% は available 基準、min/max/fit-content は内容計測で解決。
5762        // min/max-width の長さは border-box なら padding+border を含む(`border_box_inner_w`)。
5763        let bb_inner = if box_sizing.trim() == "border-box" { inner_non_content } else { 0 };
5764        // `stretch`: margin box が包含ブロックを満たす幅(margin・border・padding を除いた残り)。
5765        let stretch_w = (available_width - horizontal_non_content).max(0);
5766        if is_stretch_kw(min_width_val.as_deref()) {
5767            content_width = content_width.max(stretch_w);
5768        } else if let Some(min_width) = self.resolve_sizing_value(min_width_val.as_deref(), available_width) {
5769            let min_width = if is_length_sizing(min_width_val.as_deref()) { (min_width - bb_inner).max(0) } else { min_width };
5770            content_width = content_width.max(min_width);
5771        }
5772        if is_stretch_kw(max_width_val.as_deref()) {
5773            content_width = content_width.min(stretch_w);
5774        } else if let Some(max_width) = self.resolve_sizing_value(max_width_val.as_deref(), available_width) {
5775            let max_width = if is_length_sizing(max_width_val.as_deref()) { (max_width - bb_inner).max(0) } else { max_width };
5776            content_width = content_width.min(max_width);
5777        }
5778        self.dimensions.content.width = content_width.max(0);
5779
5780        // margin: auto(左右)→ ブロックを水平センタリング(out-of-flow の abspos/fixed は除く)。
5781        if h_auto && !Self::child_is_out_of_flow(self) {
5782            let free = (available_width - content_width - inner_non_content).max(0);
5783            self.dimensions.margin.left = free / 2;
5784            self.dimensions.margin.right = free / 2;
5785        }
5786
5787        // Position (content box origin)
5788        let flow_y = containing_block.content.y
5789            + containing_block.content.height
5790            + self.dimensions.margin.top;
5791        self.dimensions.content.x = containing_block.content.x
5792            + self.dimensions.margin.left
5793            + self.dimensions.border.left
5794            + self.dimensions.padding.left;
5795        self.dimensions.content.y =
5796            flow_y + self.dimensions.border.top + self.dimensions.padding.top;
5797
5798        // 子の `height:%`(置換要素)の基準: 明示 px 高さ、または aspect-ratio と確定幅から。
5799        // 未確定なら -1(auto 扱い)。この関数を抜けると自動で戻る。
5800        // 【2026-10-18】`%` も包含ブロックの高さが確定していれば確定値(`html,body{height:100%}` の
5801        // 連鎖。YouTube 埋め込みの `body{position:absolute;height:100%}` → `#player{height:100%}`
5802        // → `#movie_player{height:100%;overflow:hidden}` が高さ 0 になり、動画が全部切られていた)。
5803        let parsed_height = parse_length_value(height_val.as_deref());
5804        let px_h = match &parsed_height {
5805            Some(LengthValue::Px(px)) => Some(*px),
5806            Some(LengthValue::Percent(pct)) if pct_base_h >= 0 => Some(round_f32_to_i32(pct_base_h as f32 * *pct)),
5807            _ => None,
5808        };
5809        let definite_h = match (px_h, &parsed_height) {
5810            (Some(px), _) => {
5811                if box_sizing.trim() == "border-box" {
5812                    let d = &self.dimensions;
5813                    (px - d.padding.top - d.padding.bottom - d.border.top - d.border.bottom).max(0)
5814                } else {
5815                    px.max(0)
5816                }
5817            }
5818            (None, None | Some(LengthValue::Auto)) => aspect_ratio_val
5819                .and_then(parse_aspect_ratio)
5820                .map(world_swap_ratio)
5821                .map(|(num, den)| round_f32_to_i32(self.dimensions.content.width as f32 * den / num).max(0))
5822                .unwrap_or(-1),
5823            _ => -1,
5824        };
5825        let definite_h = if forced_h >= 0 { forced_h } else { definite_h };
5826        let _pct_h_guard = PctBaseHGuard::set(definite_h);
5827
5828        // この要素が包含ブロックを作る(positioned または transform 等)なら、子孫 absolute / fixed の
5829        // 包含ブロックを self に切替(昇り解決)。
5830        // 高さは明示値が分かればそれ、無ければ 0(top/left 配置が主。bottom/right は明示高さ前提)。
5831        let exp_h_for_cb = || {
5832            if forced_h >= 0 {
5833                forced_h
5834            } else if definite_h >= 0 {
5835                definite_h
5836            } else {
5837                parse_length_value(height_val.as_deref())
5838                    .and_then(|v| resolve_length_value(v, containing_block.content.height.max(0)))
5839                    .unwrap_or(0)
5840            }
5841        };
5842        let saved_abs_cb = if box_establishes_abs_cb(self) {
5843            let prev = abs_cb_get();
5844            let exp_h = exp_h_for_cb();
5845            // 包含ブロックはパディングボックス(`establish_abs_cb` と同じ)。
5846            let d = &self.dimensions;
5847            abs_cb_set(
5848                d.content.x - d.padding.left,
5849                d.content.y - d.padding.top,
5850                d.content.width + d.padding.left + d.padding.right,
5851                exp_h + d.padding.top + d.padding.bottom,
5852            );
5853            Some(prev)
5854        } else {
5855            None
5856        };
5857        let saved_fixed_cb = if box_establishes_fixed_cb(self) {
5858            let prev = fixed_cb_get();
5859            let exp_h = exp_h_for_cb();
5860            let d = &self.dimensions;
5861            fixed_cb_set(Some((
5862                d.content.x - d.padding.left,
5863                d.content.y - d.padding.top,
5864                d.content.width + d.padding.left + d.padding.right,
5865                exp_h + d.padding.top + d.padding.bottom,
5866            )));
5867            Some(prev)
5868        } else {
5869            None
5870        };
5871
5872        // 子要素のレイアウト計算(block/inline混在の簡易フロー)
5873        let line_height_default = 20i32;
5874        let strut_h = match &self.box_type {
5875            BoxType::BlockNode(n) => {
5876                let fs = n.value_ref("font-size").and_then(parse_font_size_u32).unwrap_or(16);
5877                parse_line_height(n.value_ref("line-height"), fs).max(1)
5878            }
5879            _ => line_height_default,
5880        };
5881        let mut y_cursor = 0i32;
5882        let mut line_x = 0i32;
5883        let mut line_h = 0i32;
5884        let mut has_line_box = false;
5885        let max_w = self.dimensions.content.width.max(1);
5886
5887        // float: left/right の占有幅と底辺 y を追跡する。(占有幅, 底辺y)。
5888        // 複数floatの左右並び積み重ねはサポートせず、各サイド最新の1個のみを追跡する
5889        // (画像+段落、サイドバー+本文といった典型パターンをカバーする簡易実装)。
5890        let mut left_float: Option<(i32, i32)> = None;
5891        let mut right_float: Option<(i32, i32)> = None;
5892
5893        // 指定 y での float 占有を考慮した (x_offset, 利用可能幅) を返す。
5894        fn float_avail(
5895            max_w: i32,
5896            left_float: Option<(i32, i32)>,
5897            right_float: Option<(i32, i32)>,
5898            y: i32,
5899        ) -> (i32, i32) {
5900            let l = left_float
5901                .filter(|&(_, yb)| yb > y)
5902                .map(|(w, _)| w)
5903                .unwrap_or(0);
5904            let r = right_float
5905                .filter(|&(_, yb)| yb > y)
5906                .map(|(w, _)| w)
5907                .unwrap_or(0);
5908            (l, (max_w - l - r).max(1))
5909        }
5910
5911        // 行ごとの子の範囲 `[start, end)`。ループ後にベースライン揃えを掛ける。
5912        let mut lines: Vec<(usize, usize)> = Vec::new();
5913        let mut line_start = 0usize;
5914        // 要素間の空白(CSS Text 3 §4.1)。`last_was_space`: 直前に置いたのが空白
5915        // (行頭も含む)。`trailing_space`: 行の最後に置いた空白(行末ならぶら下げて幅 0)。
5916        let mut last_was_space = true;
5917        let mut trailing_space: Option<(usize, i32)> = None;
5918        let mut hanging: Vec<(usize, i32)> = Vec::new();
5919        let mut seen_in_flow = false;
5920        // 直前に置いた流れの中のブロックの下 margin(兄弟の margin 相殺用。CSS 2.1 §8.3.1)。
5921        // 間に行(インラインの内容)や clear が入ると隣接しないので None に戻す。
5922        let mut prev_block_mb: Option<i32> = None;
5923        let can_parent_top_collapse = match &self.box_type {
5924            BoxType::BlockNode(n) => {
5925                !is_fg_item
5926                    && !Self::child_is_out_of_flow(self)
5927                    && box_float(self) == "none"
5928                    && self.dimensions.border.top == 0
5929                    && self.dimensions.padding.top == 0
5930                    && !n.value_ref("overflow").is_some_and(|v| matches!(v.trim(), "hidden" | "scroll" | "auto" | "clip"))
5931                    && !n.value_ref("overflow-y").is_some_and(|v| matches!(v.trim(), "hidden" | "scroll" | "auto" | "clip"))
5932            }
5933            _ => false,
5934        };
5935
5936        for (ci, child) in self.children.iter_mut().enumerate() {
5937            let float_side = box_float(child);
5938            if float_side != "none" {
5939                // clear: float 自身は clear の対象にはしない(float 同士は積み重ね非対応のため)。
5940                let float_y = y_cursor;
5941                let is_inline_kind = matches!(child.box_type, BoxType::InlineNode(_) | BoxType::InlineBlockNode(_))
5942                    && !child.is_inline_flex()
5943                    && !child.is_inline_grid();
5944                let (fw, fh) = if is_inline_kind {
5945                    child.intrinsic_inline_size(max_w)
5946                } else {
5947                    let mut cb = self.dimensions.clone();
5948                    cb.content.height = float_y;
5949                    child.layout(cb.clone());
5950                    // 幅 auto のフロートは内容幅に縮む(shrink-to-fit。CSS 2.1 §10.3.5)。
5951                    if !child.is_inline_flex() && !child.is_inline_grid() {
5952                        if let Some(fit) = Self::grid_fit_outer_width(child, max_w, "start") {
5953                            cb.content.width = fit;
5954                            child.layout(cb);
5955                        }
5956                    }
5957                    (
5958                        child.dimensions.margin_box().width,
5959                        child.dimensions.margin_box().height,
5960                    )
5961                };
5962
5963                let (x, float_y) = if float_side == "left" {
5964                    let prev = left_float.filter(|&(_, yb)| yb > float_y);
5965                    if let Some((xw, yb)) = prev {
5966                        if xw + fw > max_w {
5967                            let new_y = yb;
5968                            y_cursor = y_cursor.max(new_y);
5969                            left_float = Some((fw, new_y + fh));
5970                            (self.dimensions.content.x, new_y)
5971                        } else {
5972                            left_float = Some((xw + fw, float_y + fh));
5973                            (self.dimensions.content.x + xw, float_y)
5974                        }
5975                    } else {
5976                        left_float = Some((fw, float_y + fh));
5977                        (self.dimensions.content.x, float_y)
5978                    }
5979                } else {
5980                    let prev = right_float.filter(|&(_, yb)| yb > float_y);
5981                    if let Some((xw, yb)) = prev {
5982                        if xw + fw > max_w {
5983                            let new_y = yb;
5984                            y_cursor = y_cursor.max(new_y);
5985                            right_float = Some((fw, new_y + fh));
5986                            (self.dimensions.content.x + max_w - fw, new_y)
5987                        } else {
5988                            right_float = Some((xw + fw, float_y + fh));
5989                            (self.dimensions.content.x + max_w - xw - fw, float_y)
5990                        }
5991                    } else {
5992                        right_float = Some((fw, float_y + fh));
5993                        (self.dimensions.content.x + max_w - fw, float_y)
5994                    }
5995                };
5996
5997                if is_inline_kind {
5998                    child.dimensions.content.x = x;
5999                    child.dimensions.content.y = self.dimensions.content.y + float_y;
6000                    child.dimensions.content.width = fw;
6001                    child.dimensions.content.height = fh;
6002                    let mut cb = child.dimensions.clone();
6003                    cb.content.height = 0;
6004                    child.layout(cb);
6005                    child.dimensions.content.x = x;
6006                    child.dimensions.content.y = self.dimensions.content.y + float_y;
6007                    child.dimensions.content.width = fw;
6008                    child.dimensions.content.height = fh;
6009                } else {
6010                    // 通常 block レイアウト済み。margin box の左端を float の位置 x へ移す
6011                    // (子孫もまとめて動かす)。
6012                    let dx = x - child.dimensions.margin_box().x;
6013                    child.translate(dx, 0);
6014                }
6015                // float はフローの縦カーソルを進めない。
6016                continue;
6017            }
6018
6019            match child.box_type {
6020                BoxType::BlockNode(_)
6021                | BoxType::FlexNode(_)
6022                | BoxType::GridNode(_)
6023                | BoxType::AnonymousBlock
6024                | BoxType::TableNode(_)
6025                | BoxType::TableRowGroupNode(_)
6026                | BoxType::TableRowNode(_)
6027                | BoxType::TableCellNode(_) => {
6028                    let out_of_flow = matches!(box_position(child), "absolute" | "fixed");
6029                    if out_of_flow {
6030                        // フロー外: サイズ確定のためレイアウトのみ。位置は後処理、cursor は進めない。
6031                        let mut cb = self.dimensions.clone();
6032                        cb.content.height = y_cursor;
6033                        child.layout(cb);
6034                    } else {
6035                        if line_x > 0 || has_line_box {
6036                            lines.push((line_start, ci));
6037                            hanging.extend(trailing_space.take());
6038                            y_cursor += if line_h > 0 { line_h } else { strut_h };
6039                            line_x = 0;
6040                            line_h = 0;
6041                            has_line_box = false;
6042                            prev_block_mb = None;
6043                        }
6044                        last_was_space = true;
6045                        // clear: 該当サイドの float 底辺まで縦カーソルを進める。
6046                        let clear = box_clear(child);
6047                        let y_before_clear = y_cursor;
6048                        if clear == "left" || clear == "both" {
6049                            if let Some((_, yb)) = left_float {
6050                                y_cursor = y_cursor.max(yb);
6051                            }
6052                        }
6053                        if clear == "right" || clear == "both" {
6054                            if let Some((_, yb)) = right_float {
6055                                y_cursor = y_cursor.max(yb);
6056                            }
6057                        }
6058                        if y_cursor != y_before_clear {
6059                            prev_block_mb = None;
6060                        }
6061                        let (x_off, avail) = float_avail(max_w, left_float, right_float, y_cursor);
6062                        let collapsed_cmt = if can_parent_top_collapse
6063                            && !seen_in_flow
6064                            && y_cursor == 0
6065                            && left_float.is_none()
6066                            && right_float.is_none()
6067                            && matches!(
6068                                child.box_type,
6069                                BoxType::BlockNode(_) | BoxType::FlexNode(_) | BoxType::GridNode(_) | BoxType::TableNode(_)
6070                            )
6071                        {
6072                            child.apply_box_model_styles_with_base(avail);
6073                            let cmt = child.dimensions.margin.top;
6074                            if cmt > 0 {
6075                                let collapsed = self.dimensions.margin.top.max(cmt);
6076                                let dy_parent = collapsed - self.dimensions.margin.top;
6077                                self.dimensions.margin.top = collapsed;
6078                                self.dimensions.content.y += dy_parent;
6079                                if saved_abs_cb.is_some() {
6080                                    let (ax, ay, aw, ah) = abs_cb_get();
6081                                    abs_cb_set(ax, ay + dy_parent, aw, ah);
6082                                }
6083                                if saved_fixed_cb.is_some() {
6084                                    if let Some((fx, fy, fw, fh)) = fixed_cb_get() {
6085                                        fixed_cb_set(Some((fx, fy + dy_parent, fw, fh)));
6086                                    }
6087                                }
6088                                Some(cmt)
6089                            } else {
6090                                None
6091                            }
6092                        } else {
6093                            None
6094                        };
6095                        let mut cb = self.dimensions.clone();
6096                        cb.content.height = y_cursor;
6097                        cb.content.x = self.dimensions.content.x + x_off;
6098                        cb.content.width = avail;
6099                        child.layout(cb);
6100                        if let Some(cmt) = collapsed_cmt {
6101                            child.translate_collapse_margin_top(-cmt, false);
6102                            child.dimensions.margin.top = 0;
6103                        }
6104                        // 隣り合うブロックの margin 相殺(CSS 2.1 §8.3.1): 前の下 margin と自分の上 margin は
6105                        // 「正の最大 + 負の最小」に畳む。重なった分だけ自分を上へ寄せる(WPT css-flexbox text-as-flexitem-size-001:
6106                        // `p{margin:.5em}` が 2 つ並んで 40px でなく 35px)。
6107                        if let Some(pmb) = prev_block_mb {
6108                            let cmt = child.dimensions.margin.top;
6109                            let collapsed = pmb.max(cmt).max(0) + pmb.min(cmt).min(0);
6110                            let overlap = pmb + cmt - collapsed;
6111                            if overlap != 0 {
6112                                child.translate_collapse_margin_top(-overlap, false);
6113                                y_cursor -= overlap;
6114                            }
6115                        }
6116                        seen_in_flow = true;
6117                        y_cursor += child.dimensions.margin_box().height;
6118                        prev_block_mb = Some(child.dimensions.margin.bottom);
6119                    }
6120                }
6121                BoxType::InlineNode(_) | BoxType::InlineBlockNode(_) => {
6122                    if child.is_inline_line_break() {
6123                        seen_in_flow = true;
6124                        prev_block_mb = None;
6125                        if line_x > 0 || has_line_box {
6126                            lines.push((line_start, ci));
6127                        }
6128                        hanging.extend(trailing_space.take());
6129                        last_was_space = true;
6130                        y_cursor += if line_h > 0 { line_h } else { strut_h };
6131                        line_x = 0;
6132                        line_h = 0;
6133                        has_line_box = false;
6134                        child.dimensions.content.x = self.dimensions.content.x;
6135                        child.dimensions.content.y = self.dimensions.content.y + y_cursor;
6136                        child.dimensions.content.width = 0;
6137                        child.dimensions.content.height = 0;
6138                        continue;
6139                    }
6140                    let (mut x_off, mut eff_w) =
6141                        float_avail(max_w, left_float, right_float, y_cursor);
6142                    // 先頭空白の印は置き場所で決まるので、組み直しの度に付け直す。
6143                    child.trim_leading_space = false;
6144                    let (mut inline_w, mut inline_h) = child.intrinsic_inline_size(eff_w);
6145                    // 【2026-10-09】要素間の空白は畳んで半角 1 つぶんの幅を持つ。行頭と、直前が
6146                    // 空白のときは 0。空白自身では折り返さない(行末ならぶら下げ)。従来は
6147                    // 行末の空白を除く計測のため常に幅 0 で、forms.htm の `<img> <a>` が
6148                    // 折り返すべき幅で 1 行に収まった。
6149                    let is_space = child.is_collapsible_space();
6150                    if !is_space {
6151                        seen_in_flow = true;
6152                        prev_block_mb = None;
6153                    }
6154                    let mut text_trailing_w = 0i32;
6155                    if is_space {
6156                        inline_w = if line_x == 0 || last_was_space { 0 } else { child.collapsed_space_width() };
6157                        if inline_w == 0 {
6158                            // 取り除かれた空白は行も作らない(ブロック間の改行・字下げ)。
6159                            inline_h = 0;
6160                        }
6161                    } else {
6162                        if child.text_starts_with_space() && (line_x == 0 || last_was_space) {
6163                            inline_w = inline_w.saturating_sub(child.collapsed_space_width());
6164                            child.trim_leading_space = true;
6165                        }
6166                        if child.text_ends_with_space() {
6167                            let sp_w = child.collapsed_space_width();
6168                            inline_w += sp_w;
6169                            text_trailing_w = sp_w;
6170                        }
6171                    }
6172                    // 折り返し判定も inline-block / 置換要素の余白込みで行う(2026-09-26, 2026-10-13)。
6173                    let edges_w = if matches!(child.box_type, BoxType::InlineBlockNode(_)) || child.is_replaced_inline() {
6174                        intrinsic_h_edges(child, false)
6175                    } else {
6176                        0
6177                    };
6178                    if !is_space && (line_x > 0 || has_line_box) && line_x + inline_w + edges_w > eff_w {
6179                        lines.push((line_start, ci));
6180                        hanging.extend(trailing_space.take());
6181                        y_cursor += if line_h > 0 { line_h } else { strut_h };
6182                        line_x = 0;
6183                        line_h = 0;
6184                        has_line_box = false;
6185                        let recomputed = float_avail(max_w, left_float, right_float, y_cursor);
6186                        x_off = recomputed.0;
6187                        eff_w = recomputed.1;
6188                    }
6189                    if line_x == 0 && !has_line_box {
6190                        line_start = ci;
6191                        // 折り返して行頭に来た文字も先頭の空白を落とす。
6192                        if !is_space && !child.trim_leading_space && child.text_starts_with_space() {
6193                            inline_w = inline_w.saturating_sub(child.collapsed_space_width());
6194                            child.trim_leading_space = true;
6195                        }
6196                    }
6197                    let _ = eff_w;
6198                    child.dimensions.content.x = self.dimensions.content.x + x_off + line_x;
6199                    child.dimensions.content.y = self.dimensions.content.y + y_cursor;
6200                    child.dimensions.content.width = inline_w;
6201                    child.dimensions.content.height = inline_h;
6202
6203                    // 子要素(InlineNode など)に対して再帰的にレイアウトを呼び出して、さらにその中の座標を決定する。
6204                    // 注意: layout_inline は containing.content.height を「Y フローカーソル」として
6205                    // 自身の y に加算する規約のため、ここで子自身の高さ (inline_h) を渡すと
6206                    // 子が自分の高さぶん下へずれてしまう(textarea が画面外に飛ぶバグの原因)。
6207                    // 確定済みスロット位置だけを伝えるため height は 0 にして渡す。
6208                    let mut cb = child.dimensions.clone();
6209                    cb.content.height = 0;
6210                    child.layout(cb);
6211                    // layout_inline 内の再計算は % 高さを包含高さ (=0) 基準で解決して
6212                    // 潰してしまうため、親が intrinsic 計測で確定したスロット寸法を最終値とする。
6213                    // 【2026-09-26 バグ修正】位置は**子孫ごと**スロットへ戻す。従来は箱の
6214                    // x/y だけを上書きしたため、layout_inline が margin/padding を足した位置に
6215                    // 組んだ中身が置き去りになり、padding 付きの inline-block
6216                    // (実サイトの `.btn{display:inline-block;padding:1rem 2rem}`)で
6217                    // 文字が箱の外へずれていた。
6218                    // inline-block の margin/border/padding は行内の幅・高さを占める
6219                    // (2026-09-26 まで content だけで並べ、padding が行頭より左へはみ出した)。
6220                    let (el, er, et, eb) = child.inline_block_edges();
6221                    let slot_x = self.dimensions.content.x + x_off + line_x + el;
6222                    let slot_y = self.dimensions.content.y + y_cursor + et;
6223                    let (dx, dy) = (slot_x - child.dimensions.content.x, slot_y - child.dimensions.content.y);
6224                    child.translate(dx, dy);
6225                    child.dimensions.content.width = inline_w;
6226                    child.dimensions.content.height = inline_h;
6227
6228                    line_x += el + inline_w + er;
6229                    if matches!(child.box_type, BoxType::InlineBlockNode(_)) || child.is_replaced_inline() || (!is_space && inline_w > 0) {
6230                        has_line_box = true;
6231                        if line_h < strut_h && matches!(child.box_type, BoxType::InlineBlockNode(_)) {
6232                            line_h = strut_h;
6233                        }
6234                    }
6235                    let outer_h = et + inline_h + eb;
6236                    if outer_h > line_h {
6237                        line_h = outer_h;
6238                    }
6239                    if is_space {
6240                        if inline_w > 0 {
6241                            trailing_space = Some((ci, inline_w));
6242                        }
6243                        last_was_space = true;
6244                    } else if child.text_ends_with_space() {
6245                        if text_trailing_w > 0 {
6246                            trailing_space = Some((ci, text_trailing_w));
6247                        }
6248                        last_was_space = true;
6249                    } else if !child.is_blank_inline() {
6250                        trailing_space = None;
6251                        last_was_space = false;
6252                    }
6253                }
6254            }
6255        }
6256
6257        hanging.extend(trailing_space.take());
6258        // 行末の空白はぶら下げ: 幅に数えない(下の text-align の行幅からも外れる)。
6259        for (i, trim_w) in hanging {
6260            if let Some(c) = self.children.get_mut(i) {
6261                c.dimensions.content.width = c.dimensions.content.width.saturating_sub(trim_w);
6262            }
6263        }
6264        if line_x > 0 || has_line_box {
6265            lines.push((line_start, self.children.len()));
6266            y_cursor += if line_h > 0 { line_h } else { strut_h };
6267        }
6268        // float は通常のフロー高さに寄与しないため、コンテナが「潰れて」floatだけが
6269        // はみ出す見た目を避けるべく、底辺を高さに含める(簡易実装の割り切り)。
6270        if let Some((_, yb)) = left_float {
6271            y_cursor = y_cursor.max(yb);
6272        }
6273        if let Some((_, yb)) = right_float {
6274            y_cursor = y_cursor.max(yb);
6275        }
6276
6277        // 【2026-08-31】CSS 多段組(`column-count`/`column-width`/`columns`)。
6278        //
6279        // 縦フローで子を積み終えたこの時点で、**各子を列へ振り分け直す**
6280        // 後処理として実装する。先に通常フローを完成させてから x/y を
6281        // 移し替えるので、幅計算・マージン相殺・float 等の既存経路を
6282        // 一切変更せずに済む(新しいレイアウトモードを足すより安全)。
6283        //
6284        // 割り切り: 段抜き(`column-span`)・段区切り(`break-inside`)・
6285        // 段罫線(`column-rule`)は未対応。子は「積んだ順に、各列の高さが
6286        // 均等になるよう」振り分ける(厳密なバランシングではなく、
6287        // 各列の現在高さが最小の列へ順に入れる貪欲法)。
6288        if let BoxType::BlockNode(node) = &self.box_type {
6289            let cc = node.value_ref("column-count");
6290            let cw = node.value_ref("column-width");
6291            let shorthand = node.value_ref("columns");
6292            let (sh_w, sh_c) = shorthand
6293                .map(crate::os_lib::layout::multicol::parse_columns_shorthand)
6294                .unwrap_or((None, None));
6295            let parse_px = |v: Option<&str>| -> Option<i32> {
6296                v.and_then(|s| s.trim().strip_suffix("px"))
6297                    .and_then(|n| n.trim().parse::<f32>().ok())
6298                    .filter(|f| f.is_finite() && *f > 0.0)
6299                    .map(|f| f as i32)
6300            };
6301            let count = cc
6302                .and_then(|s| s.trim().parse::<i32>().ok())
6303                .filter(|v| *v > 0)
6304                .or(sh_c);
6305            let width = parse_px(cw).or(sh_w);
6306            if count.is_some() || width.is_some() {
6307                // `column-gap`(または `gap`)の単位解決(em, rem, pt, %, px)。
6308                let gap_str = node.value_ref("column-gap").or_else(|| node.value_ref("gap"));
6309                let gap = crate::os_lib::layout::multicol::resolve_column_gap(
6310                    gap_str,
6311                    self.dimensions.content.width.max(0),
6312                    self.font_size(),
6313                );
6314                let spec = crate::os_lib::layout::multicol::MultiColSpec { count, width, gap };
6315                let cols = crate::os_lib::layout::multicol::layout_columns(
6316                    &spec,
6317                    self.dimensions.content.width.max(0),
6318                );
6319                if cols.len() > 1 {
6320                    let base_x = self.dimensions.content.x;
6321                    let base_y = self.dimensions.content.y;
6322                    // float や絶対配置は通常フローから外れているので対象外。
6323                    let flow_idx: alloc::vec::Vec<usize> = self
6324                        .children
6325                        .iter()
6326                        .enumerate()
6327                        .filter(|(_, c)| box_float(c) == "none")
6328                        .map(|(i, _)| i)
6329                        .collect();
6330
6331                    // 段抜き(column-span: all)と通常の子を分類
6332                    let items: alloc::vec::Vec<crate::os_lib::layout::multicol::ChildKind> = flow_idx
6333                        .iter()
6334                        .map(|&i| {
6335                            let child = &self.children[i];
6336                            let h = child.dimensions.margin_box().height;
6337                            let is_spanner = match &child.box_type {
6338                                BoxType::BlockNode(n) => {
6339                                    n.value_ref("column-span").map(str::trim) == Some("all")
6340                                }
6341                                _ => false,
6342                            };
6343                            if is_spanner {
6344                                crate::os_lib::layout::multicol::ChildKind::Spanner { height: h }
6345                            } else {
6346                                crate::os_lib::layout::multicol::ChildKind::ColumnItem { height: h }
6347                            }
6348                        })
6349                        .collect();
6350
6351                    let (places, total_h) =
6352                        crate::os_lib::layout::multicol::assign_children_with_spans(&items, cols.len());
6353
6354                    for (slot, &ci) in flow_idx.iter().enumerate() {
6355                        let place = places[slot];
6356                        let child = &mut self.children[ci];
6357                        let target_w = if place.is_span {
6358                            self.dimensions.content.width.max(0)
6359                        } else {
6360                            cols[place.col].width
6361                        };
6362                        let target_x = if place.is_span {
6363                            0
6364                        } else {
6365                            cols[place.col].x
6366                        };
6367
6368                        let dx = base_x + target_x - child.dimensions.content.x
6369                            + child.dimensions.margin.left
6370                            + child.dimensions.border.left
6371                            + child.dimensions.padding.left;
6372                        let dy = base_y + place.y - child.dimensions.content.y
6373                            + child.dimensions.margin.top
6374                            + child.dimensions.border.top
6375                            + child.dimensions.padding.top;
6376                        child.translate(dx, dy);
6377                        child.dimensions.content.width = (target_w
6378                            - child.dimensions.margin.left
6379                            - child.dimensions.margin.right
6380                            - child.dimensions.border.left
6381                            - child.dimensions.border.right
6382                            - child.dimensions.padding.left
6383                            - child.dimensions.padding.right)
6384                            .max(0);
6385                    }
6386                    y_cursor = total_h;
6387                }
6388            }
6389        }
6390
6391
6392        // Block要素の高さは内容フローの高さ。ただし明示 height / min-height があれば優先。
6393        // `::before`/`::after` だけを内容に持つ要素は、その 1 行ぶんの高さを持つ。
6394        if let BoxType::BlockNode(n) = &self.box_type {
6395            if let Some((_, h)) = pseudo_content_size(n) {
6396                y_cursor = y_cursor.max(h);
6397            }
6398        }
6399        self.dimensions.content.height = y_cursor;
6400        let cb_height = containing_block.content.height.max(0);
6401        // 【2026-10-03】`%` 高さは包含ブロックの高さが確定しているとき(`PCT_BASE_H`)だけ有効で、
6402        // 未確定なら auto(CSS 2.1 10.5)。従来は `containing_block.content.height`(実体は
6403        // 縦のフロー位置)を基準にしていた。
6404        // `height: stretch`: 包含ブロックの高さが確定しているとき、margin box がそれを満たす(border-box の高さ)。
6405        // 未確定なら auto。
6406        let stretch_h = is_stretch_kw(height_val.as_deref());
6407        let stretch_h_total = (pct_base_h >= 0).then(|| (pct_base_h - self.dimensions.margin.top - self.dimensions.margin.bottom).max(0));
6408        let height_len = match parsed_height.clone() {
6409            _ if stretch_h => stretch_h_total,
6410            Some(LengthValue::Percent(pct)) if pct_base_h >= 0 => {
6411                Some(round_f32_to_i32(pct_base_h as f32 * pct))
6412            }
6413            Some(LengthValue::Percent(_)) => None,
6414            v => v.and_then(|v| resolve_length_value(v, cb_height)),
6415        };
6416        // svg(置換要素)の auto 高さは自然な縦横比と幅から(`svg_natural_ratio`)。
6417        let height_len = match (height_len, &self.box_type) {
6418            (None, BoxType::BlockNode(node)) if aspect_ratio_val.is_none() => svg_natural_ratio(node)
6419                .map(|(w, h)| round_f32_to_i32(self.dimensions.content.width as f32 * h / w))
6420                .filter(|_| box_sizing.trim() != "border-box"),
6421            (h, _) => h,
6422        };
6423        if let Some(h) = height_len
6424        {
6425            // box-sizing:border-box は指定 height から縦 padding+border を引いて content 高に。
6426            let vertical_non_content = self.dimensions.border.top
6427                + self.dimensions.border.bottom
6428                + self.dimensions.padding.top
6429                + self.dimensions.padding.bottom;
6430            let content_h = if box_sizing.trim() == "border-box" || stretch_h {
6431                (h - vertical_non_content).max(0)
6432            } else {
6433                h.max(0)
6434            };
6435            self.dimensions.content.height = content_h;
6436        }
6437        // 【2026-10-04】ブロックの `max-height` は読まれておらず、未実装だった
6438        // (`height:100px; max-height:20px` が 100px のまま)。CSS 2.1 §10.7 の順で
6439        // 上限を掛けてから `min-height` を適用する(両者が衝突したら min が勝つ)。
6440        // `box-sizing:border-box` なら `height` と同じく縦の padding+border を引く。
6441        let max_stretch = is_stretch_kw(max_height_val.as_deref());
6442        if let Some(mx) = if max_stretch {
6443            stretch_h_total
6444        } else {
6445            parse_length_value(max_height_val.as_deref()).and_then(|v| match v {
6446                LengthValue::Percent(pct) => (pct_base_h >= 0).then(|| round_f32_to_i32(pct_base_h as f32 * pct)),
6447                v => resolve_length_value(v, cb_height),
6448            })
6449        } {
6450            let vertical_non_content = self.dimensions.border.top
6451                + self.dimensions.border.bottom
6452                + self.dimensions.padding.top
6453                + self.dimensions.padding.bottom;
6454            let max_content = if box_sizing.trim() == "border-box" || max_stretch {
6455                (mx - vertical_non_content).max(0)
6456            } else {
6457                mx.max(0)
6458            };
6459            self.dimensions.content.height = self.dimensions.content.height.min(max_content);
6460        }
6461        let min_stretch = is_stretch_kw(min_height_val.as_deref());
6462        if let Some(mh) = if min_stretch {
6463            stretch_h_total
6464        } else {
6465            parse_length_value(min_height_val.as_deref()).and_then(|v| match v {
6466                LengthValue::Percent(pct) => (pct_base_h >= 0).then(|| round_f32_to_i32(pct_base_h as f32 * pct)),
6467                v => resolve_length_value(v, cb_height),
6468            })
6469        } {
6470            let vertical_non_content = self.dimensions.border.top
6471                + self.dimensions.border.bottom
6472                + self.dimensions.padding.top
6473                + self.dimensions.padding.bottom;
6474            let min_content = if box_sizing.trim() == "border-box" || min_stretch {
6475                (mh - vertical_non_content).max(0)
6476            } else {
6477                mh.max(0)
6478            };
6479            self.dimensions.content.height = self.dimensions.content.height.max(min_content);
6480        }
6481
6482        // aspect-ratio: W/H。height が auto なら width から height を補完、
6483        // 逆に width が auto かつ height 明示なら height から width を補完する。
6484        if let Some((num, den)) = aspect_ratio_val.and_then(parse_aspect_ratio).map(world_swap_ratio) {
6485            let width_is_auto = !explicit_width;
6486            let height_is_auto = parsed_height.is_none();
6487            if height_is_auto {
6488                // width 確定 → height = width * den / num
6489                self.dimensions.content.height =
6490                    round_f32_to_i32(self.dimensions.content.width as f32 * den / num).max(1);
6491            } else if width_is_auto {
6492                // height 明示・width auto → width = height * num / den(min/max-width で後段クランプ済みだが
6493                // ここで上書きするため、再度 min/max-width 制約を適用する)。
6494                let h = self.dimensions.content.height as f32;
6495                let mut w = round_f32_to_i32(h * num / den).max(1);
6496                if let Some(min_w) = parse_length_value(min_width_val.as_deref())
6497                    .and_then(|v| resolve_length_value(v, available_width))
6498                {
6499                    w = w.max(min_w);
6500                }
6501                if let Some(max_w) = parse_length_value(max_width_val.as_deref())
6502                    .and_then(|v| resolve_length_value(v, available_width))
6503                {
6504                    w = w.min(max_w);
6505                }
6506                self.dimensions.content.width = w.max(1);
6507            }
6508        }
6509
6510        // text-align の後処理: center / right でインライン子要素のx座標を調整
6511        // text-align 未指定時は `direction` に応じた既定値(初期値 `start` の簡易解決)を使う:
6512        // rtl なら right 相当、それ以外(既定 ltr)は従来どおり left(無指定=無調整)。
6513        let (text_align, direction, text_align_last) = match &self.box_type {
6514            BoxType::BlockNode(node) | BoxType::TableCellNode(node) => (
6515                node.value_ref("text-align").unwrap_or(""),
6516                node.value_ref("direction").unwrap_or(""),
6517                node.value_ref("text-align-last").unwrap_or(""),
6518            ),
6519            _ => ("", "", ""),
6520        };
6521        let is_rtl = direction.trim().eq_ignore_ascii_case("rtl");
6522        let resolve_ta_kw = |s: &str, rtl: bool, allow_justify: bool| -> &'static str {
6523            let t = s.trim();
6524            if t.eq_ignore_ascii_case("center") {
6525                "center"
6526            } else if t.eq_ignore_ascii_case("right") {
6527                "right"
6528            } else if t.eq_ignore_ascii_case("left") {
6529                "left"
6530            } else if allow_justify && t.eq_ignore_ascii_case("justify") {
6531                "justify"
6532            } else if t.eq_ignore_ascii_case("start") {
6533                if rtl { "right" } else { "left" }
6534            } else if t.eq_ignore_ascii_case("end") {
6535                if rtl { "left" } else { "right" }
6536            } else {
6537                ""
6538            }
6539        };
6540        let mut ta = resolve_ta_kw(text_align, is_rtl, true);
6541        if ta.is_empty() && is_rtl {
6542            ta = "right";
6543        }
6544        // text-align-last: 最終行のみ text-align とは別の値で揃える(justify と組み合わせて
6545        // 最終行だけ left/center/right にする用途向け)。`auto`/未指定/`justify`(非対応)は
6546        // 最終行も通常の `ta` に従う。`start`/`end` も同様に direction で解決する。
6547        let ta_last_resolved = resolve_ta_kw(text_align_last, is_rtl, false);
6548        let ta_last_effective = if !ta_last_resolved.is_empty() {
6549            Some(ta_last_resolved)
6550        } else {
6551            None
6552        };
6553        if ta == "center" || ta == "right" || ta == "justify" || ta_last_effective.is_some() {
6554            let content_w = self.dimensions.content.width.max(1);
6555            let last_line_idx = lines.len().saturating_sub(1);
6556
6557            for (line_idx, &(s, e)) in lines.iter().enumerate() {
6558                // そのラインの子要素インデックスと合計幅を計算
6559                let mut line_indices = Vec::new();
6560                let mut total_w = 0i32;
6561                for ci in s..e {
6562                    match self.children[ci].box_type {
6563                        BoxType::InlineNode(_) | BoxType::InlineBlockNode(_) => {
6564                            line_indices.push(ci);
6565                            let (el, er, _, _) = self.children[ci].inline_block_edges();
6566                            total_w += el + self.children[ci].dimensions.content.width + er;
6567                        }
6568                        _ => {}
6569                    }
6570                }
6571                if line_indices.is_empty() {
6572                    continue;
6573                }
6574
6575                let is_last_line = line_idx == last_line_idx;
6576                let effective_ta = if is_last_line {
6577                    ta_last_effective.unwrap_or(if ta == "justify" {
6578                        if is_rtl { "right" } else { "left" }
6579                    } else {
6580                        ta
6581                    })
6582                } else {
6583                    ta
6584                };
6585
6586                if effective_ta == "justify" {
6587                    let k = line_indices.len();
6588                    if k > 1 {
6589                        let remaining = (content_w - total_w).max(0);
6590                        for (i, &ci) in line_indices.iter().enumerate() {
6591                            let shift = (remaining * i as i32) / (k as i32 - 1);
6592                            self.children[ci].translate(shift, 0);
6593                        }
6594                    }
6595                } else {
6596                    let offset = match effective_ta {
6597                        "center" => ((content_w - total_w) / 2).max(0),
6598                        "right" => (content_w - total_w).max(0),
6599                        _ => 0,
6600                    };
6601                    if offset > 0 {
6602                        for &ci in &line_indices {
6603                            self.children[ci].translate(offset, 0);
6604                        }
6605                    }
6606                }
6607            }
6608        }
6609
6610        // 行内のベースライン揃え。行内の箱をベースラインに合わせて垂直方向に配置し、
6611        // もし行の高さが広がった場合は後続の子要素(後続の行やブロック要素)を押し下げ、
6612        // コンテナ高さも拡張する。
6613        let mut total_delta_h = 0i32;
6614        for &(s, e) in &lines {
6615            let orig_h = self.children[s..e]
6616                .iter()
6617                .filter(|c| {
6618                    !c.is_whitespace_text()
6619                        && matches!(c.box_type, BoxType::InlineNode(_) | BoxType::InlineBlockNode(_))
6620                        && box_float(c) == "none"
6621                        && !matches!(box_position(c), "absolute" | "fixed")
6622                })
6623                .map(|c| {
6624                    let (_, _, et, eb) = c.inline_block_edges();
6625                    et + c.dimensions.content.height + eb
6626                })
6627                .max()
6628                .unwrap_or(0);
6629
6630            let new_h = Self::align_line_baselines(&mut self.children, s, e);
6631            if new_h > orig_h {
6632                let delta = new_h - orig_h;
6633                total_delta_h += delta;
6634                for ci in e..self.children.len() {
6635                    self.children[ci].translate_y(delta);
6636                }
6637            }
6638        }
6639        if total_delta_h > 0 {
6640            self.dimensions.content.height += total_delta_h;
6641        }
6642        if forced_h >= 0 {
6643            self.dimensions.content.height = forced_h;
6644        }
6645
6646        // position の後処理(relative/absolute/fixed の配置 + transform)を共有メソッドで適用。
6647        // 直接の子の包含ブロックは、高さが確定した今のパディングボックス。
6648        if saved_abs_cb.is_some() || saved_fixed_cb.is_some() {
6649            let pb = self.dimensions.padding_box();
6650            if saved_abs_cb.is_some() {
6651                abs_cb_set(pb.x, pb.y, pb.width, pb.height);
6652            }
6653            if saved_fixed_cb.is_some() {
6654                fixed_cb_set(Some((pb.x, pb.y, pb.width, pb.height)));
6655            }
6656        }
6657        self.apply_positioned_offsets_with(None, true);
6658
6659        // 子孫のために切替えた ABS_CB / FIXED_CB を復元。
6660        if let Some(prev) = saved_abs_cb {
6661            abs_cb_set(prev.0, prev.1, prev.2, prev.3);
6662        }
6663        if let Some(prev) = saved_fixed_cb {
6664            fixed_cb_set(prev);
6665        }
6666    }
6667
6668    /// avail_hint: 包含ブロックのコンテンツ幅。テキスト折り返し計測に使う。
6669    /// (以前は固定 800px フォールバックだったため、実コンテナ幅と食い違い
6670    ///   layout の行数 < flatten の行数 となって後続要素と重なるバグがあった)
6671    /// 内容ベースの寸法を返す。`avail_hint` は折り返しに使える幅。
6672    ///
6673    /// `pure` が真なら**現在の箱の幅を見ない**。内在幅
6674    /// (min-content / max-content)の算出専用の入口で、
6675    /// `block_intrinsic_widths` だけが真を渡す。
6676    ///
6677    /// 内在幅は「今どう組まれているか」に依存してはいけない値だが、
6678    /// この関数は内在幅以外の用途(表の列幅・インライン配置など)でも
6679    /// 呼ばれており、そちらは現在の幅を前提にしている。
6680    /// 【2026-09-05】一度この区別をせずに順序だけ入れ替えたところ、
6681    /// ヒーローの見出しが 2 行に折り返す退行を招いて戻した。
6682    /// 入口を分けることで、内在幅の算出だけを正す。
6683    fn intrinsic_inline_size_ext(&self, avail_hint: i32, pure: bool) -> (i32, i32) {
6684        let styled_node = match &self.box_type {
6685            BoxType::InlineNode(node) | BoxType::InlineBlockNode(node) => Some(*node),
6686            _ => None,
6687        };
6688        let styled_node = if crate::os_lib::css::CUR_WORLD.load(AtomicOrdering::Relaxed) != 0 { None } else { styled_node };
6689        if let Some(node) = styled_node {
6690            if let Ok(cache) = node.intrinsic_size_cache.try_borrow() {
6691                if let Some((ch_avail, ch_pure, ch_trim, w, h)) = *cache {
6692                    if ch_avail == avail_hint && ch_pure == pure && ch_trim == self.trim_leading_space {
6693                        return (w, h);
6694                    }
6695                }
6696            }
6697        }
6698        let res = self.intrinsic_inline_size_ext_uncached(avail_hint, pure);
6699        if let Some(node) = styled_node {
6700            if let Ok(mut cache) = node.intrinsic_size_cache.try_borrow_mut() {
6701                *cache = Some((avail_hint, pure, self.trim_leading_space, res.0, res.1));
6702            }
6703        }
6704        res
6705    }
6706
6707    fn intrinsic_inline_size_ext_uncached(&self, avail_hint: i32, pure: bool) -> (i32, i32) {
6708        // inline-flex / inline-grid: 幅は内在幅(shrink-to-fit)、高さは試し組みで測る。
6709        if self.is_inline_flex() || self.is_inline_grid() {
6710            if pure {
6711                let (minc, maxc) = self.block_intrinsic_widths();
6712                return (if avail_hint <= 1 { minc } else { maxc }, 0);
6713            }
6714            let w = self.inline_flex_content_width(avail_hint);
6715            let mut probe = self.clone();
6716            probe.layout_as_flex_at(0, 0, w);
6717            return (w, probe.dimensions.content.height.max(0));
6718        }
6719        match &self.box_type {
6720            BoxType::InlineNode(node) | BoxType::InlineBlockNode(node) => {
6721                // `%` 幅は包含ブロック基準。純粋な内在幅の計測中(pure)は基準が
6722                // 無いので auto(自然サイズ)扱い(2026-09-26 まではビューポート基準)。
6723                // 【2026-10-04】ただし min-content の計測(`avail_hint <= 1`)では、
6724                // `%` の width/max-width を持つ置換要素は「縮められる」ので 0 基準で解く
6725                // (CSS Sizing 3 §5.2.2。`img{width:100%}` の min-content 寄与は 0)。
6726                // これが無いと、グリッドの fr 列の自動最小で画像の自然サイズが拾われ、
6727                // sugi-lab.net トップの写真の列が画面幅を超えて広がった。
6728                let base = if !pure {
6729                    Some(avail_hint)
6730                } else if avail_hint <= 1 {
6731                    Some(0)
6732                } else {
6733                    None
6734                };
6735                if let Some(size) = get_replaced_element_size_in(node, base) {
6736                    return size;
6737                }
6738                let font_size = node
6739                    .value_ref("font-size")
6740                    .and_then(parse_font_size_u32)
6741                    .unwrap_or(16);
6742                let line_height_val = node.value_ref("line-height");
6743                let line_height = parse_line_height(line_height_val, font_size);
6744
6745                // Check for explicit CSS width/height (e.g., inline-block with width: 200px)
6746                // `width: 50%`等の百分率が以前は完全に無視されており(`LengthValue::Px`
6747                // のみ対応)、`<iframe width="100%">`のようなレガシー属性経由の百分率
6748                // 指定(cascade.rsでCSS `width`へマッピング済み)が正しくサイズに
6749                // 反映されないバグだった。`avail_hint`(包含ブロックのコンテンツ幅)
6750                // 基準で解決する(2026-07-21発見・修正。実サイト www.sugi-lab.net の
6751                // Access ページの地図埋め込みで発覚)。
6752                // 文字ノードには width/height は当たらない(検索を省く。2026-10-19)。
6753                let is_text_node = matches!(node.node.node_type, NodeType::Text(_));
6754                let css_w = if is_text_node { None } else {
6755                    len_value(node, "width").and_then(|v| match parse_length_value(Some(v.as_ref())) {
6756                        Some(LengthValue::Px(px)) => Some(px),
6757                        Some(LengthValue::Percent(pct)) => {
6758                            Some(round_f32_to_i32(avail_hint as f32 * pct))
6759                        }
6760                        _ => None,
6761                    })
6762                };
6763                let css_h = if is_text_node { None } else {
6764                    node.value_ref("height").and_then(|v| match parse_length_value(Some(v)) {
6765                        Some(LengthValue::Px(px)) => Some(px),
6766                        _ => None,
6767                    })
6768                };
6769
6770                match &node.node.node_type {
6771                    NodeType::Text(text) => {
6772                        // white-space: nowrap/pre は折り返さない(1行に収める)。
6773                        // white-space は継承プロパティなのでテキストノード自身の
6774                        // styled node にも祖先から伝播済みの値が入っている。
6775                        let nowrap = matches!(node.value_ref("text-overflow"), Some("ellipsis")) || matches!(
6776                            node.value_ref("white-space"),
6777                            Some("nowrap") | Some("pre")
6778                        );
6779                        let pre_wrap = matches!(
6780                            node.value_ref("white-space"),
6781                            Some("pre-wrap") | Some("pre-line")
6782                        );
6783                        let break_all = matches!(
6784                            node.value_ref("word-break"),
6785                            Some("break-all")
6786                        );
6787                        let overflow_wrap = matches!(
6788                            node.value_ref("overflow-wrap"),
6789                            Some("break-word") | Some("anywhere")
6790                        ) || matches!(
6791                            node.value_ref("word-wrap"),
6792                            Some("break-word") | Some("anywhere")
6793                        ) || matches!(
6794                            node.value_ref("word-break"),
6795                            Some("break-word")
6796                        );
6797                        // 【2026-09-05】`avail_hint` を優先する形へ変えたが、
6798                        // ヒーローの見出しが 2 行に折り返す退行を招いたため戻した。
6799                        //
6800                        // 内在幅は本来「今どう組まれているか」に依存しない値で、
6801                        // 現在の箱の幅を先に見るのは正しくない(min を求めても
6802                        // max を求めても同じ値が返る)。ただしこの関数は
6803                        // 内在幅の算出以外からも呼ばれており、そちらは
6804                        // 現在の幅を前提にしている。直すなら**呼び出し側を
6805                        // 全部見てから**にすること。詳細は `spec/flex_min_size.md`。
6806                        let available = if nowrap {
6807                            i32::MAX / 2
6808                        } else {
6809                            css_w.unwrap_or({
6810                                if pure {
6811                                    // 内在幅の算出。今の箱の幅は見ない。
6812                                    if avail_hint > 0 {
6813                                        avail_hint
6814                                    } else {
6815                                        800
6816                                    }
6817                                } else if self.dimensions.content.width > 0 {
6818                                    // 【2026-09-26 バグ修正】前回組んだ幅が今回の利用可能幅より
6819                                    // 広ければ今回の幅で折り返す。flex の縮小などで組み直すと、
6820                                    // 文字だけが縮小前の広い幅のまま折り返し、箱の外へはみ出して
6821                                    // いた(profile.htm の研究概要)。狭い側は従来どおり前回の幅
6822                                    // (全面的に今回の幅へ切り替えるとヒーロー見出しが退行した。
6823                                    // 2026-09-05 の記録)。
6824                                    if avail_hint > 0 {
6825                                        self.dimensions.content.width.min(avail_hint)
6826                                    } else {
6827                                        self.dimensions.content.width
6828                                    }
6829                                } else if avail_hint > 0 {
6830                                    avail_hint
6831                                } else {
6832                                    800
6833                                }
6834                            })
6835                        };
6836                        let ls = parse_letter_spacing_with_font(node.value_ref("letter-spacing"), available, font_size as f32);
6837                        let ws = parse_word_spacing_with_font(node.value_ref("word-spacing"), available, font_size as f32);
6838                        // 描画側と同じ規則で空白を畳んでから測る(2026-09-26。
6839                        // 畳まずに測ると HTML の字下げの分だけ箱が広く・高くなる)。
6840                        let text = &crate::os_lib::layout::line_break::collapse_white_space(
6841                            text,
6842                            node.value_ref("white-space").unwrap_or(""),
6843                        );
6844                        let text = if self.trim_leading_space {
6845                            text.strip_prefix(' ').unwrap_or(text)
6846                        } else {
6847                            text.as_str()
6848                        };
6849                        // 描画と同じ書体(font-family・太字)で折り返し行数を測る(2026-09-26)。
6850                        let (fam, weight) = text_font_of(node);
6851                        let (w, h) = crate::kernel::vector_font::get_vector_string_wrapped_size_family(
6852                            text,
6853                            font_size,
6854                            available as u32,
6855                            ls,
6856                            ws,
6857                            break_all,
6858                            overflow_wrap,
6859                            pre_wrap,
6860                            fam,
6861                            weight,
6862                        );
6863                        let lines = h as i32 / (font_size as i32 + 4).max(1);
6864                        (
6865                            css_w.unwrap_or(w as i32),
6866                            css_h.unwrap_or(lines * line_height),
6867                        )
6868                    }
6869                    NodeType::Element { tag_name, .. } => {
6870                        if tag_name == "br" {
6871                            (0, line_height)
6872                        } else {
6873                            // 【2026-10-04】中身が空の要素(疑似要素の中身も無い)は幅 0。
6874                            // 以前は一律 8px を与えていた。papers.htm の目次リンクで、
6875                            // FA 6 に存在しないアイコン `fa-presentation`(Chrome では幅 0)が
6876                            // 8px を取り、文字が他のリンクより右へずれていた。
6877                            // 空の錨 `<a name="..."></a>` も同じく余計な隙間を作っていた。
6878                            // 疑似要素で描くアイコンはこの分岐に来ない(`pseudo_content_size`)。
6879                            let (content_w, content_h) = if self.children.is_empty() {
6880                                (0, line_height)
6881                            } else {
6882                                let mut total_w = 0i32;
6883                                let mut max_h = line_height;
6884                                // inline-block の中身は、利用可能幅から自分の左右の余白を引いた幅で
6885                                // 組む(shrink-to-fit。2026-09-26。引かないと中の文字が折り返さず、
6886                                // forms.htm の長いボタンがカードの右へはみ出した)。
6887                                let avail_hint = if matches!(self.box_type, BoxType::InlineBlockNode(_))
6888                                    && avail_hint > 0
6889                                    && avail_hint < 1_000_000
6890                                {
6891                                    (avail_hint - intrinsic_h_edges(self, css_w.is_some())).max(1)
6892                                } else {
6893                                    avail_hint
6894                                };
6895                                // `layout_inline` の子の並べ方と同じく、畳まれた空白の幅を数える(2026-11-18)。
6896                                let mut after_space: Option<bool> = None;
6897                                for child in &self.children {
6898                                    // 【2026-09-05】ここは `pure` を**引き継がない**。
6899                                    //
6900                                    // 引き継ぐと入れ子の要素の内在幅が変わり、
6901                                    // ナビ項目の間隔が潰れる退行が出た
6902                                    // (実測。ロゴの重なりは解消しないまま
6903                                    // 悪化だけした)。理屈の上では引き継ぐのが
6904                                    // 正しいはずで、引き継いで壊れるということは
6905                                    // **どこかが非 pure の値に依存している**。
6906                                    // 直すならその依存を先に突き止めること。
6907                                    // 【2026-10-18】ただし文字ノード(葉)は pure を引き継ぐ。非 pure の文字の
6908                                    // 計測は今組まれている幅を基準にするため、一度狭く組まれたインライン要素の
6909                                    // max-content がその幅に縮んでいた(YouTube の「その他の動画」の span が
6910                                    // 1 文字幅になり、縦に 1 文字ずつ折り返した)。入れ子の要素は従来どおり。
6911                                    let child_is_text = matches!(
6912                                        &child.box_type,
6913                                        BoxType::InlineNode(n) if matches!(n.node.node_type, NodeType::Text(_))
6914                                    );
6915                                    // 【2026-11-30 TODO S2】フロー外(absolute / fixed)の子は内在寸法に入れない
6916                                    // (バッジ付きアイコンの inline-block が、バッジの幅だけ広がっていた)。
6917                                    if !child_is_text && Self::child_is_out_of_flow(child) {
6918                                        continue;
6919                                    }
6920                                    let child_is_block_level = matches!(
6921                                        child.box_type,
6922                                        BoxType::BlockNode(_) | BoxType::FlexNode(_) | BoxType::GridNode(_)
6923                                    );
6924                                    let (cw, ch) = if child_is_text {
6925                                        child.intrinsic_inline_size_ext(avail_hint, pure)
6926                                    } else if child_is_block_level {
6927                                        // 【2026-10-18】インラインの中のブロック級の箱(flex のボタン等)は、
6928                                        // ブロックとしての内在幅で測る(従来は (0,0) で、YouTube の操作部の
6929                                        // ボタンの並びが幅 0 と見積もられ、flex の余白を奪っていた)。
6930                                        let parsed_w = parse_length_value(box_style_value_ref(child, "width"));
6931                                        let explicit = matches!(parsed_w, Some(LengthValue::Px(_)));
6932                                        let (mn, mx) = match parsed_w {
6933                                            Some(LengthValue::Px(px)) => (px.max(0), px.max(0)),
6934                                            _ => child.block_intrinsic_widths(),
6935                                        };
6936                                        let w = if avail_hint <= 1 { mn } else { mx.min(avail_hint.max(0)) };
6937                                        (w + intrinsic_h_edges(child, explicit), child.dimensions.margin_box().height.max(0))
6938                                    } else {
6939                                        inline_child_outer_size(child, avail_hint)
6940                                    };
6941                                    let cw = if matches!(child.box_type, BoxType::InlineNode(_)) {
6942                                        let (w, _, ends_space) = child.inline_child_space_adjust(cw, after_space);
6943                                        if child.is_collapsible_space() || ends_space {
6944                                            after_space = Some(true);
6945                                        } else if !child.is_blank_inline() {
6946                                            after_space = Some(false);
6947                                        }
6948                                        w
6949                                    } else {
6950                                        if !child_is_block_level {
6951                                            after_space = Some(false);
6952                                        } else {
6953                                            after_space = Some(true);
6954                                        }
6955                                        cw
6956                                    };
6957                                    total_w += cw;
6958                                    if ch > max_h {
6959                                        max_h = ch;
6960                                    }
6961                                }
6962                                (total_w, max_h)
6963                            };
6964                            // border-box の明示サイズは content へ換算して返す(戻り値は常に content
6965                            // の大きさ。余白は呼び出し側が `inline_block_edges` 等で足す)。
6966                            let (bw, bh) = if matches!(self.box_type, BoxType::InlineBlockNode(_)) {
6967                                border_box_inner(node)
6968                            } else {
6969                                (0, 0)
6970                            };
6971                            (
6972                                css_w.map(|w| (w - bw).max(0)).unwrap_or(content_w),
6973                                css_h.map(|h| (h - bh).max(0)).unwrap_or(content_h),
6974                            )
6975                        }
6976                    }
6977                }
6978            }
6979            _ => (0, 0),
6980        }
6981    }
6982
6983    /// 従来どおりの入口(現在の箱の幅を見る)。
6984    fn intrinsic_inline_size(&self, avail_hint: i32) -> (i32, i32) {
6985        self.intrinsic_inline_size_ext(avail_hint, false)
6986    }
6987
6988    fn layout_inline(&mut self, containing_block: Dimensions, _block_like: bool) {
6989        self.apply_box_model_styles_with_base(containing_block.content.width);
6990        // 親が行に並べるために確定した中身の大きさ(呼び出し側は組む前に子の content に入れ、組んだ後もこの値を最終にする)。
6991        // 絶対配置の包含ブロック(パディング箱)はこの最終の大きさで決める(この関数の内在寸法の見積もりとは食い違うことがある)。
6992        let slot_size = (self.dimensions.content.width, self.dimensions.content.height);
6993
6994        let (width_val, min_width_val, max_width_val, height_val, min_height_val, max_height_val) =
6995            match &self.box_type {
6996                // 文字ノードには width/height 系は当たらず継承もしない(【2026-10-19】全文字ノードで
6997                // 6 個の値を検索していた。レイアウトの最頻出の経路)。
6998                BoxType::InlineNode(node) if matches!(node.node.node_type, NodeType::Text(_)) => {
6999                    (None, None, None, None, None, None)
7000                }
7001                BoxType::InlineNode(node) | BoxType::InlineBlockNode(node) => (
7002                    len_value(node, "width"),
7003                    len_value(node, "min-width"),
7004                    len_value(node, "max-width"),
7005                    len_value(node, "height"),
7006                    len_value(node, "min-height"),
7007                    len_value(node, "max-height"),
7008                ),
7009                _ => return,
7010            };
7011
7012        let available_width = containing_block.content.width.max(1);
7013        let available_height = containing_block.content.height.max(1);
7014
7015        // 【2026-11-29 バグ修正】inline-block に明示的な確定高さがある場合、
7016        // 内部計測(inline_content_intrinsic_size)および子要素配置の前に
7017        // `PCT_BASE_H` に確定高さを設定する(中の canvas/img 等の `height:%` が正しく解決されるように)。
7018        let early_definite_h = if matches!(self.box_type, BoxType::InlineBlockNode(_)) {
7019            match parse_length_value(height_val.as_deref()) {
7020                Some(LengthValue::Px(px)) => {
7021                    let border_box = box_style_value_ref(self, "box-sizing").is_some_and(|v| v.trim() == "border-box");
7022                    let v_edges = if border_box {
7023                        self.dimensions.padding.top + self.dimensions.padding.bottom + self.dimensions.border.top + self.dimensions.border.bottom
7024                    } else {
7025                        0
7026                    };
7027                    Some((px - v_edges).max(0))
7028                }
7029                Some(LengthValue::Percent(pct)) => {
7030                    let cur_pct = PCT_BASE_H.load(AtomicOrdering::Relaxed);
7031                    if cur_pct >= 0 {
7032                        Some(round_f32_to_i32(cur_pct as f32 * pct).max(0))
7033                    } else {
7034                        None
7035                    }
7036                }
7037                _ => None,
7038            }
7039        } else {
7040            None
7041        };
7042        let _inline_pct_guard = early_definite_h.map(PctBaseHGuard::set);
7043
7044        let (intrinsic_w, intrinsic_h) = self.inline_content_intrinsic_size(available_width);
7045
7046        let parsed_width = parse_length_value(width_val.as_deref());
7047        let width_is_explicit = matches!(
7048            parsed_width,
7049            Some(LengthValue::Px(_) | LengthValue::Percent(_) | LengthValue::MathExpr(_))
7050        );
7051        let mut content_width = match parsed_width {
7052            Some(LengthValue::Auto) | None => intrinsic_w.max(1),
7053            Some(LengthValue::Px(px)) => px.max(1),
7054            Some(LengthValue::Percent(pct)) => {
7055                round_f32_to_i32(available_width as f32 * pct).max(1)
7056            }
7057            Some(LengthValue::MinContent) => {
7058                let (minc, _maxc) = self.block_intrinsic_widths();
7059                minc.max(1)
7060            }
7061            Some(LengthValue::MaxContent) => {
7062                let (_minc, maxc) = self.block_intrinsic_widths();
7063                maxc.max(1)
7064            }
7065            Some(LengthValue::FitContent) => {
7066                let (minc, maxc) = self.block_intrinsic_widths();
7067                available_width.min(maxc).max(minc).max(1)
7068            }
7069            Some(LengthValue::FitContentWith(lim_box)) => {
7070                let limit = resolve_length_value_with_font(*lim_box, available_width, self.font_size())
7071                    .unwrap_or(available_width);
7072                let (minc, maxc) = self.block_intrinsic_widths();
7073                maxc.min(limit.max(minc)).max(1)
7074            }
7075            Some(LengthValue::MathExpr(expr)) => {
7076                crate::os_lib::css::eval_css_math_with_font(&expr, available_width, self.font_size())
7077                    .unwrap_or(intrinsic_w.max(1))
7078                    .max(1)
7079            }
7080        };
7081        // box-sizing: border-box → 明示の width/height/min/max は border-box 全体なので
7082        // padding+border を引いて content に換算する(layout_block と同じ)。
7083        // 【2026-10-25】従来は行内ブロックで無視され、YouTube のヘッダーのボタン
7084        // (`yt-icon-button{width:40px;height:40px;padding:8px;box-sizing:border-box}`)が
7085        // 中身 40×40(外形 56×56)になっていた。
7086        let border_box = box_style_value_ref(self, "box-sizing").is_some_and(|v| v.trim() == "border-box");
7087        let h_non_content = if border_box {
7088            self.dimensions.padding.left
7089                + self.dimensions.padding.right
7090                + self.dimensions.border.left
7091                + self.dimensions.border.right
7092        } else {
7093            0
7094        };
7095        let v_non_content = if border_box {
7096            self.dimensions.padding.top
7097                + self.dimensions.padding.bottom
7098                + self.dimensions.border.top
7099                + self.dimensions.border.bottom
7100        } else {
7101            0
7102        };
7103        let parsed_height = parse_length_value(height_val.as_deref());
7104        let height_is_explicit = matches!(
7105            parsed_height,
7106            Some(LengthValue::Px(_) | LengthValue::MathExpr(_))
7107        ) || (matches!(parsed_height, Some(LengthValue::Percent(_)))
7108            && PCT_BASE_H.load(AtomicOrdering::Relaxed) >= 0);
7109        if width_is_explicit {
7110            content_width = (content_width - h_non_content).max(1);
7111        }
7112        if let Some(min_width) = parse_length_value(min_width_val.as_deref())
7113            .and_then(|v| resolve_length_value_with_font(v, available_width, self.font_size()))
7114        {
7115            content_width = content_width.max(min_width - h_non_content);
7116        }
7117        if let Some(max_width) = parse_length_value(max_width_val.as_deref())
7118            .and_then(|v| resolve_length_value_with_font(v, available_width, self.font_size()))
7119        {
7120            content_width = content_width.min(max_width - h_non_content);
7121        }
7122
7123        let mut content_height = match parsed_height {
7124            Some(LengthValue::Auto)
7125            | Some(LengthValue::MinContent)
7126            | Some(LengthValue::MaxContent)
7127            | Some(LengthValue::FitContent)
7128            | Some(LengthValue::FitContentWith(_))
7129            | None => intrinsic_h.max(1),
7130            Some(LengthValue::Px(px)) => px.max(1),
7131            // 【2026-09-26 バグ修正】`%` 高さは包含ブロックの高さが確定しているときだけ
7132            // 有効(仕様では未確定なら auto)。ここの `containing_block.content.height` は
7133            // 呼び出し側の縦カーソル位置(flex の計測では 0)で高さではないため、
7134            // `img{max-height:100%}` が 1px に潰れていた。auto として扱う。
7135            // 【2026-10-03】包含ブロックの高さが確定していれば(`PCT_BASE_H`)それ基準。
7136            Some(LengthValue::Percent(pct)) => match PCT_BASE_H.load(AtomicOrdering::Relaxed) {
7137                b if b >= 0 => round_f32_to_i32(b as f32 * pct).max(1),
7138                _ => intrinsic_h.max(1),
7139            },
7140            Some(LengthValue::MathExpr(expr)) => {
7141                crate::os_lib::css::eval_css_math_with_font(&expr, available_height, self.font_size())
7142                    .unwrap_or(intrinsic_h.max(1))
7143                    .max(1)
7144            }
7145        };
7146        if height_is_explicit {
7147            content_height = (content_height - v_non_content).max(1);
7148        }
7149        let pct_h_cur = PCT_BASE_H.load(AtomicOrdering::Relaxed);
7150        let resolve_inline_v = |val: Option<&str>| -> Option<i32> {
7151            match parse_length_value(val) {
7152                Some(LengthValue::Percent(pct)) => {
7153                    if pct_h_cur >= 0 {
7154                        Some(round_f32_to_i32(pct_h_cur as f32 * pct))
7155                    } else {
7156                        None
7157                    }
7158                }
7159                Some(other) => resolve_length_value_with_font(other, available_height, self.font_size()),
7160                None => None,
7161            }
7162        };
7163        if let Some(min_height) = resolve_inline_v(min_height_val.as_deref()) {
7164            content_height = content_height.max(min_height - v_non_content);
7165        }
7166        if let Some(max_height) = resolve_inline_v(max_height_val.as_deref()) {
7167            content_height = content_height.min(max_height - v_non_content);
7168        }
7169        if let Some((num, den)) = box_intrinsic_ratio(self) {
7170            if num > 0.0 && den > 0.0 {
7171                if height_is_explicit && !width_is_explicit {
7172                    let mut w = round_f32_to_i32(content_height as f32 * num / den).max(1);
7173                    if let Some(min_w) = parse_length_value(min_width_val.as_deref())
7174                        .and_then(|v| resolve_length_value_with_font(v, available_width, self.font_size()))
7175                    {
7176                        w = w.max(min_w - h_non_content);
7177                    }
7178                    if let Some(max_w) = parse_length_value(max_width_val.as_deref())
7179                        .and_then(|v| resolve_length_value_with_font(v, available_width, self.font_size()))
7180                    {
7181                        w = w.min(max_w - h_non_content);
7182                    }
7183                    content_width = w;
7184                } else if width_is_explicit && !height_is_explicit {
7185                    let mut h = round_f32_to_i32(content_width as f32 * den / num).max(1);
7186                    if let Some(min_h) = resolve_inline_v(min_height_val.as_deref()) {
7187                        h = h.max(min_h - v_non_content);
7188                    }
7189                    if let Some(max_h) = resolve_inline_v(max_height_val.as_deref()) {
7190                        h = h.min(max_h - v_non_content);
7191                    }
7192                    content_height = h;
7193                } else if !width_is_explicit && !height_is_explicit {
7194                    let w_clamped = content_width != intrinsic_w.max(1);
7195                    let h_clamped = content_height != intrinsic_h.max(1);
7196                    if w_clamped && !h_clamped {
7197                        let mut h = round_f32_to_i32(content_width as f32 * den / num).max(1);
7198                        if let Some(min_h) = resolve_inline_v(min_height_val.as_deref()) {
7199                            h = h.max(min_h - v_non_content);
7200                        }
7201                        if let Some(max_h) = resolve_inline_v(max_height_val.as_deref()) {
7202                            h = h.min(max_h - v_non_content);
7203                        }
7204                        content_height = h;
7205                    } else if h_clamped && !w_clamped {
7206                        let mut w = round_f32_to_i32(content_height as f32 * num / den).max(1);
7207                        if let Some(min_w) = parse_length_value(min_width_val.as_deref())
7208                            .and_then(|v| resolve_length_value_with_font(v, available_width, self.font_size()))
7209                        {
7210                            w = w.max(min_w - h_non_content);
7211                        }
7212                        if let Some(max_w) = parse_length_value(max_width_val.as_deref())
7213                            .and_then(|v| resolve_length_value_with_font(v, available_width, self.font_size()))
7214                        {
7215                            w = w.min(max_w - h_non_content);
7216                        }
7217                        content_width = w;
7218                    }
7219                }
7220            }
7221        }
7222
7223        self.dimensions.content.width = content_width.max(1);
7224        self.dimensions.content.height = content_height.max(1);
7225        self.dimensions.content.x = containing_block.content.x
7226            + self.dimensions.margin.left
7227            + self.dimensions.border.left
7228            + self.dimensions.padding.left;
7229        self.dimensions.content.y = containing_block.content.y
7230            + containing_block.content.height
7231            + self.dimensions.margin.top
7232            + self.dimensions.border.top
7233            + self.dimensions.padding.top;
7234
7235        // 【2026-11-29 バグ修正】inline-block の確定高さ(height_is_explicit)がある場合、
7236        // 子要素(置換要素等の `height:%`)の解決基準として `PCT_BASE_H` に設定する。
7237        // auto の場合は未確定(-1)。通常の InlineNode は親の `PCT_BASE_H` を維持する。
7238        let inline_definite_h = if matches!(self.box_type, BoxType::InlineBlockNode(_)) {
7239            if height_is_explicit {
7240                content_height
7241            } else {
7242                -1
7243            }
7244        } else {
7245            PCT_BASE_H.load(AtomicOrdering::Relaxed)
7246        };
7247        let _pct_h_guard = PctBaseHGuard::set(inline_definite_h);
7248
7249        // 子要素のレイアウト計算を行う。インライン要素(!block_like)であっても、
7250        // 内包するテキストや子インライン要素の座標を設定する必要があるため、常に実行します。
7251        let mut child_flow_x = 0i32;
7252        let mut child_flow_y = 0i32;
7253        let mut line_h = 0i32;
7254        let max_w = self.dimensions.content.width.max(1);
7255        // インライン/インラインブロックの vertical-align(既定 top/baseline は無調整): 1行の
7256        // 全子要素が揃って初めて行の高さ(line_h)が確定するため、行の開始インデックスを覚えておき、
7257        // 改行が確定した時点でその行の子要素だけを事後的に `translate_y` でシフトする。
7258        let mut line_start_idx = 0usize;
7259        // 直前の子が空白だったか(`inline_child_space_adjust`。最初の行の先頭は分からないので None)。
7260        let mut after_space: Option<bool> = None;
7261
7262        // 【2026-11-30 TODO S2】この箱が包含ブロックを作る(`position:relative` の inline-block 等)なら、
7263        // 子孫の absolute / fixed の基準をこの箱のパディング箱へ切り替える。幅・高さはここで確定済み。
7264        // 従来は block の入れ物(layout_block)にしかこの処理が無く、inline-block の中の絶対配置は
7265        // 流れに残って(しかも行の高さを消費して)入れ物の角に付かなかった。
7266        let est_abs = box_establishes_abs_cb(self);
7267        let est_fixed = box_establishes_fixed_cb(self);
7268        let cb_pb = if est_abs || est_fixed {
7269            let mut pb = self.dimensions.padding_box();
7270            if matches!(self.box_type, BoxType::InlineBlockNode(_)) && slot_size.0 > 0 && slot_size.1 > 0 {
7271                pb.width += slot_size.0 - self.dimensions.content.width;
7272                pb.height += slot_size.1 - self.dimensions.content.height;
7273            }
7274            pb
7275        } else {
7276            Rect::default()
7277        };
7278        let saved_abs_cb = if est_abs {
7279            let prev = abs_cb_get();
7280            abs_cb_set(cb_pb.x, cb_pb.y, cb_pb.width, cb_pb.height);
7281            Some(prev)
7282        } else {
7283            None
7284        };
7285        let saved_fixed_cb = if est_fixed {
7286            let prev = fixed_cb_get();
7287            fixed_cb_set(Some((cb_pb.x, cb_pb.y, cb_pb.width, cb_pb.height)));
7288            Some(prev)
7289        } else {
7290            None
7291        };
7292
7293        let mut i = 0usize;
7294        while i < self.children.len() {
7295            // フロー外(absolute / fixed): サイズ確定のため組むだけで、行にも高さにも加えない。
7296            // 静的位置は今のフローカーソル。最終位置は末尾の apply_positioned_offsets が決める。
7297            if Self::child_is_out_of_flow(&self.children[i]) {
7298                let mut cb = self.dimensions.clone();
7299                cb.content.x += child_flow_x;
7300                cb.content.height = child_flow_y;
7301                self.children[i].layout(cb);
7302                i += 1;
7303                continue;
7304            }
7305            match self.children[i].box_type {
7306                BoxType::BlockNode(_)
7307                | BoxType::FlexNode(_)
7308                | BoxType::GridNode(_)
7309                | BoxType::TableNode(_)
7310                | BoxType::TableRowGroupNode(_)
7311                | BoxType::TableRowNode(_)
7312                | BoxType::TableCellNode(_) => {
7313                    if child_flow_x > 0 {
7314                        self.finalize_inline_line_vertical_align(line_start_idx, i, line_h, max_w);
7315                        child_flow_y += line_h;
7316                        child_flow_x = 0;
7317                        line_h = 0;
7318                    }
7319                    line_start_idx = i + 1;
7320                    let child = &mut self.children[i];
7321                    let mut cb = self.dimensions.clone();
7322                    cb.content.height = child_flow_y;
7323                    child.layout(cb);
7324                    child_flow_y += child.dimensions.margin_box().height;
7325                    after_space = Some(true);
7326                    // 【2026-09-26 バグ修正】この `i += 1` が抜けており、インライン要素の
7327                    // 中にブロックの子があると(`<a><div>..</div></a>` 等、実サイトで
7328                    // ごく普通の形)同じ子を永遠にレイアウトし続けて**ブラウザが固まって**いた。
7329                    i += 1;
7330                }
7331                BoxType::InlineNode(_) | BoxType::InlineBlockNode(_) => {
7332                    if self.children[i].is_inline_line_break() {
7333                        self.finalize_inline_line_vertical_align(line_start_idx, i, line_h, max_w);
7334                        child_flow_y += line_h.max(20);
7335                        child_flow_x = 0;
7336                        line_h = 0;
7337                        line_start_idx = i + 1;
7338                        after_space = Some(true);
7339                        i += 1;
7340                        continue;
7341                    }
7342                    let (measured_w, child_h) = self.children[i].intrinsic_inline_size(max_w);
7343                    let (mut child_w, mut trim, mut ends_space) =
7344                        self.children[i].inline_child_space_adjust(measured_w, after_space);
7345                    if child_flow_x > 0 && child_flow_x + child_w > max_w {
7346                        self.finalize_inline_line_vertical_align(line_start_idx, i, line_h, max_w);
7347                        child_flow_y += line_h.max(20);
7348                        child_flow_x = 0;
7349                        line_h = 0;
7350                        line_start_idx = i;
7351                        // 折り返して行頭に来た子は、先頭の空白を落とす。
7352                        (child_w, trim, ends_space) = self.children[i].inline_child_space_adjust(measured_w, Some(true));
7353                    }
7354                    let is_blank = self.children[i].is_blank_inline();
7355                    let is_space = self.children[i].is_collapsible_space();
7356                    let child = &mut self.children[i];
7357                    if child.trim_leading_space != trim {
7358                        child.trim_leading_space = trim;
7359                    }
7360                    if is_space || ends_space {
7361                        after_space = Some(true);
7362                    } else if !is_blank {
7363                        after_space = Some(false);
7364                    }
7365                    child.dimensions.content.x = self.dimensions.content.x + child_flow_x;
7366                    child.dimensions.content.y = self.dimensions.content.y + child_flow_y;
7367                    child.dimensions.content.width = child_w;
7368                    child.dimensions.content.height = child_h;
7369
7370                    // 子要素(InlineNode など)に対して再帰的にレイアウトを呼び出して、さらにその中の座標を決定する。
7371                    // 注意: 子自身が InlineNode/InlineBlockNode の場合、渡した cb.content.height
7372                    // (ここでは子自身の高さ)を子の layout_inline が「Y フローカーソル」として
7373                    // 自身の content.y に加算してしまい、確定済みのスロット位置を上書きしてしまう
7374                    // (layout_block の inline 子ループに既存の同種ワークアラウンドと同じ理由)。
7375                    // そのため子のレイアウト後に確定済みのスロット位置へ再設定する。
7376                    let cb = child.dimensions.clone();
7377                    child.layout(cb);
7378                    // 子孫ごとスロットへ戻す(layout_block の inline 子と同じ理由。2026-09-26)。
7379                    let (el, er, et, eb) = child.inline_block_edges();
7380                    let slot_x = self.dimensions.content.x + child_flow_x + el;
7381                    let slot_y = self.dimensions.content.y + child_flow_y + et;
7382                    let (dx, dy) = (slot_x - child.dimensions.content.x, slot_y - child.dimensions.content.y);
7383                    child.translate(dx, dy);
7384                    child.dimensions.content.width = child_w;
7385                    child.dimensions.content.height = child_h;
7386
7387                    child_flow_x += el + child_w + er;
7388                    let outer_h = et + child_h + eb;
7389                    if outer_h > line_h {
7390                        line_h = outer_h;
7391                    }
7392                    i += 1;
7393                }
7394                BoxType::AnonymousBlock => {
7395                    i += 1;
7396                }
7397            }
7398        }
7399        // 最終行(末尾に改行/ブロック要素が無いまま終わる行)の vertical-align を適用する。
7400        self.finalize_inline_line_vertical_align(line_start_idx, self.children.len(), line_h, max_w);
7401
7402        // 子の relative / absolute / fixed / transform を適用する(layout_block と同じ共有処理)。
7403        // 文字だけの子(最頻出)しか無いときは何も起きないので呼ばない。
7404        let has_element_child = self.children.iter().any(|c| {
7405            !matches!(&c.box_type, BoxType::InlineNode(n) if matches!(n.node.node_type, NodeType::Text(_)))
7406        });
7407        if has_element_child {
7408            self.apply_positioned_offsets_with(None, true);
7409        }
7410        if let Some(prev) = saved_abs_cb {
7411            abs_cb_set(prev.0, prev.1, prev.2, prev.3);
7412        }
7413        if let Some(prev) = saved_fixed_cb {
7414            fixed_cb_set(prev);
7415        }
7416    }
7417
7418    /// インラインの1行ぶん(`[start, end)` の子要素)に `vertical-align` を適用する。
7419    /// **簡略化**: `top`/`baseline`/`sub`/`super`/`text-top` はいずれも無調整(top相当)、
7420    /// `middle` は行の中央、`bottom`/`text-bottom` は行の下端に揃える。table セルの
7421    /// vertical-align(内容のみシフト)とは異なり、ここでは子要素自身(背景/境界線含む)を
7422    /// まるごとシフトする(インラインボックス自体の行内配置を変えるのが目的のため)。
7423    fn finalize_inline_line_vertical_align(&mut self, start: usize, end: usize, line_h: i32, max_w: i32) {
7424        if line_h <= 0 || end <= start {
7425            return;
7426        }
7427        for idx in start..end {
7428            let Some(child) = self.children.get_mut(idx) else {
7429                continue;
7430            };
7431            if !matches!(
7432                child.box_type,
7433                BoxType::InlineNode(_) | BoxType::InlineBlockNode(_)
7434            ) {
7435                continue;
7436            }
7437            let va = box_style_value_ref(child, "vertical-align").unwrap_or("");
7438            let offset = match va.trim() {
7439                "middle" => {
7440                    let (_, child_h) = inline_child_outer_size(child, max_w);
7441                    (line_h - child_h) / 2
7442                }
7443                "bottom" | "text-bottom" => {
7444                    let (_, child_h) = inline_child_outer_size(child, max_w);
7445                    line_h - child_h
7446                }
7447                _ => 0,
7448            };
7449            if offset != 0 {
7450                child.translate_y(offset);
7451            }
7452        }
7453    }
7454
7455    /// min-width/max-width 等のサイジング値を解決する。px/% は base 基準、
7456    /// `min-content`/`max-content`/`fit-content` は内容計測で解決。auto/未指定は None。
7457    fn resolve_sizing_value(&self, value: Option<&str>, base: i32) -> Option<i32> {
7458        match parse_length_value(value)? {
7459            LengthValue::Auto => None,
7460            LengthValue::Px(px) => Some(px),
7461            LengthValue::Percent(pct) => Some(round_f32_to_i32(base as f32 * pct)),
7462            LengthValue::MinContent => Some(self.block_intrinsic_widths().0),
7463            LengthValue::MaxContent => Some(self.block_intrinsic_widths().1),
7464            LengthValue::FitContent => {
7465                let (minc, maxc) = self.block_intrinsic_widths();
7466                Some(maxc.min(base.max(0)).max(minc))
7467            }
7468            LengthValue::FitContentWith(lim_box) => {
7469                let limit = resolve_length_value_with_font(*lim_box, base, self.font_size())
7470                    .unwrap_or(base);
7471                let (minc, maxc) = self.block_intrinsic_widths();
7472                Some(maxc.min(limit.max(minc)))
7473            }
7474            LengthValue::MathExpr(expr) => {
7475                crate::os_lib::css::eval_css_math_with_font(&expr, base, self.font_size())
7476            }
7477        }
7478    }
7479
7480    /// `flex-basis` が中身の幅(`min-width: auto` の自動最小サイズ)を下回らないようにする
7481    /// (CSS Flexbox L1 §4.5。仮のサイズは下限で止まる)。`overflow` が visible 以外なら下限は 0。
7482    /// YouTube の `#owner` は `flex-basis: 0.000000001px` で、潰れて隣の列と重なっていた(2026-11-01)。
7483    /// 計測は重いので、今の幅より小さくなるときだけ測る。
7484    fn basis_with_auto_min(&self, basis: i32) -> i32 {
7485        self.basis_with_auto_min_h(basis, None)
7486    }
7487
7488    /// `basis_with_auto_min` の、交差軸の高さが確定しているとき(単一行・高さ確定のコンテナで stretch される項目)の版。
7489    /// 最小内容幅をその高さで測る(中の `height:100%` の canvas 等が縮む。WPT css-flexbox flex-item-percentage-height-img-001:
7490    /// `flex-basis: 0` の項目の下限が canvas の本来の幅 400 で測られ 410px になっていた。正しくは 200px)。
7491    fn basis_with_auto_min_h(&self, basis: i32, definite_h: Option<i32>) -> i32 {
7492        // 伸びるアイテムは基準をそのまま使い、配分のときに下限で止める(§9.7)。
7493        if box_flex_grow_f32(self) > 0.0 {
7494            return basis;
7495        }
7496        let auto_min = box_style_value_ref(self, "min-width").is_none_or(|v| v.trim() == "auto");
7497        let visible = box_style_value_ref(self, "overflow").is_none_or(|v| v.trim() == "visible");
7498        if auto_min && visible {
7499            let min_c = match definite_h {
7500                Some(h) => self.block_intrinsic_widths_with_h(Some(h)).0,
7501                None => self.block_intrinsic_widths().0,
7502            };
7503            basis.max(min_c)
7504        } else {
7505            basis
7506        }
7507    }
7508
7509    /// 伸びるアイテムの下限(`min-width: auto` の自動最小サイズ)。
7510    fn grow_auto_min(&self) -> i32 {
7511        let auto_min = box_style_value_ref(self, "min-width").is_none_or(|v| v.trim() == "auto");
7512        let visible = box_style_value_ref(self, "overflow").is_none_or(|v| v.trim() == "visible");
7513        if auto_min && visible {
7514            self.block_intrinsic_widths().0.max(0)
7515        } else {
7516            0
7517        }
7518    }
7519
7520    /// ブロック要素の内容ベース幅を返す: (min_content, max_content)。
7521    /// max_content = 折返しなしの最大行幅、min_content = 最大限折返したときの最小幅。
7522    /// 直下の子(inline/text/block)を計測して集約する。
7523    pub(crate) fn block_intrinsic_widths(&self) -> (i32, i32) {
7524        // 縦書き: 親と世界が違う箱の内在「幅」は block サイズ(試し組みで測る)。
7525        let cur_world = crate::os_lib::css::CUR_WORLD.load(AtomicOrdering::Relaxed);
7526        if cur_world != 0 || crate::os_lib::css::WM_SEEN.load(AtomicOrdering::Relaxed) {
7527            if let Some(n) = self.world_node() {
7528                let w = super::writing_mode::world_of(n);
7529                if w != cur_world {
7530                    return self.orthogonal_intrinsic_widths(cur_world, w);
7531                }
7532            }
7533        }
7534        let (styled_opt, tag): (Option<&StyledNode<'a>>, u8) = match &self.box_type {
7535            BoxType::BlockNode(n) => (Some(*n), 1),
7536            BoxType::InlineNode(n) => (Some(*n), 2),
7537            BoxType::InlineBlockNode(n) => (Some(*n), 3),
7538            BoxType::FlexNode(n) => (Some(*n), 4),
7539            BoxType::GridNode(n) => (Some(*n), 5),
7540            BoxType::TableNode(n) => (Some(*n), 6),
7541            BoxType::TableRowGroupNode(n) => (Some(*n), 7),
7542            BoxType::TableRowNode(n) => (Some(*n), 8),
7543            BoxType::TableCellNode(n) => (Some(*n), 9),
7544            BoxType::AnonymousBlock => (None, 0),
7545        };
7546        let cw = self.dimensions.content.width;
7547        // 縦書きの世界では覚え書きを使わない(同じ要素が世界ごとに別の寸法になるため)。
7548        let styled_opt = if crate::os_lib::css::CUR_WORLD.load(AtomicOrdering::Relaxed) != 0 { None } else { styled_opt };
7549        if let Some(node) = styled_opt {
7550            if let Ok(cache) = node.block_intrinsic_cache.try_borrow() {
7551                if let Some((c_tag, c_cw, min_c, max_c)) = *cache {
7552                    if c_tag == tag && c_cw == cw {
7553                        return (min_c, max_c);
7554                    }
7555                }
7556            }
7557        }
7558        let res = self.block_intrinsic_widths_uncached();
7559        if let Some(node) = styled_opt {
7560            if let Ok(mut cache) = node.block_intrinsic_cache.try_borrow_mut() {
7561                *cache = Some((tag, cw, res.0, res.1));
7562            }
7563        }
7564        res
7565    }
7566
7567    /// ブロック要素の内容ベース幅を `definite_h`(交差軸 stretch 等で確定した高さ)付きで測る。
7568    fn block_intrinsic_widths_with_h(&self, definite_h: Option<i32>) -> (i32, i32) {
7569        if let Some(h) = definite_h {
7570            NEXT_DEFINITE_H.store(h, AtomicOrdering::Relaxed);
7571            let res = self.block_intrinsic_widths_uncached();
7572            NEXT_DEFINITE_H.store(-1, AtomicOrdering::Relaxed);
7573            res
7574        } else {
7575            self.block_intrinsic_widths()
7576        }
7577    }
7578
7579    /// テキストや置換要素、明示幅指定などの実質的な内在幅要素をサブツリーに含むか。
7580    fn subtree_has_text_or_replaced(&self) -> bool {
7581        if self.is_replaced_inline() {
7582            return true;
7583        }
7584        if let Some(styled) = self.styled_node() {
7585            if let NodeType::Element { tag_name, .. } = &styled.node.node_type {
7586                if matches!(tag_name.as_str(), "img" | "video" | "canvas" | "iframe" | "embed" | "object" | "svg") {
7587                    return true;
7588                }
7589            }
7590        }
7591        match &self.box_type {
7592            BoxType::InlineNode(n) | BoxType::InlineBlockNode(n) => {
7593                if let NodeType::Text(t) = &n.node.node_type {
7594                    return !t.trim().is_empty();
7595                }
7596                if pseudo_content_size(n).is_some() {
7597                    return true;
7598                }
7599            }
7600            _ => {}
7601        }
7602        if matches!(
7603            parse_length_value(box_style_value_ref(self, "width")),
7604            Some(LengthValue::Px(_))
7605        ) {
7606            return true;
7607        }
7608        self.children.iter().any(|c| !Self::child_is_out_of_flow(c) && c.subtree_has_text_or_replaced())
7609    }
7610
7611    /// ブロックレベルの子の内在幅を計測する(`aspect-ratio` + 解決可能な高さにも対応)。
7612    fn block_child_intrinsic_with_ratio(child: &LayoutBox, pct_base_h: i32) -> (i32, i32, bool) {
7613        if let Some(LengthValue::Px(px)) = parse_length_value(box_style_value_ref(child, "width")) {
7614            return (px.max(0), px.max(0), true);
7615        }
7616        if let Some((num, den)) = box_aspect_ratio(child) {
7617            if num > 0.0 && den > 0.0 {
7618                let h_opt = match parse_length_value(box_style_value_ref(child, "height")) {
7619                    Some(LengthValue::Px(px)) => Some((px - border_box_inner_h(child)).max(0)),
7620                    Some(LengthValue::Percent(pct)) if pct_base_h >= 0 => {
7621                        Some((round_f32_to_i32(pct_base_h as f32 * pct) - border_box_inner_h(child)).max(0))
7622                    }
7623                    _ => None,
7624                };
7625                if let Some(ch) = h_opt {
7626                    let w = round_f32_to_i32(ch as f32 * num / den).max(0);
7627                    return (w, w, false);
7628                }
7629            }
7630        }
7631        let (a, b) = child.block_intrinsic_widths();
7632        (a, b, false)
7633    }
7634
7635    fn block_intrinsic_widths_uncached(&self) -> (i32, i32) {
7636        let forced_dh = NEXT_DEFINITE_H.swap(-1, AtomicOrdering::Relaxed);
7637        let _forced_h_guard = if forced_dh >= 0 {
7638            Some(PctBaseHGuard::set(forced_dh))
7639        } else {
7640            None
7641        };
7642        if let BoxType::BlockNode(n) | BoxType::InlineBlockNode(n) | BoxType::InlineNode(n) = &self.box_type {
7643            if let Some((w, _)) = pseudo_content_size(n) {
7644                return (w, w);
7645            }
7646        }
7647        // 自身が inline/inline-block を直接表すなら、その計測を使う
7648        // (inline-flex は下の flex コンテナの計測へ回す)。
7649        if matches!(
7650            self.box_type,
7651            BoxType::InlineNode(_) | BoxType::InlineBlockNode(_)
7652        ) && !self.is_inline_flex()
7653            && !self.is_inline_grid()
7654        {
7655            let max_c = self.intrinsic_inline_size_ext(1_000_000, true).0;
7656            let min_c = self.intrinsic_inline_size_ext(1, true).0;
7657            return (min_c.max(0), max_c.max(min_c).max(0));
7658        }
7659        if let BoxType::InlineBlockNode(node) = &self.box_type {
7660            if self.is_inline_grid() {
7661                let cols = parse_grid_tracks(
7662                    node.value_ref("grid-template-columns").unwrap_or(""),
7663                    0,
7664                );
7665                let all_px: Option<i32> = if cols.is_empty() {
7666                    None
7667                } else {
7668                    cols.iter().try_fold(0i32, |acc, t| match t {
7669                        GridTrack::Px(px) => Some(acc + (*px).max(0)),
7670                        _ => None,
7671                    })
7672                };
7673                if let Some(sum) = all_px {
7674                    let (_, cg) = parse_flex_gap(node, 0);
7675                    let w = sum + cg.max(0) * (cols.len() as i32 - 1).max(0);
7676                    return (w, w);
7677                }
7678            }
7679        }
7680        let flex_node = match &self.box_type {
7681            BoxType::FlexNode(n) => Some(*n),
7682            BoxType::InlineBlockNode(n) if self.is_inline_flex() => Some(*n),
7683            _ => None,
7684        };
7685        if let Some(node) = flex_node {
7686            let dir = node
7687                .value_ref("flex-direction")
7688                .unwrap_or("row")
7689                .trim();
7690            let is_row = !(dir.len() >= 6 && dir.as_bytes()[..6].eq_ignore_ascii_case(b"column"));
7691            let wraps = node
7692                .value_ref("flex-wrap")
7693                .map(|w| {
7694                    let wt = w.trim();
7695                    wt.len() >= 4 && wt.as_bytes()[..4].eq_ignore_ascii_case(b"wrap")
7696                })
7697                .unwrap_or(false);
7698            if is_row {
7699                let cur_pct_h = if forced_dh >= 0 {
7700                    forced_dh
7701                } else {
7702                    match parse_length_value(box_style_value_ref(self, "height")) {
7703                        Some(LengthValue::Px(px)) => (px - border_box_inner_h(self)).max(0),
7704                        _ => -1,
7705                    }
7706                };
7707                let _inner_pct_g = PctBaseHGuard::set(cur_pct_h);
7708                struct FlexIntrItem {
7709                    raw_basis: i32,
7710                    clamped_basis: i32,
7711                    used_min: i32,
7712                    used_max: i32,
7713                    min_contrib: i32,
7714                    max_contrib: i32,
7715                    grow: f32,
7716                    shrink: f32,
7717                    edges: i32,
7718                }
7719                let mut items: Vec<FlexIntrItem> = Vec::new();
7720                for child in self.children.iter().filter(|c| !Self::child_is_out_of_flow(c)) {
7721                    let inner_w = border_box_inner_w(child);
7722                    let explicit_px = match parse_length_value(box_style_value_ref(child, "width")) {
7723                        Some(LengthValue::Px(px)) => Some(px.max(0)),
7724                        _ => None,
7725                    };
7726                    let explicit_content_w = explicit_px.map(|w| (w - inner_w).max(0));
7727                    let (raw_cmin, raw_cmax) = if let Some((num, den)) = box_aspect_ratio(child) {
7728                        if num > 0.0 && den > 0.0 && explicit_px.is_none() {
7729                            let h_opt = match parse_length_value(box_style_value_ref(child, "height")) {
7730                                Some(LengthValue::Px(px)) => Some((px - border_box_inner_h(child)).max(0)),
7731                                Some(LengthValue::Percent(pct)) if cur_pct_h >= 0 => {
7732                                    Some((round_f32_to_i32(cur_pct_h as f32 * pct) - border_box_inner_h(child)).max(0))
7733                                }
7734                                _ => None,
7735                            };
7736                            if let Some(ch) = h_opt {
7737                                let w = round_f32_to_i32(ch as f32 * num / den).max(0);
7738                                (w, w)
7739                            } else {
7740                                child.block_intrinsic_widths()
7741                            }
7742                        } else {
7743                            child.block_intrinsic_widths()
7744                        }
7745                    } else {
7746                        child.block_intrinsic_widths()
7747                    };
7748                    let explicit_min = match parse_length_value(box_style_value_ref(child, "min-width")) {
7749                        Some(LengthValue::Px(px)) => Some((px - inner_w).max(0)),
7750                        _ => None,
7751                    };
7752                    let explicit_max = match parse_length_value(box_style_value_ref(child, "max-width")) {
7753                        Some(LengthValue::Px(px)) => Some((px - inner_w).max(0)),
7754                        _ => None,
7755                    };
7756                    let clips = box_style_value_ref(child, "overflow")
7757                        .is_some_and(|v| matches!(v.trim(), "hidden" | "scroll" | "auto" | "clip"))
7758                        || box_style_value_ref(child, "overflow-x")
7759                            .is_some_and(|v| matches!(v.trim(), "hidden" | "scroll" | "auto" | "clip"));
7760                    let auto_min = if clips {
7761                        0
7762                    } else {
7763                        let mut cs = raw_cmin;
7764                        if let Some(mx) = explicit_max {
7765                            cs = cs.min(mx);
7766                        }
7767                        if let Some(sw) = explicit_content_w {
7768                            cs = cs.min(sw);
7769                        }
7770                        cs
7771                    };
7772                    let used_min = explicit_min.unwrap_or(auto_min);
7773                    let used_max = explicit_max.unwrap_or(i32::MAX).max(used_min);
7774                    let basis_opt = box_flex_basis(child, 0).filter(|_| !box_flex_basis_is_percentage(child));
7775                    let raw_basis = basis_opt
7776                        .map(|b| (b - inner_w).max(0))
7777                        .or(explicit_content_w)
7778                        .unwrap_or(raw_cmax);
7779                    let clamped_basis = raw_basis.clamp(used_min, used_max);
7780                    let contrib_lo = explicit_min.unwrap_or(0);
7781                    let contrib_hi = explicit_max.unwrap_or(i32::MAX).max(contrib_lo);
7782                    let min_contrib = explicit_content_w.unwrap_or(0).max(raw_cmin).clamp(contrib_lo, contrib_hi);
7783                    let max_contrib = explicit_content_w.unwrap_or(0).max(raw_cmax).clamp(used_min, used_max);
7784                    let edges = intrinsic_h_edges(child, false);
7785                    items.push(FlexIntrItem {
7786                        raw_basis,
7787                        clamped_basis,
7788                        used_min,
7789                        used_max,
7790                        min_contrib,
7791                        max_contrib,
7792                        grow: box_flex_grow_f32(child),
7793                        shrink: box_flex_shrink_f32(child),
7794                        edges,
7795                    });
7796                }
7797                let (rg, cg) = parse_flex_gap(node, self.dimensions.content.width);
7798                let _ = rg;
7799                let n = items.len() as i32;
7800                let gaps = if n > 1 { cg * (n - 1) } else { 0 };
7801                let max_sum: i32 = items.iter().map(|it| it.max_contrib + it.edges).sum();
7802                if wraps {
7803                    let mut max_min = 0i32;
7804                    for it in &items {
7805                        let c = if it.min_contrib > it.clamped_basis {
7806                            if it.grow > 0.0 { it.min_contrib } else { it.clamped_basis }
7807                        } else if it.min_contrib < it.clamped_basis {
7808                            if it.shrink > 0.0 { it.min_contrib } else { it.clamped_basis }
7809                        } else {
7810                            it.clamped_basis
7811                        };
7812                        max_min = max_min.max(c + it.edges);
7813                    }
7814                    return (max_min.max(0), (max_sum + gaps).max(max_min).max(0));
7815                }
7816                // nowrap: CSS Flexbox §9.9.1 desired flex fraction による min-content 寄与。
7817                let mut max_frac = f32::NEG_INFINITY;
7818                for it in &items {
7819                    let diff = it.min_contrib - it.raw_basis;
7820                    let df = if diff > 0 {
7821                        if it.grow > 0.0 { diff as f32 / it.grow } else { 0.0 }
7822                    } else if diff < 0 {
7823                        if it.shrink > 0.0 && it.raw_basis > 0 {
7824                            diff as f32 / (it.shrink * it.raw_basis as f32)
7825                        } else {
7826                            f32::NEG_INFINITY
7827                        }
7828                    } else {
7829                        0.0
7830                    };
7831                    if df > max_frac {
7832                        max_frac = df;
7833                    }
7834                }
7835                let chosen = if max_frac.is_finite() { max_frac } else { 0.0 };
7836                let sum_min: i32 = items
7837                    .iter()
7838                    .map(|it| {
7839                        let c = if chosen > 0.0 {
7840                            if it.grow > 0.0 {
7841                                round_f32_to_i32(it.raw_basis as f32 + chosen * it.grow)
7842                                    .clamp(it.used_min, it.used_max)
7843                                    .max(it.min_contrib)
7844                            } else {
7845                                it.clamped_basis
7846                            }
7847                        } else if it.min_contrib < it.clamped_basis && it.shrink > 0.0 {
7848                            it.min_contrib
7849                        } else {
7850                            it.clamped_basis
7851                        };
7852                        c + it.edges
7853                    })
7854                    .sum();
7855                let min_c = (sum_min + gaps).max(0);
7856                return (min_c, (max_sum + gaps).max(min_c).max(0));
7857            }
7858            if wraps {
7859                if let Some(r) = self.column_wrap_intrinsic_widths(node) {
7860                    return r;
7861                }
7862            }
7863        }
7864
7865        let grid_node = match &self.box_type {
7866            BoxType::GridNode(n) => Some(*n),
7867            BoxType::InlineBlockNode(n) if self.is_inline_grid() => Some(*n),
7868            _ => None,
7869        };
7870        if let Some(node) = grid_node {
7871            return self.grid_container_intrinsic_widths(node);
7872        }
7873
7874        self.children_intrinsic_widths_inner(if forced_dh >= 0 { Some(forced_dh) } else { None })
7875    }
7876
7877    /// `flex-flow: column wrap` の内在幅。高さの制約(height / max-height / min-height)で項目を列へ
7878    /// 詰め、各列の最大の項目幅の合計 + 列間 gap を返す。高さが確定しなければ `None`(汎用計測へ)。
7879    fn column_wrap_intrinsic_widths(&self, node: &StyledNode) -> Option<(i32, i32)> {
7880        let pct_base = PCT_BASE_H.load(AtomicOrdering::Relaxed);
7881        let inner = border_box_inner_h(self);
7882        let resolve = |prop: &str| -> Option<i32> {
7883            match parse_length_value(box_style_value_ref(self, prop)) {
7884                Some(LengthValue::Px(px)) => Some(px),
7885                Some(LengthValue::Percent(p)) if pct_base >= 0 => Some(round_f32_to_i32(pct_base as f32 * p)),
7886                _ => None,
7887            }
7888        };
7889        let mut limit = resolve("height").map(|h| (h - inner).max(0));
7890        if let Some(mx) = resolve("max-height") {
7891            let mx = (mx - inner).max(0);
7892            limit = Some(limit.map_or(mx, |l| l.min(mx)));
7893        }
7894        if let (Some(l), Some(mn)) = (limit, resolve("min-height")) {
7895            limit = Some(l.max((mn - inner).max(0)));
7896        }
7897        let limit = limit?;
7898        let (rg, cg) = parse_flex_gap(node, 0);
7899        let items: Vec<&LayoutBox> = self.children.iter().filter(|c| !Self::child_is_out_of_flow(c)).collect();
7900        let width_of = |c: &LayoutBox| -> (i32, i32) {
7901            let explicit = match parse_length_value(box_style_value_ref(c, "width")) {
7902                Some(LengthValue::Px(px)) => Some(px.max(0)),
7903                _ => None,
7904            };
7905            let (cmin, cmax) = explicit.map(|w| (w, w)).unwrap_or_else(|| c.block_intrinsic_widths());
7906            let (cmin, cmax) = clamp_contribution(c, cmin, cmax, explicit.is_none());
7907            let edges = intrinsic_h_edges(c, explicit.is_some());
7908            (cmin + edges, cmax + edges)
7909        };
7910        let main_of = |c: &LayoutBox, c_max_w: i32| -> i32 {
7911            let m = box_flex_basis(c, limit)
7912                .filter(|_| !box_flex_basis_is_percentage(c))
7913                .or_else(|| box_len(c, "height", limit).map(|h| h + border_box_inner_h(c)))
7914                .or_else(|| {
7915                    box_aspect_ratio(c).and_then(|(num, den)| {
7916                        (num > 0.0 && den > 0.0).then(|| round_f32_to_i32(c_max_w as f32 * den / num).max(0))
7917                    })
7918                })
7919                .unwrap_or(0);
7920            m.max(0) + c.dimensions.margin.top.max(0) + c.dimensions.margin.bottom.max(0)
7921        };
7922        let mut total = (0i32, 0i32);
7923        let mut lines = 0i32;
7924        let mut line_main = 0i32;
7925        let mut line_w = (0i32, 0i32);
7926        let mut line_n = 0i32;
7927        for c in items {
7928            let (wmin, wmax) = width_of(c);
7929            let m = main_of(c, wmax);
7930            let add = if line_n > 0 { rg + m } else { m };
7931            if line_n > 0 && line_main + add > limit {
7932                total = (total.0 + line_w.0, total.1 + line_w.1);
7933                lines += 1;
7934                line_main = m;
7935                line_w = (wmin, wmax);
7936                line_n = 1;
7937            } else {
7938                line_main += add;
7939                line_w = (line_w.0.max(wmin), line_w.1.max(wmax));
7940                line_n += 1;
7941            }
7942        }
7943        if line_n > 0 {
7944            total = (total.0 + line_w.0, total.1 + line_w.1);
7945            lines += 1;
7946        }
7947        let gaps = if lines > 1 { cg * (lines - 1) } else { 0 };
7948        Some(((total.0 + gaps).max(0), (total.1 + gaps).max(total.0 + gaps).max(0)))
7949    }
7950
7951    /// グリッドコンテナの内在幅 (min-content, max-content)(CSS Grid §11.1・列のトラックサイズ決定を
7952    /// min-content / max-content 制約で走らせ、トラックの合計 + 溝)。`%` や auto-fill は確定幅が
7953    /// 無いので 1 回の繰り返し・auto 扱い。
7954    fn grid_container_intrinsic_widths(&self, node: &StyledNode) -> (i32, i32) {
7955        let t_cols = node.value_ref("grid-template-columns").unwrap_or("");
7956        let t_rows = node.value_ref("grid-template-rows").unwrap_or("");
7957        let (_, cg) = parse_flex_gap(node, 0);
7958        let sub = is_subgrid(t_cols);
7959        // 幅未確定でも max-width(min で下限)→ min-width が確定長さ/% なら auto-repeat の回数に使う。
7960        let avail_w_hint = GRID_INTRINSIC_AVAIL_W.load(AtomicOrdering::Relaxed);
7961        let bb = border_box_inner_w(self);
7962        let px_of = |p: &str| match parse_length_value(len_value(node, p).as_deref()) {
7963            Some(LengthValue::Px(px)) => Some((px - bb).max(0)),
7964            Some(LengthValue::Percent(pct)) if avail_w_hint >= 0 => {
7965                Some((round_f32_to_i32(avail_w_hint as f32 * pct) - bb).max(0))
7966            }
7967            Some(LengthValue::MathExpr(ref e)) if avail_w_hint >= 0 || !e.contains('%') => {
7968                crate::os_lib::css::eval_css_math_with_font(e, avail_w_hint.max(0), self.font_size())
7969                    .map(|px| (px - bb).max(0))
7970            }
7971            _ => None,
7972        };
7973        let (min_w, max_w) = (px_of("min-width"), px_of("max-width"));
7974        let col_avail = max_w.map(|mx| mx.max(min_w.unwrap_or(0)));
7975        let col_min = if col_avail.is_none() { min_w } else { None };
7976        let col_tpl = if sub {
7977            parse_template("", None, None, 0)
7978        } else {
7979            parse_template_with_font_est(t_cols, None, col_avail, cg, self.font_size(), 0.0, col_min)
7980        };
7981        let row_tpl = if is_subgrid(t_rows) { parse_template("", None, None, 0) } else { parse_template(t_rows, None, None, 0) };
7982        let areas = parse_grid_template_areas(node.value_ref("grid-template-areas").unwrap_or(""));
7983        let n_exp_rows = row_tpl.tracks.len().max(areas.len());
7984        let n_exp_cols = col_tpl.tracks.len().max(areas.iter().map(|r| r.len()).max().unwrap_or(0));
7985        let mut row_names = row_tpl.names.clone();
7986        let mut col_names = col_tpl.names.clone();
7987        row_names.resize(n_exp_rows + 1, Vec::new());
7988        col_names.resize(n_exp_cols + 1, Vec::new());
7989        if !areas.is_empty() {
7990            add_area_line_names(&areas, &mut row_names, &mut col_names);
7991        }
7992        let mut idxs: Vec<usize> = Vec::new();
7993        let mut place_in: Vec<PlaceIn> = Vec::new();
7994        for (idx, child) in self.children.iter().enumerate() {
7995            if Self::child_is_out_of_flow(child) {
7996                continue;
7997            }
7998            let (rs, re, cs, ce) = read_item_lines(child);
7999            idxs.push(idx);
8000            place_in.push(PlaceIn {
8001                row: resolve_axis(&rs, &re, &row_names, n_exp_rows),
8002                col: resolve_axis(&cs, &ce, &col_names, n_exp_cols),
8003            });
8004        }
8005        let flow = node.value_ref("grid-auto-flow").unwrap_or("");
8006        let placed = place_items(
8007            &place_in,
8008            n_exp_rows,
8009            n_exp_cols,
8010            flow.split_whitespace().any(|t| t == "column"),
8011            flow.split_whitespace().any(|t| t == "dense"),
8012        );
8013        let n_cols = placed.n_cols.max(n_exp_cols).max(usize::from(!idxs.is_empty()));
8014        let auto_cols = {
8015            let t = parse_template(node.value_ref("grid-auto-columns").unwrap_or(""), None, None, 0);
8016            if t.tracks.is_empty() { alloc::vec![TrackDef::AUTO] } else { t.tracks }
8017        };
8018        let defs = grid_build_defs(&col_tpl, n_cols, placed.neg_cols, &auto_cols);
8019        let mut items: Vec<SizeItem> = Vec::new();
8020        for (k, &idx) in idxs.iter().enumerate() {
8021            let Some(&(_, c, _, cs)) = placed.pos.get(k) else { continue };
8022            let (mn, mx, am, edges, no_clamp) = Self::grid_col_contrib(&self.children[idx]);
8023            items.push(SizeItem {
8024                start: c,
8025                end: c + cs,
8026                min_c: mn as f32,
8027                max_c: mx as f32,
8028                auto_min: am as f32,
8029                edges: edges as f32,
8030                no_auto_clamp: no_clamp,
8031            });
8032        }
8033        let collapsed = alloc::vec![false; n_cols];
8034        let gap = cg.max(0) as f32;
8035        let total = |free: FreeSpace| -> i32 {
8036            let sizes = size_tracks(&defs, &items, free, gap, &collapsed, false);
8037            let gaps = if n_cols > 1 { (n_cols - 1) as f32 * gap } else { 0.0 };
8038            round_f32_to_i32(sizes.iter().sum::<f32>() + gaps).max(0)
8039        };
8040        let minc = total(FreeSpace::Min);
8041        let maxc = total(FreeSpace::Max).max(minc);
8042        (minc, maxc)
8043    }
8044
8045    /// 子の内在幅を集約する(ブロックとしての中身。インラインの子は同じ行に並ぶので max は加算・
8046    /// min は最大、ブロックの子は縦に積むので両方とも最大)。
8047    pub(crate) fn children_intrinsic_widths(&self) -> (i32, i32) {
8048        self.children_intrinsic_widths_inner(None)
8049    }
8050
8051    fn children_intrinsic_widths_inner(&self, explicit_dh: Option<i32>) -> (i32, i32) {
8052        let cur_pct_h = explicit_dh.unwrap_or_else(|| {
8053            match parse_length_value(box_style_value_ref(self, "height")) {
8054                Some(LengthValue::Px(px)) => (px - border_box_inner_h(self)).max(0),
8055                _ => -1,
8056            }
8057        });
8058        let _pct_h_guard = PctBaseHGuard::set(cur_pct_h);
8059        // ブロック子は縦に積むため両者とも最大。
8060        let mut inline_max = 0i32; // 現在のインライン連なりの max-content 合計
8061        let mut overall_max = 0i32;
8062        let mut overall_min = 0i32;
8063        for child in &self.children {
8064            // 【2026-10-03】`<br>` は行を締める(前後の行幅を足さない)。sugi-lab.net のヒーローの
8065            // 副題 2 行が 1 行として足され、flex の子の板が Chrome より広くなっていた。
8066            if child.is_inline_line_break() {
8067                overall_max = overall_max.max(inline_max);
8068                inline_max = 0;
8069                continue;
8070            }
8071            match child.box_type {
8072                BoxType::InlineNode(_) | BoxType::InlineBlockNode(_) => {
8073                    // intrinsic_inline_size は inline-block の明示 width を尊重する。
8074                    // 【2026-10-18】inline-block(と置換要素)の左右の margin も行の幅に入る。従来は
8075                    // 含めず、YouTube の中央の再生ボタン(幅 56px・`margin:0 34px`)の包みが 56px に
8076                    // 縮み、ボタンが右へはみ出してクリックが当たらなかった。
8077                    let mut cmax = child.intrinsic_inline_size_ext(1_000_000, true).0;
8078                    let mut cmin = child.intrinsic_inline_size_ext(1, true).0;
8079                    if matches!(child.box_type, BoxType::InlineBlockNode(_)) && !child.is_replaced_inline() {
8080                        let explicit = matches!(parse_length_value(box_style_value_ref(child, "width")), Some(LengthValue::Px(_)));
8081                        // 幅 auto で中身がブロック等なら、中身の集約の方が広いことがある(従来は文字だけを測り 0)。
8082                        if !explicit && !child.is_inline_flex() && !child.is_inline_grid() {
8083                            let (amin, amax) = child.children_intrinsic_widths();
8084                            cmin = cmin.max(amin);
8085                            cmax = cmax.max(amax);
8086                        }
8087                        // intrinsic_inline_size は content の大きさなので余白は常に全部足す。
8088                        let edges = intrinsic_h_edges(child, false);
8089                        cmin += edges;
8090                        cmax += edges;
8091                    } else if child.is_replaced_inline() {
8092                        let m = inline_h_margins(child);
8093                        cmin += m;
8094                        cmax += m;
8095                    }
8096                    inline_max += cmax;
8097                    overall_min = overall_min.max(cmin);
8098                }
8099                _ => {
8100                    let is_float = matches!(box_style_value_ref(child, "float").map(|v| v.trim()), Some("left" | "right" | "inline-start" | "inline-end"))
8101                        && !matches!(box_style_value_ref(child, "position").map(|v| v.trim()), Some("absolute" | "fixed"));
8102                    let clears = matches!(box_style_value_ref(child, "clear").map(|v| v.trim()), Some("left" | "right" | "both" | "inline-start" | "inline-end"));
8103                    if !is_float || clears {
8104                        overall_max = overall_max.max(inline_max);
8105                        inline_max = 0;
8106                    }
8107                    let (cmin, cmax, explicit) = Self::block_child_intrinsic_with_ratio(child, cur_pct_h);
8108                    let (cmin, cmax) = clamp_contribution(child, cmin, cmax, !explicit);
8109                    let edges = intrinsic_h_edges(child, explicit);
8110                    let (cmin, cmax) = (cmin + edges, cmax + edges);
8111                    overall_min = overall_min.max(cmin);
8112                    if is_float {
8113                        inline_max += cmax;
8114                    } else {
8115                        overall_max = overall_max.max(cmax);
8116                    }
8117                }
8118            }
8119        }
8120        overall_max = overall_max.max(inline_max);
8121        (overall_min.max(0), overall_max.max(overall_min).max(0))
8122    }
8123
8124    fn inline_content_intrinsic_size(&self, available_width: i32) -> (i32, i32) {
8125        let styled_node = match &self.box_type {
8126            BoxType::InlineNode(node) | BoxType::InlineBlockNode(node) => Some(*node),
8127            _ => None,
8128        };
8129        let styled_node = if crate::os_lib::css::CUR_WORLD.load(AtomicOrdering::Relaxed) != 0 { None } else { styled_node };
8130        if let Some(node) = styled_node {
8131            if let Ok(cache) = node.intrinsic_size_cache.try_borrow() {
8132                if let Some((ch_avail, ch_pure, ch_trim, w, h)) = *cache {
8133                    if ch_avail == available_width && !ch_pure && ch_trim == self.trim_leading_space {
8134                        return (w, h);
8135                    }
8136                }
8137            }
8138        }
8139        let res = self.inline_content_intrinsic_size_uncached(available_width);
8140        if let Some(node) = styled_node {
8141            if let Ok(mut cache) = node.intrinsic_size_cache.try_borrow_mut() {
8142                *cache = Some((available_width, false, self.trim_leading_space, res.0, res.1));
8143            }
8144        }
8145        res
8146    }
8147
8148    fn inline_content_intrinsic_size_uncached(&self, available_width: i32) -> (i32, i32) {
8149        match &self.box_type {
8150            BoxType::InlineNode(node) | BoxType::InlineBlockNode(node) => {
8151                if let Some(size) = get_replaced_element_size_in(node, Some(available_width)) {
8152                    return size;
8153                }
8154                match &node.node.node_type {
8155                    NodeType::Text(text) => {
8156                        let font_size = node
8157                            .value_ref("font-size")
8158                            .and_then(parse_font_size_u32)
8159                            .unwrap_or(16);
8160                        let line_height_val = node.value_ref("line-height");
8161                        let line_height = parse_line_height(line_height_val, font_size);
8162                        let ws_str = node.value_ref("white-space").unwrap_or("");
8163                        let pre_wrap = matches!(ws_str, "pre-wrap" | "pre-line");
8164                        let wb_str = node.value_ref("word-break");
8165                        let break_all = matches!(wb_str, Some("break-all"));
8166                        // CSS Text 3 §5.5: min-content 計測時は、`anywhere` のみ soft wrap opportunity を考慮し、
8167                        // `break-word` は `normal` と同様に単語内での折り返しを考慮しない。
8168                        let ow_str = node.value_ref("overflow-wrap");
8169                        let ww_str = node.value_ref("word-wrap");
8170                        let is_anywhere = matches!(ow_str, Some("anywhere"))
8171                            || matches!(ww_str, Some("anywhere"));
8172                        let is_break_word = matches!(ow_str, Some("break-word"))
8173                            || matches!(ww_str, Some("break-word"))
8174                            || matches!(wb_str, Some("break-word"));
8175                        let overflow_wrap = if available_width <= 100 {
8176                            is_anywhere
8177                        } else {
8178                            is_anywhere || is_break_word
8179                        };
8180                        // 描画側と同じ規則で空白を畳んでから測る(2026-09-26。
8181                        // 畳まずに測ると HTML の字下げの分だけ箱が広く・高くなる)。
8182                        let text = &crate::os_lib::layout::line_break::collapse_white_space(
8183                            text,
8184                            ws_str,
8185                        );
8186                        let text = if self.trim_leading_space {
8187                            text.strip_prefix(' ').unwrap_or(text)
8188                        } else {
8189                            text.as_str()
8190                        };
8191                        let (fam, weight) = text_font_of(node);
8192                        let (w, h) = crate::kernel::vector_font::get_vector_string_wrapped_size_family(
8193                            text,
8194                            font_size,
8195                            available_width.max(1) as u32,
8196                            0, // ls
8197                            0, // ws
8198                            break_all,
8199                            overflow_wrap,
8200                            pre_wrap,
8201                            fam,
8202                            weight,
8203                        );
8204                        let lines = h as i32 / (font_size as i32 + 4).max(1);
8205                        (w as i32, lines * line_height)
8206                    }
8207                    NodeType::Element { .. } if pseudo_content_size(node).is_some() => {
8208                        pseudo_content_size(node).unwrap_or((0, 0))
8209                    }
8210                    NodeType::Element { .. } => {
8211                        let mut max_line_w = 0i32;
8212                        let mut total_h = 0i32;
8213                        let mut current_line_w = 0i32;
8214                        let mut current_line_h = 0i32;
8215                        // `layout_inline` の子の並べ方と同じく、畳まれた空白の幅を数える(2026-11-18)。
8216                        let mut after_space: Option<bool> = None;
8217                        for child in &self.children {
8218                            // フロー外(absolute / fixed)の子は内在寸法に入れない(上の `intrinsic_inline_size_ext_uncached` と同じ。2026-11-30)。
8219                            if !matches!(&child.box_type, BoxType::InlineNode(n) if matches!(n.node.node_type, NodeType::Text(_)))
8220                                && Self::child_is_out_of_flow(child)
8221                            {
8222                                continue;
8223                            }
8224                            if child.is_inline_line_break() {
8225                                if current_line_w > max_line_w {
8226                                    max_line_w = current_line_w;
8227                                }
8228                                total_h += current_line_h.max(20);
8229                                current_line_w = 0;
8230                                current_line_h = 0;
8231                                after_space = Some(true);
8232                                continue;
8233                            }
8234                            let (raw_w, ch) = inline_child_outer_size(child, available_width.max(1));
8235                            let (mut cw, _, mut ends_space) = if matches!(child.box_type, BoxType::InlineNode(_)) {
8236                                child.inline_child_space_adjust(raw_w, after_space)
8237                            } else {
8238                                (raw_w, false, false)
8239                            };
8240                            if current_line_w > 0 && current_line_w + cw > available_width.max(1) {
8241                                if current_line_w > max_line_w {
8242                                    max_line_w = current_line_w;
8243                                }
8244                                total_h += current_line_h.max(20);
8245                                current_line_w = 0;
8246                                current_line_h = 0;
8247                                if matches!(child.box_type, BoxType::InlineNode(_)) {
8248                                    (cw, _, ends_space) = child.inline_child_space_adjust(raw_w, Some(true));
8249                                }
8250                            }
8251                            if child.is_collapsible_space() || ends_space {
8252                                after_space = Some(true);
8253                            } else if !child.is_blank_inline() {
8254                                after_space = Some(false);
8255                            }
8256                            current_line_w += cw;
8257                            if ch > current_line_h {
8258                                current_line_h = ch;
8259                            }
8260                        }
8261                        if current_line_w > max_line_w {
8262                            max_line_w = current_line_w;
8263                        }
8264                        total_h += current_line_h.max(20);
8265                        if total_h == 0 {
8266                            let font_size = node
8267                                .value_ref("font-size")
8268                                .and_then(parse_font_size_u32)
8269                                .unwrap_or(16);
8270                            return (8, (font_size as i32 + 4).max(12));
8271                        }
8272                        (max_line_w.max(1), total_h.max(1))
8273                    }
8274                }
8275            }
8276            _ => (0, 0),
8277        }
8278    }
8279
8280    fn is_inline_line_break(&self) -> bool {
8281        match &self.box_type {
8282            BoxType::InlineNode(node) | BoxType::InlineBlockNode(node) => {
8283                matches!(&node.node.node_type, NodeType::Element { tag_name, .. } if tag_name == "br")
8284            }
8285            _ => false,
8286        }
8287    }
8288
8289    fn apply_box_model_styles_with_base(&mut self, containing_width: i32) {
8290        let pct_w = GRID_PCT_BASE_W.swap(-1, AtomicOrdering::Relaxed);
8291        let eff_w = if pct_w >= 0 { pct_w } else { containing_width };
8292        // 【2026-09-26 バグ修正】従来は Block/InlineBlock 以外で即 return しており、
8293        // flex・grid・table コンテナの margin/padding/border が常に 0 だった
8294        // (`layout_flex`/`layout_grid`/`layout_table` は値が入る前提で計算している)。
8295        // 表の行は余白を持たないので対象外。セルは padding と border を持つ(margin は効かない。CSS 2.1 §17.5)。
8296        // 【2026-11-28】従来はセルも対象外で、表レイアウト側(`layout_table`)は `cell.dimensions.padding` を読むだけだったため、
8297        // セルの padding・border が常に 0 だった(WPT css-flexbox table-as-item-cross-size: `td{padding:23px}` の表の高さが 0)。
8298        let is_cell = matches!(self.box_type, BoxType::TableCellNode(_));
8299        let node = match &self.box_type {
8300            BoxType::BlockNode(n)
8301            | BoxType::InlineBlockNode(n)
8302            | BoxType::FlexNode(n)
8303            | BoxType::GridNode(n)
8304            | BoxType::TableNode(n)
8305            | BoxType::TableCellNode(n) => n,
8306            BoxType::InlineNode(n) if self.is_replaced_inline() => n,
8307            _ => return,
8308        };
8309        let (m, p, b) = style_box_edges(node, eff_w, &self.dimensions);
8310        self.dimensions.margin = if is_cell { EdgeSizes::default() } else { m };
8311        self.dimensions.padding = p;
8312        self.dimensions.border = b;
8313    }
8314
8315    fn apply_box_model_styles(&mut self) {
8316        self.apply_box_model_styles_with_base(0);
8317    }
8318}
8319