liora-components 0.1.21

Enterprise-style native GPUI component library for Liora applications.
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
//! Paragraph module.
//!
//! This public module implements the Liora selectable paragraph/text-run composition component. It keeps the reusable
//! component logic inside `liora-components` rather than host applications so
//! downstream GPUI applications can compose the same behavior with their own
//! app state, assets, and release policy.
//!
//! ## Usage model
//!
//! Components in this module render native GPUI element trees. Stateless builder
//! values can be constructed inline, while controls with focus, selection,
//! popup, drag, or editing state should be stored as `gpui::Entity<T>` fields in
//! the parent view so state survives GPUI render passes.
//!
//! ## Design contract
//!
//! The implementation should use Liora theme tokens from `liora-core` and
//! `liora-theme`, keep accessibility-oriented keyboard/pointer behavior close to
//! the component, and avoid app-specific host-application resources in this SDK
//! crate.

use crate::{SelectableText, SelectableTextOptions, SelectableTextWrap, Text};
use gpui::{
    App, Component, ElementId, IntoElement, RenderOnce, SharedString, StyledText, TextRun,
    TextStyle, WhiteSpace, Window, div, prelude::*, px,
};
use liora_core::{
    Config, LocalizedText, code_font_family, code_font_weight, ui_font_family, ui_font_weight,
};
use std::{
    collections::hash_map::DefaultHasher,
    hash::{Hash, Hasher},
    panic::Location,
};

/// Fluent native GPUI component for rendering Liora paragraph.
pub struct Paragraph {
    children: Vec<Text>,
    selectable: bool,
    id: SharedString,
}

impl Paragraph {
    /// Creates `Paragraph` with default theme-driven styling and no optional callbacks attached.
    #[track_caller]
    pub fn new() -> Self {
        Self {
            children: Vec::new(),
            selectable: true,
            id: default_paragraph_id("", Location::caller()),
        }
    }

    /// Applies the text preset.
    #[track_caller]
    pub fn with_text(text: impl Into<LocalizedText>) -> Self {
        let text = text.into();
        let id = default_paragraph_id(text.stable_seed(), Location::caller());
        Self {
            children: vec![Text::new(text)],
            selectable: true,
            id,
        }
    }

    /// Adds a child element to the component body.
    pub fn child(mut self, child: Text) -> Self {
        self.children.push(child);
        self
    }

    /// Replaces or appends child elements rendered by the component.
    pub fn children(mut self, children: impl IntoIterator<Item = Text>) -> Self {
        self.children.extend(children);
        self
    }

    /// Toggles whether the rendered text can be selected.
    pub fn selectable(mut self, selectable: bool) -> Self {
        self.selectable = selectable;
        self
    }

    /// Assigns a stable element id used by GPUI state, hit testing, and automated interaction tests.
    pub fn id(mut self, id: impl Into<SharedString>) -> Self {
        self.id = id.into();
        self
    }

    /// Registers GPUI key bindings required for keyboard interaction.
    pub fn register_key_bindings(cx: &mut App) {
        SelectableText::register_key_bindings(cx);
    }

    fn default_text_style(
        theme: &liora_theme::Theme,
        ui_family: Option<SharedString>,
        ui_weight: Option<gpui::FontWeight>,
    ) -> TextStyle {
        let font_size = px(theme.font_size.md);
        let mut style = TextStyle::default();
        style.color = theme.neutral.text_2;
        style.font_size = font_size.into();
        style.line_height = px(theme.font_size.md * 1.6).into();
        style.white_space = WhiteSpace::Normal;
        style.text_overflow = None;
        style.line_clamp = None;
        if let Some(family) = ui_family {
            style.font_family = family;
        }
        if let Some(weight) = ui_weight {
            style.font_weight = weight;
        }
        style
    }

