Skip to main content

atmos/os_lib/web_engine/
paint_update.rs

1//! DOM インラインスタイル変更の軽量再ペイント(PaintOnly)判定。
2//!
3//! スクロールイベントやタイマー等で JavaScript が `element.style.transform = ...` や
4//! `element.style.color = ...` などの見た目のみを変えるプロパティを頻繁に更新する場合、
5//! 毎回 HTML を再パースして全ルールを再カスケードする全再レイアウト(約 350ms)を行うと
6//! 画面がカクつき、スクロールの追従性が著しく劣化する。
7//!
8//! 本モジュールは、蓄積された保留スタイル更新(pending updates)と構造変更フラグから、
9//! 全再レイアウトを省略して RenderElement への直接上書き(再ペイントのみ)で済ませられるか
10//! を決定論的に判定する純粋ロジックを提供する。
11
12extern crate alloc;
13
14use alloc::string::String;
15use alloc::vec::Vec;
16use super::repaint_scope::is_paint_only;
17
18/// 保留中のスタイル更新 1 件。
19#[derive(Debug, Clone, PartialEq, Eq)]
20pub struct PendingStyleUpdate {
21    pub node_idx: usize,
22    pub prop: String,
23    pub val: String,
24}
25
26/// 必要な更新処理の範囲。
27#[derive(Debug, Clone, PartialEq, Eq)]
28pub enum UpdateScope {
29    /// 変更なし。
30    Nothing,
31    /// 軽量再ペイントのみ。各要素の (element_id, prop, val) のリストを返す。
32    PaintOnly(Vec<(String, String, String)>),
33    /// 全再レイアウトが必要。
34    Relayout,
35}
36
37/// 保留中のスタイル更新群と構造ダーティフラグから、処理範囲を判定する。
38///
39/// `resolve_id` は `node_idx` からその要素の RenderElement 照合用 `element_id` を
40/// 解決するクロージャ。要素に id が無い場合は None を返し、安全に Relayout へフォールバックする。
41pub fn classify_updates<F>(
42    structural_dirty: bool,
43    updates: &[PendingStyleUpdate],
44    resolve_id: F,
45) -> UpdateScope
46where
47    F: Fn(usize) -> Option<String>,
48{
49    if structural_dirty {
50        return UpdateScope::Relayout;
51    }
52    if updates.is_empty() {
53        return UpdateScope::Nothing;
54    }
55
56    let mut paint_values = Vec::with_capacity(updates.len());
57    for u in updates {
58        // プロパティが PaintOnly か判定
59        match is_paint_only(&u.prop) {
60            Ok(true) => {}
61            _ => return UpdateScope::Relayout,
62        }
63        // 要素の element_id を解決(見つからなければ安全に Relayout へ)
64        let Some(eid) = resolve_id(u.node_idx) else {
65            return UpdateScope::Relayout;
66        };
67        if eid.is_empty() {
68            return UpdateScope::Relayout;
69        }
70        paint_values.push((eid, u.prop.clone(), u.val.clone()));
71    }
72
73    UpdateScope::PaintOnly(paint_values)
74}
75
76/// 単一テキスト子の保留テキスト更新 1 件(TODO P4c/d)。
77#[derive(Debug, Clone, PartialEq, Eq)]
78pub struct PendingTextUpdate {
79    pub elem_idx: usize,
80    pub text_idx: usize,
81    pub new_text: String,
82}
83
84/// インプレーステキスト更新の判定に使う `RenderElement` の位置・種別スナップショット。
85#[derive(Debug, Clone, PartialEq, Eq)]
86pub struct TextElementSlot {
87    pub elem_array_idx: usize,
88    pub node_idx: Option<usize>,
89    pub is_text: bool,
90    pub x_offset: i32,
91    pub y_offset: i32,
92    pub width: i32,
93    pub height: i32,
94}
95
96/// 単一行・固定幅箱のインプレーステキスト更新を適用できるか判定する(純粋ロジック)。
97///
98/// 全条件を満たす場合のみ `Some(Vec<(elem_array_idx, new_text, new_width)>)` を返し、
99/// 複数行への折り返し変化や隣接インライン要素の押し出しが生じる恐れがある場合は
100/// `None` を返して通常の `parse_and_layout` へ安全にフォールバックする。
101pub fn plan_in_place_text_updates<M>(
102    structural_dirty: bool,
103    style_updates_empty: bool,
104    text_updates: &[PendingTextUpdate],
105    slots: &[TextElementSlot],
106    mut measure_text: M,
107) -> Option<Vec<(usize, String, i32)>>
108where
109    M: FnMut(usize, &str) -> i32,
110{
111    if structural_dirty || !style_updates_empty || text_updates.is_empty() {
112        return None;
113    }
114
115    let mut planned = Vec::with_capacity(text_updates.len());
116    for u in text_updates {
117        if u.new_text.is_empty() || u.new_text.contains('\n') || u.new_text.contains('\r') {
118            return None;
119        }
120        let mut matched = slots
121            .iter()
122            .filter(|s| s.is_text && (s.node_idx == Some(u.text_idx) || s.node_idx == Some(u.elem_idx)));
123        let target = matched.next()?;
124        // 複数行に折り返されている(同一ノードから 2 要素以上生成されている)場合は対象外。
125        if matched.next().is_some() {
126            return None;
127        }
128
129        let new_w = measure_text(target.elem_array_idx, &u.new_text);
130        if new_w <= 0 {
131            return None;
132        }
133
134        if new_w != target.width {
135            let row_tol = target.height.max(1);
136            let same_row = |s: &TextElementSlot| -> bool {
137                s.is_text
138                    && s.elem_array_idx != target.elem_array_idx
139                    && (s.y_offset - target.y_offset).abs() < row_tol
140                    && s.x_offset >= target.x_offset
141            };
142            let parent_box = slots
143                .iter()
144                .find(|s| !s.is_text && s.node_idx == Some(u.elem_idx));
145            let fits_fixed_parent = parent_box.is_some_and(|b| {
146                target.x_offset >= b.x_offset
147                    && target.x_offset + new_w <= b.x_offset + b.width
148                    && !slots.iter().any(|s| same_row(s) && s.x_offset < b.x_offset + b.width)
149            });
150            let no_right_sibling = !slots.iter().any(same_row);
151            if !fits_fixed_parent && !no_right_sibling {
152                return None;
153            }
154        }
155
156        planned.push((target.elem_array_idx, u.new_text.clone(), new_w));
157    }
158
159    Some(planned)
160}