Skip to main content

atmos/os_lib/css/
counter_scope.rs

1//! CSS Lists and Counters Module Level 3 準拠のカウンタスコープ管理モジュール
2//!
3//! `counter-reset` による新しいネストレベルの生成、`counter-increment` による
4//! 最深スコープの更新、および `counters(name, sep, style)` の複数深度連結を純粋ロジックとして提供する。
5
6extern crate alloc;
7use alloc::collections::BTreeMap;
8use alloc::format;
9use alloc::string::{String, ToString};
10use alloc::vec::Vec;
11use crate::os_lib::css::types::CounterStyleDef;
12
13/// カウンタのスコープスタック管理
14#[derive(Debug, Clone, PartialEq, Eq, Default)]
15pub struct CounterScopeStack {
16    /// カウンタ名 -> スコープスタック(外側から内側への値のリスト)
17    counters: BTreeMap<String, Vec<i64>>,
18}
19
20impl CounterScopeStack {
21    pub fn new() -> Self {
22        Self {
23            counters: BTreeMap::new(),
24        }
25    }
26
27    /// カウンタが一つも無いか(スタイルの使い回しの判定。`style_memo.rs`)。
28    pub fn is_empty(&self) -> bool {
29        self.counters.values().all(|v| v.is_empty())
30    }
31
32    /// 既存のフラットマップからスタックを初期化する(後方互換用)。
33    pub fn from_map(map: &BTreeMap<String, i64>) -> Self {
34        let mut counters = BTreeMap::new();
35        for (k, &v) in map {
36            counters.insert(k.clone(), alloc::vec![v]);
37        }
38        Self { counters }
39    }
40
41    /// 現在の最深スコープの値だけをフラットマップとして取り出す。
42    pub fn to_flat_map(&self) -> BTreeMap<String, i64> {
43        let mut map = BTreeMap::new();
44        for (k, v) in &self.counters {
45            if let Some(&top) = v.last() {
46                map.insert(k.clone(), top);
47            }
48        }
49        map
50    }
51
52    /// `counter-reset: name value` を適用する。
53    /// 仕様(CSS Lists and Counters §3):
54    /// 要素に `counter-reset` がある場合、その名前の新しいカウンタスコープをスタックにプッシュする。
55    pub fn push_reset(&mut self, name: &str, value: i64) {
56        self.counters
57            .entry(name.to_string())
58            .or_default()
59            .push(value);
60    }
61
62    /// 要素のスコープを抜ける際に、その要素で `push_reset` されたレベルをポップする。
63    pub fn pop_reset(&mut self, name: &str) {
64        if let Some(stack) = self.counters.get_mut(name) {
65            stack.pop();
66            if stack.is_empty() {
67                self.counters.remove(name);
68            }
69        }
70    }
71
72    /// `counter-increment: name value` を適用する。
73    /// 仕様: スタックの最深(最も内側)のカウンタに value を加算する。
74    /// もしまだ一度も reset されていない場合は、暗黙のルートスコープ(初期値 0)を生成して加算する。
75    pub fn increment(&mut self, name: &str, value: i64) {
76        let stack = self.counters.entry(name.to_string()).or_default();
77        if let Some(top) = stack.last_mut() {
78            *top += value;
79        } else {
80            stack.push(value);
81        }
82    }
83
84    /// `counter-set: name value` を適用する。
85    /// 仕様: 最深スコープの値を上書きする。スタックが空なら暗黙のルートスコープを作成。
86    pub fn set(&mut self, name: &str, value: i64) {
87        let stack = self.counters.entry(name.to_string()).or_default();
88        if let Some(top) = stack.last_mut() {
89            *top = value;
90        } else {
91            stack.push(value);
92        }
93    }
94
95    /// 現在(最深スコープ)のカウンタ値を取得する。
96    /// スコープが存在しない場合は 0 を返す。
97    pub fn get_current(&self, name: &str) -> i64 {
98        self.counters
99            .get(name)
100            .and_then(|stack| stack.last().copied())
101            .unwrap_or(0)
102    }
103
104    /// カウンタのすべてのスコープ(外側から内側)の値を取得する。
105    pub fn get_all(&self, name: &str) -> &[i64] {
106        self.counters
107            .get(name)
108            .map(|s| s.as_slice())
109            .unwrap_or(&[])
110    }
111
112    /// `counter(name, style)` の書式化文字列を生成する。
113    pub fn format_counter(
114        &self,
115        name: &str,
116        style: Option<&str>,
117        counter_styles: &[CounterStyleDef],
118    ) -> String {
119        let val = self.get_current(name);
120        format_single_counter_value(val, style, counter_styles)
121    }
122
123    /// `counters(name, sep, style)` の書式化文字列を生成する。
124    /// すべてのネストレベルの値を `sep` で連結する。
125    pub fn format_counters(
126        &self,
127        name: &str,
128        sep: &str,
129        style: Option<&str>,
130        counter_styles: &[CounterStyleDef],
131    ) -> String {
132        let all = self.get_all(name);
133        if all.is_empty() {
134            // スコープが空の場合は現在値(0)を1つ出力
135            return format_single_counter_value(0, style, counter_styles);
136        }
137        let formatted_pieces: Vec<String> = all
138            .iter()
139            .map(|&val| format_single_counter_value(val, style, counter_styles))
140            .collect();
141        formatted_pieces.join(sep)
142    }
143}
144
145/// 単一のカウンタ数値を指定されたスタイルまたはカスタムスタイルでフォーマットする。
146pub fn format_single_counter_value(
147    val: i64,
148    style: Option<&str>,
149    counter_styles: &[CounterStyleDef],
150) -> String {
151    let val_u32 = val.max(0) as u32;
152    match style.map(|s| s.to_ascii_lowercase()).as_deref() {
153        Some("upper-roman") => crate::os_lib::util::ordinal::number_to_roman(val_u32, true),
154        Some("lower-roman") => crate::os_lib::util::ordinal::number_to_roman(val_u32, false),
155        Some("upper-alpha") | Some("upper-latin") => {
156            crate::os_lib::util::ordinal::number_to_alpha(val_u32, true)
157        }
158        Some("lower-alpha") | Some("lower-latin") => {
159            crate::os_lib::util::ordinal::number_to_alpha(val_u32, false)
160        }
161        Some("decimal") | None => format!("{}", val),
162        Some(custom) => {
163            if let Some(def) = counter_styles.iter().find(|d| d.name == custom) {
164                crate::os_lib::css::types::format_with_counter_style(def, val)
165            } else {
166                format!("{}", val)
167            }
168        }
169    }
170}
171
172/// `counter-reset` / `counter-increment` / `counter-set` を `CounterScopeStack` に適用する。
173/// 戻り値は、この要素自身が `counter-reset` した(=スコープをプッシュした)カウンタ名のリスト(順序保持)。
174pub fn apply_counter_decls_to_stack(
175    specified_values: &BTreeMap<String, String>,
176    stack: &mut CounterScopeStack,
177) -> Vec<String> {
178    let mut pushed_resets = Vec::new();
179    if let Some(reset) = specified_values.get("counter-reset") {
180        for (name, value) in crate::os_lib::css::selector::parse_counter_decl(reset, 0) {
181            stack.push_reset(&name, value);
182            pushed_resets.push(name);
183        }
184    }
185    if let Some(incr) = specified_values.get("counter-increment") {
186        for (name, value) in crate::os_lib::css::selector::parse_counter_decl(incr, 1) {
187            stack.increment(&name, value);
188        }
189    }
190    if let Some(set) = specified_values.get("counter-set") {
191        for (name, value) in crate::os_lib::css::selector::parse_counter_decl(set, 0) {
192            stack.set(&name, value);
193        }
194    }
195    pushed_resets
196}