strata-ui 0.1.2

Universal frontend framework in pure Rust with pixel-perfect CSS emulation and React/TSX ergonomics
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
//! Text input layout synchronization, caret offset calculation, and caret rendering.

use super::*;

impl AppRuntime {
    /// Resets the caret blink cycle so the insertion caret is immediately solid and visible.
    #[inline]
    pub fn reset_caret_blink(&mut self) {
        self.caret_blink_epoch = std::time::Instant::now();
        self.last_caret_blink_state = true;
    }

    /// Polls caret blink cycle and returns true if blink state toggled (requiring a redraw).
    pub fn poll_caret_blink(&mut self) -> bool {
        if self.active_focus.is_none() {
            return false;
        }
        let elapsed_ms = self.caret_blink_epoch.elapsed().as_millis();
        let is_blink_on = (elapsed_ms / 530).is_multiple_of(2);
        if is_blink_on != self.last_caret_blink_state {
            self.last_caret_blink_state = is_blink_on;
            true
        } else {
            false
        }
    }

    /// Synchronizes the active focused text input's live buffer and styling into the layout tree.
    pub fn sync_active_input_layout(&mut self) {
        let Some(ref active) = self.active_focus else {
            return;
        };
        let target_idx = active.input_index;
        let target_id = active.input_id.clone();
        let target_entity_id = active.entity_id;
        let mut counter = 0;
        let text_val = active.state.text.get();

        let layout_by_entity = if let Some(eid) = target_entity_id {
            self.layout_root.find_by_entity_id_mut(eid)
        } else {
            None
        };
        let layout_match = match layout_by_entity {
            Some(l) => Some(l),
            None => Self::find_input_layout_mut(
                &self.root_blueprint,
                &mut self.layout_root,
                target_idx,
                target_id.as_deref(),
                &mut counter,
            ),
        };

        if let Some(layout) = layout_match {
            let is_mono = strata_layout::is_monospace_family(layout.style.font_family);
            if !text_val.is_empty() {
                layout.text = Some(text_val.clone());
                if let Some(c) = layout.style.caret_color {
                    layout.style.color = c;
                }
                let (tw, th) = strata_layout::text::measure_text_bounds_with_family(
                    &text_val,
                    layout.style.font_size,
                    layout.style.line_height,
                    None,
                    is_mono,
                    layout.style.font_family,
                );
                layout.geometry.content_box.width = tw.max(layout.geometry.content_box.width);
                layout.geometry.content_box.height = th.max(layout.geometry.content_box.height);
            } else {
                let mut ph = None;
                let mut bp_counter = 0;
                let bp_match = if let Some(eid) = target_entity_id {
                    self.root_blueprint.find_by_entity_id(eid)
                } else {
                    None
                };
                let bp_match = bp_match.or_else(|| {
                    Self::find_input_blueprint(
                        &self.root_blueprint,
                        target_idx,
                        target_id.as_deref(),
                        &mut bp_counter,
                    )
                });
                if let Some(bp) = bp_match {
                    if let NodeBlueprint::Element { attributes, .. } = bp {
                        for attr in attributes {
                            if let strata_dom::Attribute::Property { key, value } = attr {
                                if key == "placeholder" && !value.is_empty() {
                                    ph = Some(value.clone());
                                }
                            }
                        }
                    }
                }
                if let Some(ph_str) = ph {
                    layout.text = Some(ph_str);
                    layout.style.color = strata_style::types::Color::new(140, 145, 155, 255);
                } else {
                    layout.text = Some(String::new());
                }
            }
        }

        self.update_gtk_ime_location();
    }

    /// Calculates the exact character index from an x offset within an input using active font metrics and character advances.
    pub fn calculate_exact_char_index_at_offset(
        text: &str,
        rel_x: f32,
        font_size: f32,
        line_height: f32,
        is_mono: bool,
        font_family: strata_primitives::AtomId,
    ) -> usize {
        if rel_x <= 0.0 || text.is_empty() {
            return 0;
        }
        let chars: Vec<char> = text.chars().collect();
        let total = chars.len();

        let (full_w, _) = strata_layout::text::measure_text_bounds_with_family(
            text,
            font_size,
            line_height,
            None,
            is_mono,
            font_family,
        );
        if rel_x >= full_w {
            return total;
        }

        let mut prev_w = 0.0f32;
        for i in 1..=total {
            let prefix: String = chars[..i].iter().collect();
            let (w, _) = strata_layout::text::measure_text_bounds_with_family(
                &prefix,
                font_size,
                line_height,
                None,
                is_mono,
                font_family,
            );
            let mid = (prev_w + w) / 2.0;
            if rel_x < mid {
                return i - 1;
            } else if rel_x <= w {
                return i;
            }
            prev_w = w;
        }
        total
    }