    pub(crate) fn selectable_text_parts(
        &self,
        cx: &impl liora_core::LocalesContext,
        theme: &liora_theme::Theme,
        code_family: Option<SharedString>,
        ui_family: Option<SharedString>,
        code_weight: Option<gpui::FontWeight>,
        ui_weight: Option<gpui::FontWeight>,
    ) -> (SharedString, Vec<TextRun>) {
        let default_style = Self::default_text_style(theme, ui_family.clone(), ui_weight);
        let mut full_text = String::new();
        let mut runs: Vec<TextRun> = Vec::new();

        for segment in &self.children {
            if segment.content.is_empty() {
                continue;
            }

            let segment_text = segment.content.inline(cx);
            let text = segment_text.as_ref();
            let leading_glue_len = if runs.is_empty() {
                0
            } else {
                leading_no_line_start_len(text)
            };

            if leading_glue_len > 0 {
                full_text.push_str(&text[..leading_glue_len]);
                if let Some(previous_run) = runs.last_mut() {
                    previous_run.len += leading_glue_len;
                }
            }

            let remaining = &text[leading_glue_len..];
            if !remaining.is_empty() {
                full_text.push_str(remaining);
                let mut segment = segment.clone();
                if segment.weight.is_none() {
                    segment.weight = if segment.is_code_style {
                        code_weight.or(ui_weight)
                    } else {
                        ui_weight
                    };
                }
                if segment.is_code_style && segment.font_family.is_none() {
                    segment.font_family =
                        Some(code_family.clone().unwrap_or_else(|| "Monospace".into()));
                } else if !segment.is_code_style && segment.font_family.is_none() {
                    segment.font_family = ui_family.clone();
                }
                let mut run = segment.to_text_run(&default_style, remaining.len());
                run.len = remaining.len();
                runs.push(run);
            }
        }

        (full_text.into(), runs)
    }
}

fn default_paragraph_id(seed: &str, location: &Location<'_>) -> SharedString {
    let mut hasher = DefaultHasher::new();
    seed.hash(&mut hasher);
    format!(
        "paragraph-{}:{}:{}-{:016x}",
        location.file(),
        location.line(),
        location.column(),
        hasher.finish()
    )
    .into()
}

fn leading_no_line_start_len(text: &str) -> usize {
    let Some(first) = text.chars().next() else {
        return 0;
    };

    if !is_no_line_start_punctuation(first) {
        return 0;
    }

    let mut end = 0;
    let mut saw_punctuation = false;
    for (index, ch) in text.char_indices() {
        if is_no_line_start_punctuation(ch) {
            saw_punctuation = true;
            end = index + ch.len_utf8();
            continue;
        }

        if saw_punctuation && ch.is_whitespace() {
            end = index + ch.len_utf8();
            continue;
        }

        break;
    }

    end
}

fn is_no_line_start_punctuation(ch: char) -> bool {
    matches!(
        ch,
        ':' | ''
            | ','
            | ''
            | '.'
            | ''
            | ';'
            | ''
            | '!'
            | ''
            | '?'
            | ''
            | ''
            | ')'
            | ''
            | ']'
            | ''
            | '}'
            | ''
            | ''
            | ''
            | ''
            | ''
    )
}

impl RenderOnce for Paragraph {
    fn render(self, _window: &mut Window, cx: &mut App) -> impl IntoElement {
        let theme = &cx.global::<Config>().theme;
        let code_family = code_font_family(cx);
        let ui_family = ui_font_family(cx);
        let code_weight = code_font_weight(cx);
        let ui_weight = ui_font_weight(cx);
        let (full_text, runs) = self.selectable_text_parts(
            cx,
            theme,
            Some(code_family),
            ui_family.clone(),
            code_weight,
            ui_weight,
        );
        let font_size = px(theme.font_size.md);

        if self.selectable {
            return SelectableText::view(
                SelectableTextOptions {
                    id: ElementId::from(self.id.clone()),
                    text: full_text,
                    runs,
                    font_size,
                    line_height: font_size * 1.6,
                    text_color: theme.neutral.text_2,
                    wrap: SelectableTextWrap::Normal,
                    key_context: "SelectableText",
                    fill_width: true,
                    font_family: ui_family,
                },
                _window,
                cx,
            );
        }

        let mut paragraph = div()
            .w_full()
            .text_size(font_size)
            .line_height(font_size * 1.6)
            .text_color(theme.neutral.text_2)
            .whitespace_normal()
            .child(StyledText::new(full_text).with_runs(runs));

        if let Some(family) = ui_family {
            paragraph = paragraph.font_family(family);
        }

        paragraph.into_any_element()
    }
}

