Skip to main content

atmos/os_lib/layout/
boxmodel.rs

1// 分割: layout.rs より機械的に移動(2026-07-16 リファクタ フェーズ4)。
2// ロジック不変。可視性のみ pub(crate) へ昇格し、親が pub(crate) use で再エクスポート。
3use super::*;
4
5/// margin の左右が auto か(`margin:auto` / `margin:0 auto` / `margin-left:auto`)。
6pub(crate) fn margin_is_h_auto(node: &StyledNode) -> bool {
7    if node
8        .value_ref("margin-left")
9        .map(|v| v.trim() == "auto")
10        .unwrap_or(false)
11    {
12        return true;
13    }
14    if let Some(m) = node.value_ref("margin") {
15        let w = crate::os_lib::css::CUR_WORLD.load(AtomicOrdering::Relaxed);
16        if w != 0 {
17            // 縦書きの世界: 論理の左(inline-start)が指す物理の辺をショートハンドから取る。
18            return shorthand_side_token(m, crate::os_lib::css::world_phys_side(w, 3)) == Some("auto");
19        }
20        let mut it = m.split_whitespace();
21        let first = it.next();
22        let second = it.next();
23        let lr = second.or(first);
24        return lr.map(|s| s == "auto").unwrap_or(false);
25    }
26    false
27}
28
29/// 1〜4 値の辺ショートハンド(margin/padding/inset 等)から物理の辺 `idx`(0=top,1=right,2=bottom,3=left)の値を取る。
30pub(crate) fn shorthand_side_token(m: &str, idx: usize) -> Option<&str> {
31    let mut toks = [""; 4];
32    let mut count = 0;
33    for t in m.split_whitespace().take(4) {
34        toks[count] = t;
35        count += 1;
36    }
37    match count {
38        1 => Some(toks[0]),
39        2 => Some(if idx == 0 || idx == 2 { toks[0] } else { toks[1] }),
40        3 => Some(match idx {
41            0 => toks[0],
42            2 => toks[2],
43            _ => toks[1],
44        }),
45        4 => Some(toks[idx]),
46        _ => None,
47    }
48}
49
50/// flex アイテムの主軸方向の auto margin 個数を返す(row: left/right、column: top/bottom)。
51/// `margin-<side>:auto` 明示、または `margin` ショートハンドの該当辺が auto のとき数える。
52pub(crate) fn box_main_auto_margins(b: &LayoutBox, is_row: bool) -> (bool, bool) {
53    fn side_auto(b: &LayoutBox, side: &str, short_idx_4: usize) -> bool {
54        if let Some(v) = box_style_value_ref(b, side) {
55            return v.trim() == "auto";
56        }
57        if let Some(m) = box_style_value_ref(b, "margin") {
58            let w = crate::os_lib::css::CUR_WORLD.load(AtomicOrdering::Relaxed);
59            let short_idx_4 = if w != 0 { crate::os_lib::css::world_phys_side(w, short_idx_4) } else { short_idx_4 };
60            let mut toks = [""; 4];
61            let mut count = 0;
62            for tok in m.split_whitespace().take(4) {
63                toks[count] = tok;
64                count += 1;
65            }
66            // margin ショートハンド: 1=all, 2=(v,h), 3=(t,h,b), 4=(t,r,b,l)
67            let val = match count {
68                1 => Some(toks[0]),
69                2 => {
70                    // top/bottom=0, left/right=1
71                    if short_idx_4 == 0 || short_idx_4 == 2 {
72                        Some(toks[0])
73                    } else {
74                        Some(toks[1])
75                    }
76                }
77                3 => match short_idx_4 {
78                    0 => Some(toks[0]),
79                    2 => Some(toks[2]),
80                    _ => Some(toks[1]), // left/right
81                },
82                4 => Some(toks[short_idx_4]),
83                _ => None,
84            };
85            return val.map(|s| s == "auto").unwrap_or(false);
86        }
87        false
88    }
89    if is_row {
90        // top=0,right=1,bottom=2,left=3
91        (
92            side_auto(b, "margin-left", 3),
93            side_auto(b, "margin-right", 1),
94        )
95    } else {
96        (
97            side_auto(b, "margin-top", 0),
98            side_auto(b, "margin-bottom", 2),
99        )
100    }
101}
102
103/// 要素の position 値(小文字化。未指定は "static")。
104/// `position` の値(既知の 5 種。それ以外・未指定は "static")。
105/// 【2026-10-19】レイアウトの最頻出の呼び出しの 1 つで、従来は毎回小文字化した `String` を作っていた。
106pub(crate) fn box_position(b: &LayoutBox) -> &'static str {
107    let Some(v) = box_style_value_ref(b, "position") else { return "static" };
108    let v = v.trim();
109    if v.eq_ignore_ascii_case("relative") {
110        "relative"
111    } else if v.eq_ignore_ascii_case("absolute") {
112        "absolute"
113    } else if v.eq_ignore_ascii_case("fixed") {
114        "fixed"
115    } else if v.eq_ignore_ascii_case("sticky") {
116        "sticky"
117    } else {
118        "static"
119    }
120}
121
122/// 要素が `transform`/`perspective`/`filter`/`backdrop-filter`/`contain:paint|layout|strict|content`
123/// によって子孫の `position:absolute`/`fixed` の包含ブロックを作るか(CSS Transforms 1 §2、
124/// Filter Effects 1、CSS Containment 1 §3)。
125pub fn styled_establishes_fixed_cb(styled: &StyledNode) -> bool {
126    let non_none = |prop: &str| {
127        styled.value_ref(prop).is_some_and(|v| {
128            let t = v.trim();
129            !t.is_empty() && !t.eq_ignore_ascii_case("none")
130        })
131    };
132    if non_none("transform")
133        || non_none("perspective")
134        || non_none("filter")
135        || non_none("backdrop-filter")
136    {
137        return true;
138    }
139    if styled.value_ref("contain").is_some_and(|v| {
140        v.split_whitespace().any(|tok| {
141            tok.eq_ignore_ascii_case("paint")
142                || tok.eq_ignore_ascii_case("layout")
143                || tok.eq_ignore_ascii_case("strict")
144                || tok.eq_ignore_ascii_case("content")
145        })
146    }) {
147        return true;
148    }
149    styled.value_ref("will-change").is_some_and(|v| {
150        v.split(|c: char| c == ',' || c.is_ascii_whitespace()).any(|tok| {
151            tok.eq_ignore_ascii_case("transform")
152                || tok.eq_ignore_ascii_case("perspective")
153                || tok.eq_ignore_ascii_case("filter")
154                || tok.eq_ignore_ascii_case("backdrop-filter")
155                || tok.eq_ignore_ascii_case("contain")
156                || tok.eq_ignore_ascii_case("scale")
157                || tok.eq_ignore_ascii_case("rotate")
158                || tok.eq_ignore_ascii_case("translate")
159        })
160    })
161}
162
163/// レイアウト箱が `transform` 等により `position:fixed` の子孫の包含ブロックを作るか。
164pub(crate) fn box_establishes_fixed_cb(b: &LayoutBox) -> bool {
165    let styled = match &b.box_type {
166        BoxType::BlockNode(s)
167        | BoxType::InlineNode(s)
168        | BoxType::InlineBlockNode(s)
169        | BoxType::FlexNode(s)
170        | BoxType::GridNode(s)
171        | BoxType::TableNode(s)
172        | BoxType::TableRowGroupNode(s)
173        | BoxType::TableRowNode(s)
174        | BoxType::TableCellNode(s) => *s,
175        BoxType::AnonymousBlock => return false,
176    };
177    styled_establishes_fixed_cb(styled)
178}
179
180/// レイアウト箱が `position:absolute` の子孫の包含ブロックを作るか(位置指定要素、または
181/// `transform` 等で包含ブロックを作る要素)。
182pub(crate) fn box_establishes_abs_cb(b: &LayoutBox) -> bool {
183    matches!(box_position(b), "relative" | "absolute" | "fixed" | "sticky")
184        || box_establishes_fixed_cb(b)
185}
186
187/// `direction:rtl` のとき論理方向キーワード(inline-start/inline-end)を物理方向
188/// (left/right)へ解決する。`direction` は継承プロパティとして既に解決済みのため、
189/// このボックス自身の `specified_values` を見るだけで祖先からの継承値も反映される。
190pub(crate) fn box_is_rtl(b: &LayoutBox) -> bool {
191    box_style_value_ref(b, "direction")
192        .map(|v| v.trim().eq_ignore_ascii_case("rtl"))
193        .unwrap_or(false)
194}
195
196/// 要素の float 値。"left" / "right"(物理方向は direction に関わらず不変)に加え、
197/// CSS Logical Properties の `inline-start`/`inline-end`(direction に応じて
198/// left/right へ解決される)にも対応する。それ以外は "none" 扱い。
199pub(crate) fn box_float(b: &LayoutBox) -> &'static str {
200    let Some(raw) = box_style_value_ref(b, "float") else {
201        return "none";
202    };
203    let v = raw.trim();
204    if v.eq_ignore_ascii_case("none") || v.is_empty() {
205        "none"
206    } else if v.eq_ignore_ascii_case("left") {
207        "left"
208    } else if v.eq_ignore_ascii_case("right") {
209        "right"
210    } else if v.eq_ignore_ascii_case("inline-start") {
211        if box_is_rtl(b) { "right" } else { "left" }
212    } else if v.eq_ignore_ascii_case("inline-end") {
213        if box_is_rtl(b) { "left" } else { "right" }
214    } else {
215        "none"
216    }
217}
218
219/// 要素の clear 値。"left" / "right" / "both" に加え、`float` と同様に
220/// `inline-start`/`inline-end` の論理方向キーワードにも対応する。
221pub(crate) fn box_clear(b: &LayoutBox) -> &'static str {
222    let Some(raw) = box_style_value_ref(b, "clear") else {
223        return "none";
224    };
225    let v = raw.trim();
226    if v.eq_ignore_ascii_case("none") || v.is_empty() {
227        "none"
228    } else if v.eq_ignore_ascii_case("left") {
229        "left"
230    } else if v.eq_ignore_ascii_case("right") {
231        "right"
232    } else if v.eq_ignore_ascii_case("both") {
233        "both"
234    } else if v.eq_ignore_ascii_case("inline-start") {
235        if box_is_rtl(b) { "right" } else { "left" }
236    } else if v.eq_ignore_ascii_case("inline-end") {
237        if box_is_rtl(b) { "left" } else { "right" }
238    } else {
239        "none"
240    }
241}
242
243/// 長さプロパティを base(%解決の基準)で解決。auto/未指定は None。
244pub(crate) fn box_len(b: &LayoutBox, prop: &str, base: i32) -> Option<i32> {
245    let raw = box_style_value_ref(b, prop);
246    if raw.is_some_and(is_stretch_value) {
247        return stretch_len(b, prop, base);
248    }
249    parse_length_value(raw).and_then(|lv| resolve_length_value(lv, base))
250}
251
252/// サイズの値が `stretch`(CSS Sizing 4)か。接頭辞付きの `-webkit-fill-available` なども同じ意味。
253pub(crate) fn is_stretch_value(v: &str) -> bool {
254    let t = v.trim();
255    t.eq_ignore_ascii_case("stretch")
256        || t.eq_ignore_ascii_case("-webkit-fill-available")
257        || t.eq_ignore_ascii_case("-moz-available")
258        || t.eq_ignore_ascii_case("fill-available")
259}
260
261/// `stretch` を「`base`(包含ブロックの大きさ)から自分の margin を引いた margin box で満たす」長さへ解く。
262/// 戻りは指定値の流儀(`box-sizing:content-box` なら border・padding を引いた中身の大きさ。border-box ならそのまま)で、
263/// 呼び出し側が `border_box_inner_*` を引く既存の扱いにそのまま乗る。高さは基準が確定していない(0 以下)なら None(auto 扱い)。
264/// 【2026-11-30 TODO S2】flex・grid の項目の `width:stretch`(`-webkit-fill-available`)。従来は値が解けず auto 扱いだった。
265fn stretch_len(b: &LayoutBox, prop: &str, base: i32) -> Option<i32> {
266    let horizontal = prop.ends_with("width");
267    if !horizontal && base <= 0 {
268        return None;
269    }
270    let d = &b.dimensions;
271    let (margin, edges) = if horizontal {
272        (d.margin.left + d.margin.right, d.padding.left + d.padding.right + d.border.left + d.border.right)
273    } else {
274        (d.margin.top + d.margin.bottom, d.padding.top + d.padding.bottom + d.border.top + d.border.bottom)
275    };
276    let border_box = box_style_value_ref(b, "box-sizing").is_some_and(|v| v.trim().eq_ignore_ascii_case("border-box"));
277    let total = base - margin;
278    Some(if border_box { total } else { total - edges }.max(0))
279}
280
281/// `top`/`right`/`bottom`/`left`(`side` はその名前そのもの)を解決する。個別の longhand が
282/// 明示されていればそれを優先し、無ければ `inset` ショートハンド(margin と同じ1〜4値展開)
283/// から対応する辺を取り出してフォールバックする。
284pub(crate) fn box_inset_len(b: &LayoutBox, side: &str, base: i32) -> Option<i32> {
285    if let Some(v) = box_len(b, side, base) {
286        return Some(v);
287    }
288    let side_idx = match side {
289        "top" => 0,
290        "right" => 1,
291        "bottom" => 2,
292        "left" => 3,
293        _ => return None,
294    };
295    let inset = box_style_value_ref(b, "inset")?;
296    let w = crate::os_lib::css::CUR_WORLD.load(AtomicOrdering::Relaxed);
297    let side_idx = if w != 0 { crate::os_lib::css::world_phys_side(w, side_idx) } else { side_idx };
298    let mut toks = [""; 4];
299    let mut count = 0;
300    for t in inset.split_whitespace().take(4) {
301        toks[count] = t;
302        count += 1;
303    }
304    let tok = match count {
305        1 => Some(toks[0]),
306        2 => match side_idx {
307            0 | 2 => Some(toks[0]),
308            _ => Some(toks[1]),
309        },
310        3 => match side_idx {
311            0 => Some(toks[0]),
312            2 => Some(toks[2]),
313            _ => Some(toks[1]),
314        },
315        4 => Some(toks[side_idx]),
316        _ => None,
317    }?;
318    parse_length_value(Some(tok)).and_then(|lv| resolve_length_value(lv, base))
319}
320
321/// `name(...)` の括弧内スライスを取り出す(ヒープ確保ゼロ)。
322pub(crate) fn extract_fn_args_ref<'a>(s: &'a str, name: &str) -> Option<&'a str> {
323    let mut rest = s;
324    while let Some(pos) = rest.find(name) {
325        let after_name = rest.get(pos + name.len()..)?;
326        if let Some(after_paren) = after_name.strip_prefix('(') {
327            let end = after_paren.find(')')?;
328            return after_paren.get(..end);
329        }
330        rest = after_name;
331    }
332    None
333}
334
335/// `name(...)` の括弧内文字列を取り出す(`string_slice` lint 回避で str::get のみ使用)。
336pub(crate) fn extract_fn_args(s: &str, name: &str) -> Option<String> {
337    extract_fn_args_ref(s, name).map(String::from)
338}
339
340/// translate の 1 引数(px / % / rem / vh / vw)を base 基準で解決。
341/// 以前は `px`/`%` の2種のみ対応で、それ以外の単位(`rem`/`vh`/`vw`等)は
342/// `t.strip_suffix("px").unwrap_or(t)`が単位付き文字列をそのまま数値
343/// パースへ渡してしまい、静かに`0`へフォールバックしていた——単に
344/// 「対応外」なのではなく、`transform: translate(1rem, 10px)`のような
345/// 式で意図した移動量が消えて要素が動かなくなる、実害のあるバグだった。
346/// `em`(要素自身の算出フォントサイズ基準)はこの関数の引数だけでは
347/// 算出フォントサイズを解決できないため対象外のまま
348/// (`font-size`の継承解決には別途プロパティ探索が必要で、誤った既定値
349/// 〔例:常に16px〕を当てはめると`rem`と区別が付かない別の壊れ方になる
350/// リスクがあり見送り)。2026-07-17 発見・実装。
351pub(crate) fn resolve_translate_len(tok: &str, base: i32) -> i32 {
352    let t = tok.trim();
353    if let Some(p) = t.strip_suffix('%') {
354        return p
355            .trim()
356            .parse::<f32>()
357            .map(|v| (v / 100.0 * base as f32) as i32)
358            .unwrap_or(0);
359    }
360    if let Some(p) = t.strip_suffix("rem") {
361        return p.trim().parse::<f32>().map(|v| (v * crate::os_lib::css::units::root_font_px()) as i32).unwrap_or(0);
362    }
363    if let Some(p) = t.strip_suffix("vh") {
364        let h = super::values::VIEWPORT_HINT_H.load(core::sync::atomic::Ordering::Relaxed);
365        return p
366            .trim()
367            .parse::<f32>()
368            .map(|v| (v / 100.0 * h as f32) as i32)
369            .unwrap_or(0);
370    }
371    if let Some(p) = t.strip_suffix("vw") {
372        let w = super::values::VIEWPORT_HINT_W.load(core::sync::atomic::Ordering::Relaxed);
373        return p
374            .trim()
375            .parse::<f32>()
376            .map(|v| (v / 100.0 * w as f32) as i32)
377            .unwrap_or(0);
378    }
379    let n = t.strip_suffix("px").unwrap_or(t).trim();
380    n.parse::<f32>().map(|v| v as i32).unwrap_or(0)
381}
382
383/// `transform` から translate オフセット (dx, dy) を取り出す。% は要素自身の (w,h) 基準。
384/// translate(x[,y]) / translateX(x) / translateY(y) に対応(scale/rotate は未対応・無視)。
385pub(crate) fn box_translate(b: &LayoutBox) -> (i32, i32) {
386    let Some(t) = box_style_value_ref(b, "transform") else {
387        return (0, 0);
388    };
389    let w = b.dimensions.content.width;
390    let h = b.dimensions.content.height;
391    if let Some(args) = extract_fn_args_ref(t, "translate") {
392        let mut parts = args.split(',');
393        let dx = parts
394            .next()
395            .map(|a| resolve_translate_len(a, w))
396            .unwrap_or(0);
397        let dy = parts
398            .next()
399            .map(|a| resolve_translate_len(a, h))
400            .unwrap_or(0);
401        return (dx, dy);
402    }
403    let dx = extract_fn_args_ref(t, "translateX")
404        .map(|a| resolve_translate_len(a, w))
405        .unwrap_or(0);
406    let dy = extract_fn_args_ref(t, "translateY")
407        .map(|a| resolve_translate_len(a, h))
408        .unwrap_or(0);
409    (dx, dy)
410}
411
412/// グリッド占有 (rowspan/colspan 解決用) のヘルパ。
413pub(crate) fn occ_is(occ: &[Vec<bool>], r: usize, c: usize) -> bool {
414    occ.get(r)
415        .and_then(|row| row.get(c))
416        .copied()
417        .unwrap_or(false)
418}
419pub(crate) fn occ_mark(occ: &mut Vec<Vec<bool>>, r: usize, c: usize) {
420    while occ.len() <= r {
421        occ.push(Vec::new());
422    }
423    let row = &mut occ[r];
424    while row.len() <= c {
425        row.push(false);
426    }
427    row[c] = true;
428}
429
430// レイアウトツリーの構築と計算