    /// Renders the visible insertion caret cursor and selection highlight for the currently focused text input.
    pub fn render_active_input_caret(&mut self) {
        let Some(ref active) = self.active_focus else {
            return;
        };

        let mut current_idx = 0;
        let target_idx = active.input_index;
        let target_id = active.input_id.as_deref();

        let layout_by_entity = if let Some(eid) = active.entity_id {
            self.layout_root.find_by_entity_id(eid)
        } else {
            None
        };
        let Some(layout) = layout_by_entity.or_else(|| {
            Self::find_input_layout(
                &self.root_blueprint,
                &self.layout_root,
                target_idx,
                target_id,
                &mut current_idx,
            )
        }) else {
            return;
        };

        let content_box = layout.geometry.content_box;
        if content_box.width <= 0.0 || content_box.height <= 0.0 {
            return;
        }

        let font_size = layout.style.font_size;
        let line_height = layout.style.line_height;
        let is_mono = strata_layout::is_monospace_family(layout.style.font_family);
        let font_family = layout.style.font_family;
        let text_color = layout.style.color;
        let mut caret_color = layout.style.caret_color.unwrap_or(text_color);
        if caret_color.a == 0 {
            caret_color = strata_style::types::Color::new(236, 233, 225, 255);
        }
        let text = active.state.text.get();
        let total_chars = text.chars().count();
        let cursor_idx = active.state.cursor_index.get().min(total_chars);

        // Alignment offset for text-align: center / right
        let align_offset = match layout.style.text_align {
            strata_style::types::TextAlign::Center => {
                let (tw, _) = strata_layout::text::measure_text_bounds_with_family(
                    &text,
                    font_size,
                    line_height,
                    None,
                    is_mono,
                    font_family,
                );
                ((content_box.width - tw) / 2.0).max(0.0)
            }
            strata_style::types::TextAlign::Right => {
                let (tw, _) = strata_layout::text::measure_text_bounds_with_family(
                    &text,
                    font_size,
                    line_height,
                    None,
                    is_mono,
                    font_family,
                );
                (content_box.width - tw).max(0.0)
            }
            _ => 0.0,
        };

        let caret_w = 2.0f32;
        let caret_h = (font_size * 1.2).min(content_box.height).max(14.0);
        let caret_y = content_box.y + ((content_box.height - caret_h) / 2.0).max(0.0);

        // 1. Selection range highlight (CSS ::selection)
        if let Some((start, end)) = active.state.selection_range() {
            let start_clamped = start.min(total_chars);
            let end_clamped = end.min(total_chars);
            if start_clamped < end_clamped {
                let start_prefix: String = text.chars().take(start_clamped).collect();
                let (start_w, _) = strata_layout::text::measure_text_bounds_with_family(
                    &start_prefix,
                    font_size,
                    line_height,
                    None,
                    is_mono,
                    font_family,
                );
                let sel_slice: String = text
                    .chars()
                    .skip(start_clamped)
                    .take(end_clamped - start_clamped)
                    .collect();
                let (sel_w, _) = strata_layout::text::measure_text_bounds_with_family(
                    &sel_slice,
                    font_size,
                    line_height,
                    None,
                    is_mono,
                    font_family,
                );

                let sel_h = (font_size * 1.25).min(content_box.height);
                let sel_y = content_box.y + ((content_box.height - sel_h) / 2.0).max(0.0);
                let sel_x = content_box.x + align_offset + start_w;

                self.display_list
                    .push(strata_render::compositor::DrawCommand::DrawRect {
                        bounds: strata_layout::Rect::new(sel_x, sel_y, sel_w, sel_h),
                        color: strata_style::types::Color::rgba(59, 130, 246, 120), // Standard CSS selection blue
                    });
            }
        }

        // 2. Visible Caret Line Cursor (CSS caret-color, blinking, and insertion cursor)
        let has_sel = active.state.has_selection();
        let elapsed_ms = self.caret_blink_epoch.elapsed().as_millis();
        let is_blink_on = (elapsed_ms / 530).is_multiple_of(2);

        if !has_sel && is_blink_on {
            let prefix: String = text.chars().take(cursor_idx).collect();
            let (cursor_w, _) = strata_layout::text::measure_text_bounds_with_family(
                &prefix,
                font_size,
                line_height,
                None,
                is_mono,
                font_family,
            );
            let caret_x = (content_box.x + align_offset + cursor_w)
                .min(content_box.x + content_box.width - caret_w);

            self.display_list
                .push(strata_render::compositor::DrawCommand::DrawRect {
                    bounds: strata_layout::Rect::new(caret_x, caret_y, caret_w, caret_h),
                    color: caret_color,
                });
        }
    }