impl IntoElement for Paragraph {
    type Element = Component<Self>;
    fn into_element(self) -> Self::Element {
        Component::new(self)
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    use gpui::{FontStyle, FontWeight};

    #[test]
    fn paragraph_default_id_is_stable_across_render_rebuilds() {
        let source = include_str!("paragraph.rs")
            .split("#[cfg(test)]")
            .next()
            .unwrap();

        assert!(source.contains("#[track_caller]"));
        assert!(source.contains("fn default_paragraph_id"));
        assert!(!source.contains(r#"liora_core::unique_id("paragraph")"#));
    }

    #[test]
    fn paragraph_defaults_to_mouse_selectable() {
        assert!(Paragraph::new().selectable);
        assert!(Paragraph::with_text("Selectable paragraph").selectable);
    }

    #[test]
    fn text_and_paragraph_use_selectable_text_for_native_selection() {
        let text_source = include_str!("text.rs");
        let paragraph_source = include_str!("paragraph.rs");
        let selectable_source = include_str!("selectable_text.rs");

        assert!(text_source.contains("SelectableText::view"));
        assert!(paragraph_source.contains("SelectableText::view"));
        assert!(text_source.contains("pub fn selectable"));
        assert!(paragraph_source.contains("pub fn selectable"));
        assert!(selectable_source.contains("event.click_count == 2"));
        assert!(selectable_source.contains("ClipboardItem::new_string"));
        assert!(selectable_source.contains(r#"KeyBinding::new("ctrl-c""#));
        assert!(selectable_source.contains("window.capture_pointer"));
        assert!(selectable_source.contains("cx.on_blur(&self.focus_handle"));
        assert!(selectable_source.contains("fn clear_selection"));
    }

    #[test]
    fn paragraph_composes_segments_into_one_styled_text_run_list() {
        let theme = liora_theme::Theme::light();
        let locales = liora_core::LocalesConfig::default();
        let (text, runs) = Paragraph::new()
            .child(Text::new("Hello ").bold())
            .child(Text::new("世界").italic())
            .selectable_text_parts(&locales, &theme, Some("Monospace".into()), None, None, None);

        assert_eq!(text.as_ref(), "Hello 世界");
        assert_eq!(runs.len(), 2);
        assert_eq!(runs[0].len, "Hello ".len());
        assert_eq!(runs[1].len, "世界".len());
        assert_eq!(runs[0].font.weight, FontWeight::BOLD);
        assert_eq!(runs[1].font.style, FontStyle::Italic);
    }

    #[test]
    fn paragraph_glues_line_start_forbidden_punctuation_to_previous_run() {
        let theme = liora_theme::Theme::light();
        let locales = liora_core::LocalesConfig::default();
        let (text, runs) = Paragraph::new()
            .child(Text::new("crates/liora-components").code_style(&theme))
            .child(Text::new(":所有可复用组件,例如 "))
            .child(Text::new("Button").code_style(&theme))
            .child(Text::new(""))
            .child(Text::new("Input").code_style(&theme))
            .child(Text::new(""))
            .selectable_text_parts(&locales, &theme, Some("Monospace".into()), None, None, None);

        assert_eq!(
            text.as_ref(),
            "crates/liora-components:所有可复用组件,例如 Button、Input。"
        );
        assert_eq!(runs[0].len, "crates/liora-components:".len());
        assert_eq!(runs[2].len, "Button、".len());
        assert_eq!(runs[3].len, "Input。".len());
    }

    #[test]
    fn text_segments_map_inline_code_style_to_text_runs_without_forcing_app_font() {
        let theme = liora_theme::Theme::light();
        let default_style = Paragraph::default_text_style(&theme, None, None);
        let run = Text::new("code")
            .code_style(&theme)
            .bold()
            .underline()
            .to_text_run(&default_style, "code".len());

        assert_eq!(run.len, "code".len());
        assert_eq!(run.font.family.as_ref(), ".SystemUIFont");
        assert_eq!(run.font.weight, FontWeight::BOLD);
        assert_eq!(run.color, theme.danger.base);
        assert_eq!(run.background_color, Some(theme.neutral.hover));
        assert!(run.underline.is_some());
    }

    #[test]
    fn paragraph_default_style_accepts_app_ui_font_family_and_weight() {
        let theme = liora_theme::Theme::light();
        let style =
            Paragraph::default_text_style(&theme, Some("MiSans".into()), Some(FontWeight::MEDIUM));

        assert_eq!(style.font_family.as_ref(), "MiSans");
        assert_eq!(style.font_weight, FontWeight::MEDIUM);
    }

    #[test]
    fn paragraph_default_style_keeps_native_wrapping_without_truncation() {
        let theme = liora_theme::Theme::light();
        let style = Paragraph::default_text_style(&theme, None, None);

        assert_eq!(style.white_space, WhiteSpace::Normal);
        assert!(style.text_overflow.is_none());
        assert!(style.line_clamp.is_none());
    }
}