Skip to main content

atmos/os_lib/css/
shorthand.rs

1// 分割: css.rs より機械的に移動(2026-07-16 リファクタ フェーズ3)。
2// ロジック不変。可視性のみ pub(crate) へ昇格し、親が pub(crate) use で再エクスポート。
3use super::*;
4
5pub(crate) fn parse_border_shorthand(s: &str) -> (Option<String>, Option<String>, Option<String>) {
6    let mut width = None;
7    let mut style = None;
8    let mut color = None;
9
10    for token in split_top_level_ws(s) {
11        let t = token.trim();
12        if t.is_empty() {
13            continue;
14        }
15        let t_lower = t.to_lowercase();
16
17        // 1. スタイルの判定。`BorderStyle` enum は None/Solid/Dashed/Dotted/Double の
18        // 5種のみ対応(groove/ridge/inset/outset の立体的な描画は非対応)なので、
19        // それらのキーワードは意味的に近い値へ縮退させる: `hidden`→`none`(描画上等価)、
20        // `groove`/`ridge`/`inset`/`outset`→`solid`(何もマッチせず境界線ごと消えてしまう
21        // よりは、実線として見える方が実害が小さいという判断)。
22        if matches!(
23            t_lower.as_str(),
24            "none" | "solid" | "dashed" | "dotted" | "double"
25        ) {
26            style = Some(t_lower);
27            continue;
28        }
29        if t_lower == "hidden" {
30            style = Some(String::from("none"));
31            continue;
32        }
33        if matches!(t_lower.as_str(), "groove" | "ridge" | "inset" | "outset") {
34            style = Some(String::from("solid"));
35            continue;
36        }
37
38        // 2. 幅の判定
39        if t_lower.ends_with("px")
40            || t_lower.parse::<f32>().is_ok()
41            || t_lower == "thin"
42            || t_lower == "medium"
43            || t_lower == "thick"
44        {
45            let val = match t_lower.as_str() {
46                "thin" => String::from("1px"),
47                "medium" => String::from("3px"),
48                "thick" => String::from("5px"),
49                _ => t_lower,
50            };
51            width = Some(val);
52            continue;
53        }
54
55        // 3. 色の判定
56        if t_lower.starts_with('#')
57            || t_lower.starts_with("rgb")
58            || t_lower.starts_with("hsl")
59            || t_lower == "currentcolor"
60            || parse_color(&t_lower).is_some()
61        {
62            color = Some(t_lower);
63            continue;
64        }
65    }
66
67    (width, style, color)
68}
69
70/// CSS-wide keywords(`initial`/`inherit`/`unset`/`revert`)を持つプロパティを
71/// specified_values から取り除く。取り除いた後の挙動:
72/// - 継承プロパティ(`INHERITED_PROPS`): 呼び出し側の継承伝搬処理(
73///   `if !specified_values.contains_key(k)`)が自然に親の値で埋めるため、
74///   `inherit`/`unset` の意味的にも正しい結果になる。
75/// - 非継承プロパティ: 親の全プロパティを参照する仕組みがこの処理系には無いため、
76///   `inherit` を厳密には解決できず「未指定(=各所のデフォルト値)」へフォールバックする
77///   簡略実装(`initial`/`revert` も同様に扱う)。値を素通りさせて壊れた文字列
78///   (例: `color:inherit` がそのまま色として解釈されようとして失敗する)を残すよりは
79///   安全という判断。
80pub(crate) fn strip_css_wide_keywords(specified_values: &mut BTreeMap<String, String>) {
81    let keys_to_remove: alloc::vec::Vec<String> = specified_values
82        .iter()
83        .filter(|(_, v)| {
84            matches!(
85                v.trim().to_ascii_lowercase().as_str(),
86                "initial" | "inherit" | "unset" | "revert" | "revert-layer"
87            )
88        })
89        .map(|(k, _)| k.clone())
90        .collect();
91    for k in keys_to_remove {
92        specified_values.remove(&k);
93    }
94}
95
96/// `all: unset/initial/revert`(すべてのプロパティを一括リセットするショートハンド)を解決する。
97/// **簡略化**: 本来はカスケードの中で `all` より後に書かれた個別プロパティだけが生き残るが、
98/// この処理系はプロパティ名ごとに独立してカスケード解決した後の `specified_values` しか
99/// 見えないため、そこまで厳密な順序判定はできない。実用上ほとんどの利用パターン
100/// (`.reset{all:unset}` のように単独で使う)をカバーする近似として、`all` が
101/// CSS-wide keyword なら、カスタムプロパティ(`--` 始まり)と `all` 自身を除く
102/// 全プロパティを削除する。
103pub(crate) fn resolve_all_shorthand(specified_values: &mut BTreeMap<String, String>) {
104    let is_reset = specified_values
105        .get("all")
106        .map(|v| {
107            matches!(
108                v.trim().to_ascii_lowercase().as_str(),
109                "unset" | "initial" | "revert"
110            )
111        })
112        .unwrap_or(false);
113    if !is_reset {
114        return;
115    }
116    let keys_to_remove: alloc::vec::Vec<String> = specified_values
117        .keys()
118        .filter(|k| *k != "all" && !k.starts_with("--"))
119        .cloned()
120        .collect();
121    for k in keys_to_remove {
122        specified_values.remove(&k);
123    }
124    specified_values.remove("all");
125}
126
127/// `margin-block`/`margin-inline`/`padding-block`/`padding-inline`/`inset-block`/
128/// `inset-inline`(1〜2値。1番目が start、2番目(省略時は1番目と同値)が end)を
129/// `-start`/`-end` の longhand へ展開する。既に longhand 側が個別指定されていれば
130/// そちらを優先し、shorthand 側は無視する(`resolve_logical_properties` の
131/// 「物理プロパティが既にあれば論理プロパティを無視する」規則と同じ優先順位の考え方)。
132pub(crate) fn expand_logical_box_shorthands(specified_values: &mut BTreeMap<String, String>) {
133    const SHORTHANDS: &[(&str, &str, &str)] = &[
134        ("margin-block", "margin-block-start", "margin-block-end"),
135        ("margin-inline", "margin-inline-start", "margin-inline-end"),
136        ("padding-block", "padding-block-start", "padding-block-end"),
137        ("padding-inline", "padding-inline-start", "padding-inline-end"),
138        ("inset-block", "inset-block-start", "inset-block-end"),
139        ("inset-inline", "inset-inline-start", "inset-inline-end"),
140    ];
141    for &(shorthand, start_prop, end_prop) in SHORTHANDS {
142        if let Some(v) = specified_values.get(shorthand).cloned() {
143            let toks: Vec<&str> = v.split_whitespace().collect();
144            if let Some(&start) = toks.first() {
145                let end = toks.get(1).copied().unwrap_or(start);
146                specified_values
147                    .entry(String::from(start_prop))
148                    .or_insert_with(|| String::from(start));
149                specified_values
150                    .entry(String::from(end_prop))
151                    .or_insert_with(|| String::from(end));
152            }
153        }
154    }
155}
156
157/// CSS 論理プロパティ(`margin-inline-start` 等)を物理プロパティ(`margin-left` 等)へ
158/// 変換する。この処理系は縦書き(`writing-mode`)に対応していないため、block 軸は常に
159/// 縦方向・inline 軸は常に横方向として扱う簡略実装。`direction:rtl` の場合のみ
160/// inline-start/end を right/left(既定は left/right)へ入れ替える。
161/// 対応する物理プロパティが既に指定されている場合は論理プロパティを無視する
162/// (同じ要素内で両方書かれた場合、物理プロパティを優先する簡易な優先順位)。
163pub(crate) fn resolve_logical_properties(specified_values: &mut BTreeMap<String, String>) {
164    // 高速パス: 論理プロパティになり得るキーワードを含まなければ即リターン(毎要素数十回の String 確保を回避)
165    let has_logical = specified_values.keys().any(|k| {
166        k.contains("block") || k.contains("inline") || k.starts_with("inset")
167    });
168    if !has_logical {
169        return;
170    }
171
172    let rtl = specified_values
173        .get("direction")
174        .map(|v| v.trim().eq_ignore_ascii_case("rtl"))
175        .unwrap_or(false);
176
177    // (プロパティ種別プレフィックス, block-start, block-end, inline-start物理名, inline-end物理名)
178    const PREFIXES: &[(&str, &str, &str)] = &[
179        ("margin", "margin-top", "margin-bottom"),
180        ("padding", "padding-top", "padding-bottom"),
181        ("border", "border-top", "border-bottom"),
182    ];
183    for &(prefix, phys_top, phys_bottom) in PREFIXES {
184        let logical_bs = match prefix {
185            "margin" => "margin-block-start",
186            "padding" => "padding-block-start",
187            _ => "border-block-start",
188        };
189        let logical_be = match prefix {
190            "margin" => "margin-block-end",
191            "padding" => "padding-block-end",
192            _ => "border-block-end",
193        };
194        let (logical_is, phys_is) = match (prefix, rtl) {
195            ("margin", false) => ("margin-inline-start", "margin-left"),
196            ("margin", true) => ("margin-inline-start", "margin-right"),
197            ("padding", false) => ("padding-inline-start", "padding-left"),
198            ("padding", true) => ("padding-inline-start", "padding-right"),
199            (_, false) => ("border-inline-start", "border-left"),
200            (_, true) => ("border-inline-start", "border-right"),
201        };
202        let (logical_ie, phys_ie) = match (prefix, rtl) {
203            ("margin", false) => ("margin-inline-end", "margin-right"),
204            ("margin", true) => ("margin-inline-end", "margin-left"),
205            ("padding", false) => ("padding-inline-end", "padding-right"),
206            ("padding", true) => ("padding-inline-end", "padding-left"),
207            (_, false) => ("border-inline-end", "border-right"),
208            (_, true) => ("border-inline-end", "border-left"),
209        };
210        let pairs = [
211            (logical_bs, phys_top),
212            (logical_be, phys_bottom),
213            (logical_is, phys_is),
214            (logical_ie, phys_ie),
215        ];
216        for (logical, physical) in pairs {
217            if specified_values.contains_key(physical) {
218                continue;
219            }
220            if let Some(v) = specified_values.get(logical).cloned() {
221                specified_values.insert(String::from(physical), v);
222            }
223        }
224    }
225
226    // border-{block,inline}-{start,end}-{width,style,color}
227    const SUFFIXES: &[&str] = &["width", "style", "color"];
228    for &suffix in SUFFIXES {
229        let (logical_bs, phys_top) = match suffix {
230            "width" => ("border-block-start-width", "border-top-width"),
231            "style" => ("border-block-start-style", "border-top-style"),
232            _ => ("border-block-start-color", "border-top-color"),
233        };
234        let (logical_be, phys_bottom) = match suffix {
235            "width" => ("border-block-end-width", "border-bottom-width"),
236            "style" => ("border-block-end-style", "border-bottom-style"),
237            _ => ("border-block-end-color", "border-bottom-color"),
238        };
239        let (logical_is, phys_is) = match (suffix, rtl) {
240            ("width", false) => ("border-inline-start-width", "border-left-width"),
241            ("width", true) => ("border-inline-start-width", "border-right-width"),
242            ("style", false) => ("border-inline-start-style", "border-left-style"),
243            ("style", true) => ("border-inline-start-style", "border-right-style"),
244            (_, false) => ("border-inline-start-color", "border-left-color"),
245            (_, true) => ("border-inline-start-color", "border-right-color"),
246        };
247        let (logical_ie, phys_ie) = match (suffix, rtl) {
248            ("width", false) => ("border-inline-end-width", "border-right-width"),
249            ("width", true) => ("border-inline-end-width", "border-left-width"),
250            ("style", false) => ("border-inline-end-style", "border-right-style"),
251            ("style", true) => ("border-inline-end-style", "border-left-style"),
252            (_, false) => ("border-inline-end-color", "border-right-color"),
253            (_, true) => ("border-inline-end-color", "border-left-color"),
254        };
255        let pairs = [
256            (logical_bs, phys_top),
257            (logical_be, phys_bottom),
258            (logical_is, phys_is),
259            (logical_ie, phys_ie),
260        ];
261        for (logical, physical) in pairs {
262            if specified_values.contains_key(physical) {
263                continue;
264            }
265            if let Some(v) = specified_values.get(logical).cloned() {
266                specified_values.insert(String::from(physical), v);
267            }
268        }
269    }
270
271    // inset-*
272    let (is_phys, ie_phys) = if rtl {
273        ("right", "left")
274    } else {
275        ("left", "right")
276    };
277    let inset_pairs = [
278        ("inset-block-start", "top"),
279        ("inset-block-end", "bottom"),
280        ("inset-inline-start", is_phys),
281        ("inset-inline-end", ie_phys),
282    ];
283    for (logical, physical) in inset_pairs {
284        if specified_values.contains_key(physical) {
285            continue;
286        }
287        if let Some(v) = specified_values.get(logical).cloned() {
288            specified_values.insert(String::from(physical), v);
289        }
290    }
291
292    // inline-size / block-size / min-* / max-*
293    let is_vert = specified_values
294        .get("writing-mode")
295        .map(|v| {
296            let t = v.trim();
297            t.eq_ignore_ascii_case("vertical-rl")
298                || t.eq_ignore_ascii_case("vertical-lr")
299                || t.eq_ignore_ascii_case("sideways-rl")
300                || t.eq_ignore_ascii_case("sideways-lr")
301        })
302        .unwrap_or(false);
303    let size_pairs = if is_vert {
304        [
305            ("inline-size", "height"),
306            ("block-size", "width"),
307            ("min-inline-size", "min-height"),
308            ("max-inline-size", "max-height"),
309            ("min-block-size", "min-width"),
310            ("max-block-size", "max-width"),
311        ]
312    } else {
313        [
314            ("inline-size", "width"),
315            ("block-size", "height"),
316            ("min-inline-size", "min-width"),
317            ("max-inline-size", "max-width"),
318            ("min-block-size", "min-height"),
319            ("max-block-size", "max-height"),
320        ]
321    };
322    for (logical, physical) in size_pairs {
323        if specified_values.contains_key(physical) {
324            continue;
325        }
326        if let Some(v) = specified_values.get(logical).cloned() {
327            specified_values.insert(String::from(physical), v);
328        }
329    }
330}
331
332/// 大文字小文字を無視して `from` を `to` へすべて置換する(`str::replace` は大小文字を
333/// 区別するため使えない)。`currentColor`/`currentcolor`/`CURRENTCOLOR` 等の表記ゆれに対応する。
334pub(crate) fn replace_ignore_case(haystack: &str, from: &str, to: &str) -> String {
335    if from.is_empty() {
336        return String::from(haystack);
337    }
338    let hay_lower = haystack.to_ascii_lowercase();
339    let from_lower = from.to_ascii_lowercase();
340    let mut result = String::new();
341    let mut rest = haystack;
342    let mut rest_lower: &str = &hay_lower;
343    while let Some(pos) = rest_lower.find(from_lower.as_str()) {
344        result.push_str(rest.get(..pos).unwrap_or(""));
345        result.push_str(to);
346        rest = rest.get(pos + from.len()..).unwrap_or("");
347        rest_lower = rest_lower.get(pos + from.len()..).unwrap_or("");
348    }
349    result.push_str(rest);
350    result
351}
352
353/// `currentColor` キーワードを、この要素で確定した `color` の値に置換する。
354/// `color` 自身の継承伝搬が終わった直後(呼び出し元で保証)に実行する必要がある。
355/// `color` プロパティ自体は対象外(`color:currentColor` は無限自己参照になるため触らない)。
356pub(crate) fn resolve_current_color(specified_values: &mut BTreeMap<String, String>) {
357    let Some(color_val) = specified_values.get("color").cloned() else {
358        return;
359    };
360    let keys: alloc::vec::Vec<String> = specified_values
361        .iter()
362        .filter(|(k, v)| k.as_str() != "color" && v.to_ascii_lowercase().contains("currentcolor"))
363        .map(|(k, _)| k.clone())
364        .collect();
365    for k in keys {
366        if let Some(v) = specified_values.get(&k) {
367            let replaced = replace_ignore_case(v, "currentcolor", &color_val);
368            specified_values.insert(k, replaced);
369        }
370    }
371}
372
373/// `place-items`/`place-content`/`place-self`(`align-*`/`justify-*` を1行にまとめる
374/// ショートハンド)を展開する。`place-x: A` は `align-x:A; justify-x:A`、
375/// `place-x: A B` は `align-x:A; justify-x:B` となる。対応する longhand が既に
376/// 指定されていればそちらを優先し、ショートハンドでは上書きしない。
377pub(crate) fn expand_place_shorthands(specified_values: &mut BTreeMap<String, String>) {
378    const PLACE_SHORTHANDS: &[(&str, &str, &str)] = &[
379        ("place-items", "align-items", "justify-items"),
380        ("place-content", "align-content", "justify-content"),
381        ("place-self", "align-self", "justify-self"),
382    ];
383    for &(shorthand_key, align_key, justify_key) in PLACE_SHORTHANDS {
384        let Some(v) = specified_values.get(shorthand_key).cloned() else {
385            continue;
386        };
387        let toks: alloc::vec::Vec<&str> = v.split_whitespace().collect();
388        let (align_v, justify_v) = match toks.as_slice() {
389            [a] => (*a, *a),
390            [a, j] => (*a, *j),
391            _ => continue,
392        };
393        specified_values
394            .entry(String::from(align_key))
395            .or_insert_with(|| String::from(align_v));
396        specified_values
397            .entry(String::from(justify_key))
398            .or_insert_with(|| String::from(justify_v));
399    }
400}
401
402/// `flex-flow` を `flex-direction` / `flex-wrap` へ展開する(longhand が既にあればそちらを優先)。
403pub(crate) fn expand_flex_flow_shorthand(specified_values: &mut BTreeMap<String, String>) {
404    let Some(v) = specified_values.get("flex-flow").cloned() else {
405        return;
406    };
407    for t in v.split_whitespace() {
408        let key = match t.to_ascii_lowercase().as_str() {
409            "row" | "row-reverse" | "column" | "column-reverse" => "flex-direction",
410            "nowrap" | "wrap" | "wrap-reverse" => "flex-wrap",
411            _ => continue,
412        };
413        specified_values.entry(String::from(key)).or_insert_with(|| String::from(t));
414    }
415}
416
417/// 文字列リテラル(`"..."`/`'...'`)区間をすべて取り除き、残ったトークンを空白区切りで
418/// 連結して返す。`grid-template` の `"area row" 1fr "area row" 2fr` のような
419/// エリア名と行トラックサイズが交互に並ぶ記法から、トラックサイズだけを取り出すのに使う。
420pub(crate) fn strip_quoted_segments(s: &str) -> String {
421    let mut out = String::new();
422    let mut chars = s.chars().peekable();
423    while let Some(c) = chars.next() {
424        if c == '"' || c == '\'' {
425            let quote = c;
426            for c2 in chars.by_ref() {
427                if c2 == quote {
428                    break;
429                }
430            }
431        } else {
432            out.push(c);
433        }
434    }
435    out.split_whitespace().collect::<alloc::vec::Vec<_>>().join(" ")
436}
437
438/// `grid` ショートハンド(CSS Grid §7.8)を longhand へ展開する。
439/// - `none` / `<grid-template>`(`rows / columns`・エリア名の文字列つき記法)は `grid-template` へ。
440/// - `<rows> / auto-flow [dense] <auto-columns>?` → `grid-auto-flow:column`、`grid-auto-columns`
441/// - `auto-flow [dense] <auto-rows>? / <columns>` → `grid-auto-flow:row`、`grid-auto-rows`
442///
443/// 対応する longhand が既に指定されていればそちらを優先する。
444pub(crate) fn expand_grid_shorthand(specified_values: &mut BTreeMap<String, String>) {
445    let Some(v) = specified_values.get("grid").cloned() else {
446        return;
447    };
448    let v = v.trim();
449    let has_auto_flow = v.split(|c: char| c == '/' || c.is_whitespace()).any(|t| t == "auto-flow");
450    if !has_auto_flow {
451        specified_values
452            .entry(String::from("grid-template"))
453            .or_insert_with(|| String::from(v));
454        return;
455    }
456    let Some((l, r)) = v.split_once('/') else {
457        return;
458    };
459    let (l, r) = (l.trim(), r.trim());
460    let flow_rest = |part: &str| -> Option<(bool, String)> {
461        let rest = part.strip_prefix("auto-flow")?.trim();
462        let (dense, rest) = match rest.strip_prefix("dense") {
463            Some(x) if x.is_empty() || x.starts_with(char::is_whitespace) => (true, x.trim()),
464            _ => (false, rest),
465        };
466        Some((dense, String::from(rest)))
467    };
468    let flow_rest_after = |part: &str| -> Option<(bool, String)> {
469        // `dense auto-flow ...` の順も許す。
470        if let Some(x) = part.strip_prefix("dense") {
471            let (_, rest) = flow_rest(x.trim())?;
472            return Some((true, rest));
473        }
474        flow_rest(part)
475    };
476    if let Some((dense, rest)) = flow_rest_after(l) {
477        let flow = if dense { "row dense" } else { "row" };
478        specified_values.entry(String::from("grid-auto-flow")).or_insert_with(|| String::from(flow));
479        if !rest.is_empty() {
480            specified_values.entry(String::from("grid-auto-rows")).or_insert(rest);
481        }
482        specified_values.entry(String::from("grid-template-columns")).or_insert_with(|| String::from(r));
483    } else if let Some((dense, rest)) = flow_rest_after(r) {
484        let flow = if dense { "column dense" } else { "column" };
485        specified_values.entry(String::from("grid-auto-flow")).or_insert_with(|| String::from(flow));
486        if !rest.is_empty() {
487            specified_values.entry(String::from("grid-auto-columns")).or_insert(rest);
488        }
489        specified_values.entry(String::from("grid-template-rows")).or_insert_with(|| String::from(l));
490    }
491}
492
493/// `grid-template: <rows> / <columns>` および `grid-template-areas` を含む記法
494/// (`"a a" 1fr "b c" 1fr / 1fr 2fr` のようにエリア名の文字列リテラルと行トラック
495/// サイズが交互に並び、任意で `/ <columns>` が続く)を展開する。
496/// エリア名部分はそのまま `grid-template-areas` へ、文字列リテラルを取り除いた
497/// 残りのトークンを `grid-template-rows` へ、`/` 以降を `grid-template-columns` へ
498/// 展開する。対応する longhand が既に指定されていればそちらを優先する。
499pub(crate) fn expand_grid_template_shorthand(specified_values: &mut BTreeMap<String, String>) {
500    let Some(v) = specified_values.get("grid-template").cloned() else {
501        return;
502    };
503    let (rows_part, cols_part) = match v.split_once('/') {
504        Some((r, c)) => (r.trim(), Some(c.trim())),
505        None => (v.trim(), None),
506    };
507    if rows_part.contains('"') || rows_part.contains('\'') {
508        // エリア名の文字列リテラルはそのまま grid-template-areas へ。
509        specified_values
510            .entry(String::from("grid-template-areas"))
511            .or_insert_with(|| String::from(rows_part));
512        // 文字列リテラルを除いた残り(行トラックサイズ)を grid-template-rows へ。
513        let tracks = strip_quoted_segments(rows_part);
514        if !tracks.is_empty() {
515            specified_values
516                .entry(String::from("grid-template-rows"))
517                .or_insert(tracks);
518        }
519    } else if !rows_part.is_empty() {
520        specified_values
521            .entry(String::from("grid-template-rows"))
522            .or_insert_with(|| String::from(rows_part));
523    }
524    if let Some(cols) = cols_part {
525        if !cols.is_empty() {
526            specified_values
527                .entry(String::from("grid-template-columns"))
528                .or_insert_with(|| String::from(cols));
529        }
530    }
531}
532
533/// `text-emphasis: [<style>] [<color>]` ショートハンドを `text-emphasis-style`/
534/// `text-emphasis-color` へ展開する。`filled`/`open` の fill キーワードは非対応で
535/// 読み飛ばす(常に塗りつぶし形状として扱う簡略実装)。
536pub(crate) fn expand_text_emphasis_shorthand(specified_values: &mut BTreeMap<String, String>) {
537    let Some(v) = specified_values.get("text-emphasis").cloned() else {
538        return;
539    };
540    let mut style_tok: Option<&str> = None;
541    let mut color_tok: Option<&str> = None;
542    for tok in v.split_whitespace() {
543        if matches!(tok, "filled" | "open") {
544            continue;
545        }
546        if matches!(tok, "none" | "dot" | "circle" | "double-circle" | "triangle" | "sesame") {
547            style_tok = Some(tok);
548        } else if parse_color(tok).is_some() {
549            color_tok = Some(tok);
550        } else if style_tok.is_none() {
551            // クォート付きの1文字カスタムマーク(例: `"*"`)
552            style_tok = Some(tok);
553        }
554    }
555    if let Some(s) = style_tok {
556        specified_values
557            .entry(String::from("text-emphasis-style"))
558            .or_insert_with(|| String::from(s));
559    }
560    if let Some(c) = color_tok {
561        specified_values
562            .entry(String::from("text-emphasis-color"))
563            .or_insert_with(|| String::from(c));
564    }
565}
566
567/// `font: [style] [weight] size[/line-height] family-list` ショートハンドを
568/// `font-style`/`font-weight`/`font-size`/`line-height`/`font-family` へ展開する。
569/// **簡略化**: `font-variant`(`small-caps` 等)と `font-stretch` は longhand の消費側が
570/// 存在しないため読み飛ばす(値としては無視するだけで、パース自体は失敗させない)。
571/// `caption`/`icon`/`menu`/`message-box`/`small-caption`/`status-bar` のシステムフォント
572/// キーワードは非対応のため素通りする。対応する longhand が既に指定されていればそちらを
573/// 優先する(`.entry().or_insert()` パターン、他のショートハンド展開関数と同じ方針)。
574pub(crate) fn expand_font_shorthand(specified_values: &mut BTreeMap<String, String>) {
575    let Some(font) = specified_values.get("font").cloned() else {
576        return;
577    };
578    let trimmed = font.trim();
579    let lower_whole = trimmed.to_ascii_lowercase();
580    if matches!(
581        lower_whole.as_str(),
582        "caption" | "icon" | "menu" | "message-box" | "small-caption" | "status-bar"
583    ) {
584        return;
585    }
586
587    // `size` トークンの判定: サイズキーワード、または数字始まり+単位(px/em/%等)を持つ値。
588    // これにより `font-weight` の裸の数値(`700` 等、単位を持たない)と区別する。
589    fn is_size_token(t: &str) -> bool {
590        let low = t.to_ascii_lowercase();
591        const SIZE_KEYWORDS: &[&str] = &[
592            "xx-small", "x-small", "small", "medium", "large", "x-large", "xx-large", "larger",
593            "smaller",
594        ];
595        if SIZE_KEYWORDS.contains(&low.as_str()) {
596            return true;
597        }
598        let first_part = low.split('/').next().unwrap_or(&low);
599        let starts_digit = first_part
600            .chars()
601            .next()
602            .map(|c| c.is_ascii_digit())
603            .unwrap_or(false);
604        if !starts_digit {
605            return false;
606        }
607        // 単位は既知のサイズ単位のみを許容する。以前は「数字始まり+任意の英字を含む」
608        // という緩すぎる判定だったため、`oblique <angle>`(CSS Fonts 4、例:
609        // `font: oblique 10deg 12px/1.5 sans-serif`)の `10deg` を size と誤認し、
610        // 本来の size トークン(`12px/1.5`)が見えなくなる/family に混入するバグがあった。
611        const SIZE_UNITS: &[&str] = &[
612            "px", "em", "rem", "pt", "pc", "in", "cm", "mm", "q", "%", "vh", "vw", "vmin", "vmax",
613            "ex", "ch",
614        ];
615        SIZE_UNITS.iter().any(|u| first_part.ends_with(u))
616    }
617
618    let toks: alloc::vec::Vec<&str> = trimmed.split_whitespace().collect();
619    let mut style: Option<alloc::string::String> = None;
620    let mut weight: Option<alloc::string::String> = None;
621    let mut size_idx = None;
622    for (i, t) in toks.iter().enumerate() {
623        if is_size_token(t) {
624            size_idx = Some(i);
625            break;
626        }
627        match t.to_ascii_lowercase().as_str() {
628            "italic" | "oblique" => style = Some(String::from(*t)),
629            "bold" | "bolder" | "lighter" => weight = Some(String::from(*t)),
630            _ => {
631                if t.parse::<u32>().is_ok() {
632                    weight = Some(String::from(*t));
633                }
634                // normal/small-caps 等はいずれかの軸のデフォルトを明示するだけなので読み飛ばす。
635            }
636        }
637    }
638    let Some(size_idx) = size_idx else {
639        // サイズトークンが見つからない = 不正な `font` 値として非対応、何もしない。
640        return;
641    };
642    let size_tok = toks[size_idx];
643    let (size_part, line_height_part) = match size_tok.split_once('/') {
644        Some((s, l)) => (s, Some(l)),
645        None => (size_tok, None),
646    };
647    specified_values
648        .entry(String::from("font-size"))
649        .or_insert_with(|| String::from(size_part));
650    if let Some(lh) = line_height_part {
651        specified_values
652            .entry(String::from("line-height"))
653            .or_insert_with(|| String::from(lh));
654    }
655    if let Some(s) = style {
656        specified_values.entry(String::from("font-style")).or_insert(s);
657    }
658    if let Some(w) = weight {
659        specified_values.entry(String::from("font-weight")).or_insert(w);
660    }
661    let family = toks[size_idx + 1..].join(" ");
662    if !family.is_empty() {
663        specified_values
664            .entry(String::from("font-family"))
665            .or_insert(family);
666    }
667}
668
669/// 括弧の外の空白で区切る(`rgba(0, 0, 0, .1)` のように括弧の中の空白では切らない)。
670fn split_top_level_ws(s: &str) -> alloc::vec::Vec<&str> {
671    let mut out = alloc::vec::Vec::new();
672    let mut depth = 0i32;
673    let mut start: Option<usize> = None;
674    for (i, ch) in s.char_indices() {
675        match ch {
676            '(' => {
677                depth += 1;
678                if start.is_none() {
679                    start = Some(i);
680                }
681            }
682            ')' => {
683                depth -= 1;
684                if start.is_none() {
685                    start = Some(i);
686                }
687            }
688            c if c.is_whitespace() && depth <= 0 => {
689                if let Some(st) = start.take() {
690                    if let Some(t) = s.get(st..i) {
691                        out.push(t);
692                    }
693                }
694            }
695            _ => {
696                if start.is_none() {
697                    start = Some(i);
698                }
699            }
700        }
701    }
702    if let Some(st) = start {
703        if let Some(t) = s.get(st..) {
704            out.push(t);
705        }
706    }
707    out
708}
709
710/// 辺ごとの 3 つの値(幅・線種・色)の添字。
711const BP_WIDTH: usize = 0;
712const BP_STYLE: usize = 1;
713const BP_COLOR: usize = 2;
714const BORDER_SIDES: [&str; 4] = ["top", "right", "bottom", "left"];
715const BORDER_PARTS: [&str; 3] = ["width", "style", "color"];
716
717/// 1〜4 個の値(`border-color: a b c d`)を上・右・下・左へ振り分ける(CSS の 1〜4 値の規則)。
718fn border_four_values(v: &str) -> Option<[String; 4]> {
719    let t = split_top_level_ws(v);
720    let g = |i: usize| String::from(t[i]);
721    match t.len() {
722        1 => Some([g(0), g(0), g(0), g(0)]),
723        2 => Some([g(0), g(1), g(0), g(1)]),
724        3 => Some([g(0), g(1), g(2), g(1)]),
725        4 => Some([g(0), g(1), g(2), g(3)]),
726        _ => None,
727    }
728}
729
730/// `thin`/`medium`/`thick` を px にする。
731fn border_width_keyword(w: &str) -> String {
732    match w.trim().to_ascii_lowercase().as_str() {
733        "thin" => String::from("1px"),
734        "medium" => String::from("3px"),
735        "thick" => String::from("5px"),
736        other => String::from(other),
737    }
738}
739
740/// `border` 系の一括指定(`border` / `border-width|style|color` / `border-top` 等)を、
741/// 辺ごとの個別指定(`border-top-width` … 12 個)へ展開する。
742///
743/// 【2026-11-18】従来は「`border` → 個別」の展開しかなく、個別指定が 1 つでもあれば一括指定の値を
744/// 無視し(`or_insert`)、`border-color`/`border-width`/`border-style` は辺へ展開されなかった。
745/// そのため `.btn{border:2px solid transparent}` の後に `.btn-secondary{border-color:#fff}` と書くと
746/// 辺の色が透明のまま残り、`border-width`・`border-style` を別々に書くと枠が出なかった。
747///
748/// ここでは、カスケードで勝ち残った各宣言(`ranks`: キー → 優先度。インライン style を含む)を
749/// 辺 × (幅・線種・色) ごとに比べ、一番強い宣言の値をその辺の個別指定にする
750/// (仕様どおり、一括指定は個別指定を全部上書きし、後勝ち・詳細度・`!important` で決まる)。
751/// `ranks` に無いキー(UA 既定など)は最下位。同順位なら個別指定の方が勝つ。
752/// 一括指定が省いた値は初期値に戻す(線種 none・幅 medium・色 currentColor)。
753/// 線種が none の辺の幅は 0(仕様の計算値)、線種があって幅が無い辺は medium(3px)。
754pub(crate) fn expand_border_shorthands(
755    specified_values: &mut BTreeMap<String, String>,
756    ranks: &[(String, AppliedDecl<'static>)],
757) {
758    // 高速パス: border 関連プロパティが一切無ければ即リターン
759    if !specified_values.keys().any(|k| k.starts_with("border")) {
760        return;
761    }
762    let rank_of = |key: &str| -> Option<&AppliedDecl<'static>> {
763        ranks.iter().find(|(k, _)| k == key).map(|(_, r)| r)
764    };
765    // 候補同士の比較。`a` が `b` より強いか(同順位は後から調べたもの=個別指定を勝たせるため `>=`)。
766    let stronger_or_equal = |a: Option<&AppliedDecl<'static>>, b: Option<&AppliedDecl<'static>>| -> bool {
767        match (a, b) {
768            (Some(x), Some(y)) => decl_outranks(x, y),
769            (Some(_), None) => true,
770            (None, Some(_)) => false,
771            (None, None) => true,
772        }
773    };
774
775    // 一括指定の分解結果(幅・線種・色。省いた値は None=初期値へ戻す)。
776    let all = specified_values.get("border").map(|v| parse_border_shorthand(v));
777    let part_sh: [Option<[String; 4]>; 3] = [
778        specified_values.get("border-width").and_then(|v| border_four_values(v)),
779        specified_values.get("border-style").and_then(|v| border_four_values(v)),
780        specified_values.get("border-color").and_then(|v| border_four_values(v)),
781    ];
782    let part_sh_keys = ["border-width", "border-style", "border-color"];
783
784    let mut out: alloc::vec::Vec<(String, String)> = alloc::vec::Vec::new();
785    for (si, side) in BORDER_SIDES.iter().enumerate() {
786        let side_key = alloc::format!("border-{}", side);
787        let side_sh = specified_values.get(&side_key).map(|v| parse_border_shorthand(v));
788        // 辺ごとの勝者(Some(None)=一括指定が省いたので初期値、Some(Some(v))=値あり、None=指定なし)。
789        let mut win: [Option<Option<String>>; 3] = [None, None, None];
790        for pi in 0..3 {
791            let mut best: Option<(Option<AppliedDecl<'static>>, Option<String>)> = None;
792            let mut consider = |rank: Option<AppliedDecl<'static>>, val: Option<String>| {
793                let take = match &best {
794                    None => true,
795                    Some((br, _)) => stronger_or_equal(rank.as_ref(), br.as_ref()),
796                };
797                if take {
798                    best = Some((rank, val));
799                }
800            };
801            if let Some((w, s, c)) = &all {
802                let v = [w, s, c][pi].clone();
803                consider(rank_of("border").copied(), v);
804            }
805            if let Some(vals) = &part_sh[pi] {
806                consider(rank_of(part_sh_keys[pi]).copied(), Some(vals[si].clone()));
807            }
808            if let Some((w, s, c)) = &side_sh {
809                let v = [w, s, c][pi].clone();
810                consider(rank_of(&side_key).copied(), v);
811            }
812            let long_key = alloc::format!("border-{}-{}", side, BORDER_PARTS[pi]);
813            if let Some(v) = specified_values.get(&long_key) {
814                consider(rank_of(&long_key).copied(), Some(v.clone()));
815            }
816            win[pi] = best.map(|(_, v)| v);
817        }
818        if win.iter().all(|w| w.is_none()) {
819            continue;
820        }
821        // 線種(指定なし・省略は none)。
822        let style = match &win[BP_STYLE] {
823            Some(Some(s)) => s.trim().to_ascii_lowercase(),
824            _ => String::from("none"),
825        };
826        let no_line = matches!(style.as_str(), "none" | "hidden");
827        let width = if no_line {
828            String::from("0px")
829        } else {
830            match &win[BP_WIDTH] {
831                Some(Some(w)) => border_width_keyword(w),
832                _ => String::from("3px"),
833            }
834        };
835        let color = match &win[BP_COLOR] {
836            Some(Some(c)) => c.clone(),
837            _ => String::from("currentcolor"),
838        };
839        out.push((alloc::format!("border-{}-width", side), width));
840        out.push((alloc::format!("border-{}-style", side), style));
841        out.push((alloc::format!("border-{}-color", side), color));
842    }
843    for (k, v) in out {
844        specified_values.insert(k, v);
845    }
846}
847
848/// `background` ショートハンド(`background: url(...) center/cover no-repeat` 等)から
849/// `background-position`/`background-size`/`background-repeat` を抜き出し、明示的な
850/// longhand 指定が無い場合のみカスケード時点で補う。
851///
852/// 元々このスラッシュ構文(`<position> / <size>`)の分解ロジックは`web_engine/layout.rs`
853/// 内のローカル関数として存在していたが、`background`ショートハンドを読む同種のコード
854/// ブロックが同ファイル内に10箇所以上重複しており、実際にこの分解ロジックが配線されて
855/// いたのはそのうち1箇所のみだった(残りは`background-size`/`-position`/`-repeat`を
856/// 素通しするだけで、シェアされた `styled.value("background-size")` 経由の longhand
857/// フォールバックしか効かず、ショートハンド内の`/size`が無視されていた)。カスケード
858/// 時点で一度だけ展開して`specified_values`に書き戻すことで、全ての呼び出し箇所が
859/// 自動的に正しい値を受け取るようにする(2026-07-21 発見・修正。詳細は
860/// walkthrough.md 参照)。
861pub(crate) fn expand_background_shorthand(specified_values: &mut BTreeMap<String, String>) {
862    let Some(bg) = specified_values.get("background").cloned() else {
863        return;
864    };
865    // size は `<position> / <size>` のスラッシュの後ろにしか現れない。トークンを
866    // 無条件に2個取ると、`center/cover no-repeat`のように直後に`background-repeat`
867    // 等の別サブ値が続く場合に誤って取り込んでしまう(2026-07-21発見・修正。
868    // `cover`/`contain`/`auto`キーワードまたは長さ/割合に見えるトークンのみを
869    // 最大2個まで採用する)。
870    if let Some((_, after)) = bg.split_once('/') {
871        let toks: Vec<&str> = after
872            .split_whitespace()
873            .take_while(|t| {
874                matches!(*t, "cover" | "contain" | "auto")
875                    || t.ends_with('%')
876                    || t.ends_with("px")
877                    || t.ends_with("em")
878                    || t.ends_with("vw")
879                    || t.ends_with("vh")
880            })
881            .take(2)
882            .collect();
883        if !toks.is_empty() {
884            specified_values
885                .entry(String::from("background-size"))
886                .or_insert_with(|| toks.join(" "));
887        }
888    }
889    let repeat_toks: Vec<&str> = bg
890        .split_whitespace()
891        .filter(|t| {
892            matches!(
893                *t,
894                "no-repeat" | "repeat" | "repeat-x" | "repeat-y" | "space" | "round"
895            )
896        })
897        .take(2)
898        .collect();
899    if !repeat_toks.is_empty() {
900        specified_values
901            .entry(String::from("background-repeat"))
902            .or_insert_with(|| repeat_toks.join(" "));
903    }
904    // position はスラッシュより手前側のみを対象にする(後ろは size)。
905    let position_part = bg.split_once('/').map(|(before, _)| before).unwrap_or(&bg);
906    let position_toks: Vec<&str> = position_part
907        .split_whitespace()
908        .filter(|t| {
909            matches!(*t, "center" | "top" | "bottom" | "left" | "right")
910                || t.ends_with('%')
911                || t.ends_with("px")
912        })
913        .collect();
914    if !position_toks.is_empty() {
915        specified_values
916            .entry(String::from("background-position"))
917            .or_insert_with(|| position_toks.join(" "));
918    }
919}
920
921/// `container: <name> [/ <type>]` ショートハンドを展開する。
922pub(crate) fn expand_container_shorthand(specified_values: &mut BTreeMap<String, String>) {
923    if let Some(val) = specified_values.remove("container") {
924        let v = val.trim();
925        if let Some((name_part, type_part)) = v.split_once('/') {
926            let name = name_part.trim();
927            let c_type = type_part.trim();
928            if !name.is_empty() {
929                specified_values.entry(String::from("container-name")).or_insert_with(|| String::from(name));
930            }
931            if !c_type.is_empty() {
932                specified_values.entry(String::from("container-type")).or_insert_with(|| String::from(c_type));
933            }
934        } else if matches!(v, "normal" | "size" | "inline-size") {
935            specified_values.entry(String::from("container-type")).or_insert_with(|| String::from(v));
936        } else if !v.is_empty() {
937            specified_values.entry(String::from("container-name")).or_insert_with(|| String::from(v));
938        }
939    }
940}
941
942/// `text-transform` を適用する(uppercase / lowercase / capitalize)。
943pub fn apply_text_transform(text: &str, mode: &str) -> String {
944    match mode.trim() {
945        "uppercase" => text.to_uppercase(),
946        "lowercase" => text.to_lowercase(),
947        "capitalize" => {
948            // 各単語の先頭文字を大文字化(空白区切り)。
949            let mut out = String::with_capacity(text.len());
950            let mut at_word_start = true;
951            for c in text.chars() {
952                if c.is_whitespace() {
953                    at_word_start = true;
954                    out.push(c);
955                } else if at_word_start {
956                    out.extend(c.to_uppercase());
957                    at_word_start = false;
958                } else {
959                    out.push(c);
960                }
961            }
962            out
963        }
964        _ => text.to_string(),
965    }
966}
967
968// ===================================================================
969// CSS Transitions / Animations
970// ===================================================================
971