    /// Computes the exact bounding box of the active text caret if an input is currently focused.
    pub fn active_caret_rect(&self) -> Option<strata_layout::Rect> {
        let active = self.active_focus.as_ref()?;
        let mut current_idx = 0;
        let target_idx = active.input_index;
        let target_id = active.input_id.as_deref();

        let layout_by_entity = if let Some(eid) = active.entity_id {
            self.layout_root.find_by_entity_id(eid)
        } else {
            None
        };
        let layout = layout_by_entity.or_else(|| {
            Self::find_input_layout(
                &self.root_blueprint,
                &self.layout_root,
                target_idx,
                target_id,
                &mut current_idx,
            )
        })?;

        let content_box = layout.geometry.content_box;
        if content_box.width <= 0.0 || content_box.height <= 0.0 {
            return None;
        }

        let font_size = layout.style.font_size;
        let line_height = layout.style.line_height;
        let is_mono = strata_layout::is_monospace_family(layout.style.font_family);
        let font_family = layout.style.font_family;
        let text = active.state.text.get();
        let total_chars = text.chars().count();
        let cursor_idx = active.state.cursor_index.get().min(total_chars);

        let align_offset = match layout.style.text_align {
            strata_style::types::TextAlign::Center => {
                let (tw, _) = strata_layout::text::measure_text_bounds_with_family(
                    &text,
                    font_size,
                    line_height,
                    None,
                    is_mono,
                    font_family,
                );
                ((content_box.width - tw) / 2.0).max(0.0)
            }
            strata_style::types::TextAlign::Right => {
                let (tw, _) = strata_layout::text::measure_text_bounds_with_family(
                    &text,
                    font_size,
                    line_height,
                    None,
                    is_mono,
                    font_family,
                );
                (content_box.width - tw).max(0.0)
            }
            _ => 0.0,
        };

        let caret_w = 2.0f32;
        let caret_h = (font_size * 1.2).min(content_box.height).max(14.0);
        let caret_y = content_box.y + ((content_box.height - caret_h) / 2.0).max(0.0);
        let prefix: String = text.chars().take(cursor_idx).collect();
        let (cursor_w, _) = strata_layout::text::measure_text_bounds_with_family(
            &prefix,
            font_size,
            line_height,
            None,
            is_mono,
            font_family,
        );
        let caret_x = (content_box.x + align_offset + cursor_w)
            .min(content_box.x + content_box.width - caret_w);

        Some(strata_layout::Rect::new(caret_x, caret_y, caret_w, caret_h))
    }

    /// Synchronizes the IME candidate window location with the active caret position.
    pub fn sync_ime_cursor_location<W: strata_platform::PlatformWindow>(&self, window: &mut W) {
        if let Some(rect) = self.active_caret_rect() {
            window.set_ime_cursor_location(
                rect.x.round() as i32,
                rect.y.round() as i32,
                rect.width.round() as i32,
                rect.height.round() as i32,
            );
            if let Some(ref active) = self.active_focus {
                window.set_ime_surrounding_text(
                    &active.state.text.get(),
                    active.state.cursor_index.get() as i32,
                );
            }
        } else {
            window.reset_ime();
        }
    }

    /// Directly updates GTK IME context with current caret location if running on Linux GTK.
    pub fn update_gtk_ime_location(&self) {
        #[cfg(target_os = "linux")]
        {
            if let Some(rect) = self.active_caret_rect() {
                strata_platform::gtk_set_ime_cursor_location(
                    rect.x.round() as i32,
                    rect.y.round() as i32,
                    rect.width.round() as i32,
                    rect.height.round() as i32,
                );
                if let Some(ref active) = self.active_focus {
                    strata_platform::gtk_set_ime_surrounding_text(
                        &active.state.text.get(),
                        active.state.cursor_index.get() as i32,
                    );
                }
            } else {
                strata_platform::gtk_reset_ime();
            }
        }
    }
}