Skip to main content

gpui/elements/
text.rs

1use crate::{
2    ActiveTooltip, AnyView, App, Bounds, DispatchPhase, Element, ElementId, GlobalElementId,
3    HighlightStyle, Hitbox, HitboxBehavior, InspectorElementId, IntoElement, LayoutId,
4    MouseDownEvent, MouseMoveEvent, MouseUpEvent, Pixels, Point, SharedString, Size, TextOverflow,
5    TextRun, TextStyle, TooltipId, TruncateFrom, WhiteSpace, Window, WrappedLine,
6    WrappedLineLayout, register_tooltip_mouse_handlers, set_tooltip_on_window,
7};
8use anyhow::Context as _;
9use gpui_util::ResultExt;
10use itertools::Itertools;
11use smallvec::SmallVec;
12use std::{
13    borrow::Cow,
14    cell::{Cell, RefCell},
15    mem,
16    ops::{Deref, DerefMut, Range},
17    rc::Rc,
18    sync::Arc,
19};
20
21/// An [`Element`] that renders text.
22///
23/// In general, [`Text`] objects should be created via the [`text`] macro:
24/// ```rust
25/// # use gpui::*;
26/// # fn render() -> impl IntoElement {
27/// div().child(text!("hello"))
28/// # }
29/// ```
30/// ## IDs and Accessibility
31///
32/// [`Text`] elements have an ID. This ID is primarily used to produce nodes in
33/// the accessibility tree, which allows the text to be visible to screen
34/// readers and other assistive technologies.
35///
36/// This ID is stable across frames. If the same text, with the same ID, is
37/// present in two consecutive frames, no updates are reported to the screen
38/// reader. If the text changes, but the ID stays the same, then the screen
39/// reader will be notified that a text node's content has changed. **However**,
40/// if the ID changes, then the screen reader will be notified that a node has
41/// been removed, and a new node has been added.
42///
43/// When using the [`text`] macro, each invocation of the macro will get a
44/// unique ID, derived from its position in the source code (filename, line, and
45/// column). For example:
46/// ```rust
47/// # use gpui::*;
48/// let x = text!("hello");
49/// let y = text!("hello");
50/// // not equal, because different `text!` invocations produced them
51/// assert_ne!(x.id(), y.id());
52///
53/// fn make_text(s: &str) -> Text { text!(s) }
54/// let x = make_text("hello");
55/// let y = make_text("hello");
56/// // equal, because the same `text!` invocation produced them
57/// assert_eq!(x.id(), y.id());
58/// ```
59/// When the contents of an invocation of [`text`] do not change, this
60/// distinction is less relevant (with the caveat that you still need to take
61/// care to ensure that duplicate IDs do not appear).
62///
63/// However, when a [`text`] invocation's argument *does* change, you should
64/// consider whether this change should be reported as a node "updating its
65/// contents", or an old node being destroyed and a new node being created.
66#[derive(Debug, Clone)]
67pub struct Text {
68    id: Option<ElementId>,
69    text: SharedString,
70}
71
72impl Text {
73    /// Create a new [`Text`] element with a specific ID.
74    ///
75    /// If you want a unique ID to be assigned automatically, use the [`text`]
76    /// macro. The docs for [`Text`] have more detail about choosing IDs.
77    #[inline]
78    pub const fn new(id: ElementId, text: SharedString) -> Self {
79        Self { id: Some(id), text }
80    }
81
82    /// Create a new [`Text`] element that is inaccessible to screen readers.
83    ///
84    /// In order for text to be accessible to screen readers, it must have an ID
85    /// provided. If you want text to be accessible, either use [`text`] to have
86    /// an ID automatically assigned, or use [`Text::new`] to manually assign an
87    /// ID.
88    ///
89    /// This function is intended for use inside custom UI components, where
90    /// accessible properties may be set on parent containers.
91    #[inline]
92    pub const fn new_inaccessible(text: SharedString) -> Self {
93        Self { id: None, text }
94    }
95
96    /// The ID of this [`Text`] element.
97    #[inline]
98    pub const fn id(&self) -> Option<&ElementId> {
99        self.id.as_ref()
100    }
101
102    /// Produce a new [`Text`] with the given `id`.
103    pub fn with_id(mut self, id: impl Into<ElementId>) -> Self {
104        self.id = Some(id.into());
105        self
106    }
107
108    /// The text that this [`Text`] element will display.
109    #[inline]
110    pub const fn text(&self) -> &SharedString {
111        &self.text
112    }
113}
114
115impl Deref for Text {
116    type Target = SharedString;
117    fn deref(&self) -> &Self::Target {
118        &self.text
119    }
120}
121
122impl DerefMut for Text {
123    fn deref_mut(&mut self) -> &mut Self::Target {
124        &mut self.text
125    }
126}
127
128/// Trivial hash function for the location information produced by the [`text`]
129/// macro. Not covered by semver guarantees. Performance is not particularly
130/// significant because it's only used on small strings in const contexts.
131#[doc(hidden)]
132pub const fn __hash_text_macro_location_unstable_do_not_use(s: &'static str) -> u64 {
133    const BASIS: u64 = 0xcbf29ce484222325;
134    const PRIME: u64 = 0x100000001b3;
135
136    let bytes = s.as_bytes();
137    let mut hash = BASIS;
138    let mut i = 0;
139    while i < bytes.len() {
140        hash ^= bytes[i] as u64;
141        hash = hash.wrapping_mul(PRIME);
142        i += 1;
143    }
144    hash
145}
146
147/// Create a new [`Text`] element.
148///
149/// ```rust
150/// # use gpui::*;
151/// let a = text!("hello");
152/// let b = text!(id = "farewell-message", "hello");
153///
154/// ```
155///
156/// Text created with this macro is *accessible*. The macro generates an ID
157/// based on the source location. See the docs for [`Text`] for a more in-depth
158/// explanation of the significance of the ID of a [`Text`] element.
159#[macro_export]
160macro_rules! text {
161    (id = $id:expr, $text:expr) => {{ $crate::Text::new($id.into(), $text.into()) }};
162    ($text:expr) => {{
163        const ID: &'static str = concat!(file!(), "/", line!(), ":", column!());
164        const HASH: u64 = $crate::__hash_text_macro_location_unstable_do_not_use(ID);
165        $crate::Text::new($crate::ElementId::Integer(HASH), $text.into())
166    }};
167}
168
169impl Element for Text {
170    type RequestLayoutState = TextLayout;
171    type PrepaintState = ();
172
173    fn id(&self) -> Option<ElementId> {
174        self.id.clone()
175    }
176
177    fn source_location(&self) -> Option<&'static std::panic::Location<'static>> {
178        None
179    }
180
181    fn a11y_role(&self) -> Option<accesskit::Role> {
182        if self.id.is_some() {
183            Some(accesskit::Role::Label)
184        } else {
185            None
186        }
187    }
188
189    fn write_a11y_info(&self, node: &mut accesskit::Node) {
190        node.set_value(self.text.to_string());
191    }
192
193    fn request_layout(
194        &mut self,
195        id: Option<&GlobalElementId>,
196        inspector_id: Option<&InspectorElementId>,
197        window: &mut Window,
198        cx: &mut App,
199    ) -> (LayoutId, Self::RequestLayoutState) {
200        <SharedString as Element>::request_layout(&mut self.text, id, inspector_id, window, cx)
201    }
202
203    fn prepaint(
204        &mut self,
205        id: Option<&GlobalElementId>,
206        inspector_id: Option<&InspectorElementId>,
207        bounds: Bounds<Pixels>,
208        request_layout: &mut Self::RequestLayoutState,
209        window: &mut Window,
210        cx: &mut App,
211    ) -> Self::PrepaintState {
212        <SharedString as Element>::prepaint(
213            &mut self.text,
214            id,
215            inspector_id,
216            bounds,
217            request_layout,
218            window,
219            cx,
220        )
221    }
222
223    fn paint(
224        &mut self,
225        id: Option<&GlobalElementId>,
226        inspector_id: Option<&InspectorElementId>,
227        bounds: Bounds<Pixels>,
228        request_layout: &mut Self::RequestLayoutState,
229        prepaint: &mut Self::PrepaintState,
230        window: &mut Window,
231        cx: &mut App,
232    ) {
233        <SharedString as Element>::paint(
234            &mut self.text,
235            id,
236            inspector_id,
237            bounds,
238            request_layout,
239            prepaint,
240            window,
241            cx,
242        );
243    }
244}
245
246impl Element for &'static str {
247    type RequestLayoutState = TextLayout;
248    type PrepaintState = ();
249
250    fn id(&self) -> Option<ElementId> {
251        None
252    }
253
254    fn source_location(&self) -> Option<&'static core::panic::Location<'static>> {
255        None
256    }
257
258    fn request_layout(
259        &mut self,
260        _id: Option<&GlobalElementId>,
261        _inspector_id: Option<&InspectorElementId>,
262        window: &mut Window,
263        cx: &mut App,
264    ) -> (LayoutId, Self::RequestLayoutState) {
265        let state = TextLayout::default();
266        let layout_id = state.layout(SharedString::new_static(self), None, window, cx);
267        (layout_id, state)
268    }
269
270    fn prepaint(
271        &mut self,
272        _id: Option<&GlobalElementId>,
273        _inspector_id: Option<&InspectorElementId>,
274        bounds: Bounds<Pixels>,
275        text_layout: &mut Self::RequestLayoutState,
276        _window: &mut Window,
277        _cx: &mut App,
278    ) {
279        text_layout.prepaint(bounds, self)
280    }
281
282    fn paint(
283        &mut self,
284        _id: Option<&GlobalElementId>,
285        _inspector_id: Option<&InspectorElementId>,
286        _bounds: Bounds<Pixels>,
287        text_layout: &mut TextLayout,
288        _: &mut (),
289        window: &mut Window,
290        cx: &mut App,
291    ) {
292        text_layout.paint(self, window, cx)
293    }
294}
295
296impl IntoElement for String {
297    type Element = SharedString;
298
299    fn into_element(self) -> Self::Element {
300        self.into()
301    }
302}
303
304impl IntoElement for Cow<'static, str> {
305    type Element = SharedString;
306
307    fn into_element(self) -> Self::Element {
308        self.into()
309    }
310}
311
312impl Element for SharedString {
313    type RequestLayoutState = TextLayout;
314    type PrepaintState = ();
315
316    fn id(&self) -> Option<ElementId> {
317        None
318    }
319
320    fn source_location(&self) -> Option<&'static core::panic::Location<'static>> {
321        None
322    }
323
324    fn request_layout(
325        &mut self,
326        _id: Option<&GlobalElementId>,
327        _inspector_id: Option<&InspectorElementId>,
328        window: &mut Window,
329        cx: &mut App,
330    ) -> (LayoutId, Self::RequestLayoutState) {
331        let state = TextLayout::default();
332        let layout_id = state.layout(self.clone(), None, window, cx);
333        (layout_id, state)
334    }
335
336    fn prepaint(
337        &mut self,
338        _id: Option<&GlobalElementId>,
339        _inspector_id: Option<&InspectorElementId>,
340        bounds: Bounds<Pixels>,
341        text_layout: &mut Self::RequestLayoutState,
342        _window: &mut Window,
343        _cx: &mut App,
344    ) {
345        text_layout.prepaint(bounds, self.as_ref())
346    }
347
348    fn paint(
349        &mut self,
350        _id: Option<&GlobalElementId>,
351        _inspector_id: Option<&InspectorElementId>,
352        _bounds: Bounds<Pixels>,
353        text_layout: &mut Self::RequestLayoutState,
354        _: &mut Self::PrepaintState,
355        window: &mut Window,
356        cx: &mut App,
357    ) {
358        text_layout.paint(self.as_ref(), window, cx)
359    }
360}
361
362/// Renders text with runs of different styles.
363///
364/// Callers are responsible for setting the correct style for each run.
365/// For text with a uniform style, you can usually avoid calling this constructor
366/// and just pass text directly.
367pub struct StyledText {
368    text: SharedString,
369    runs: Option<Vec<TextRun>>,
370    delayed_highlights: Option<Vec<(Range<usize>, HighlightStyle)>>,
371    delayed_font_family_overrides: Option<Vec<(Range<usize>, SharedString)>>,
372    layout: TextLayout,
373}
374
375impl StyledText {
376    /// Construct a new styled text element from the given string.
377    pub fn new(text: impl Into<SharedString>) -> Self {
378        StyledText {
379            text: text.into(),
380            runs: None,
381            delayed_highlights: None,
382            delayed_font_family_overrides: None,
383            layout: TextLayout::default(),
384        }
385    }
386
387    /// Get the layout for this element. This can be used to map indices to pixels and vice versa.
388    pub fn layout(&self) -> &TextLayout {
389        &self.layout
390    }
391
392    /// Set the styling attributes for the given text, as well as
393    /// as any ranges of text that have had their style customized.
394    pub fn with_default_highlights(
395        self,
396        default_style: &TextStyle,
397        highlights: impl IntoIterator<Item = (Range<usize>, HighlightStyle)>,
398    ) -> Self {
399        debug_assert!(
400            self.delayed_highlights.is_none(),
401            "Can't use `with_default_highlights` and `with_highlights`"
402        );
403        let runs = Self::compute_runs(&self.text, default_style, highlights);
404        self.with_runs(runs)
405    }
406
407    /// Set the styling attributes for the given text, as well as
408    /// as any ranges of text that have had their style customized.
409    pub fn with_highlights(
410        mut self,
411        highlights: impl IntoIterator<Item = (Range<usize>, HighlightStyle)>,
412    ) -> Self {
413        debug_assert!(
414            self.runs.is_none(),
415            "Can't use `with_highlights` and `with_default_highlights`"
416        );
417        self.delayed_highlights = Some(
418            highlights
419                .into_iter()
420                .inspect(|(run, _)| {
421                    debug_assert!(self.text.is_char_boundary(run.start));
422                    debug_assert!(self.text.is_char_boundary(run.end));
423                })
424                .collect::<Vec<_>>(),
425        );
426        self
427    }
428
429    fn compute_runs(
430        text: &str,
431        default_style: &TextStyle,
432        highlights: impl IntoIterator<Item = (Range<usize>, HighlightStyle)>,
433    ) -> Vec<TextRun> {
434        let mut runs = Vec::new();
435        let mut ix = 0;
436        for (range, highlight) in highlights {
437            if ix < range.start {
438                debug_assert!(text.is_char_boundary(range.start));
439                runs.push(default_style.clone().to_run(range.start - ix));
440            }
441            debug_assert!(text.is_char_boundary(range.end));
442            runs.push(
443                default_style
444                    .clone()
445                    .highlight(highlight)
446                    .to_run(range.len()),
447            );
448            ix = range.end;
449        }
450        if ix < text.len() {
451            runs.push(default_style.to_run(text.len() - ix));
452        }
453        runs
454    }
455
456    /// Override the font family for specific byte ranges of the text.
457    ///
458    /// This is resolved lazily at layout time, so the overrides are applied
459    /// on top of the inherited text style from the parent element.
460    /// Can be combined with [`with_highlights`](Self::with_highlights).
461    ///
462    /// The overrides must be sorted by range start and non-overlapping.
463    /// Each override range must fall on character boundaries.
464    pub fn with_font_family_overrides(
465        mut self,
466        overrides: impl IntoIterator<Item = (Range<usize>, SharedString)>,
467    ) -> Self {
468        self.delayed_font_family_overrides = Some(
469            overrides
470                .into_iter()
471                .inspect(|(range, _)| {
472                    debug_assert!(self.text.is_char_boundary(range.start));
473                    debug_assert!(self.text.is_char_boundary(range.end));
474                })
475                .collect(),
476        );
477        self
478    }
479
480    fn apply_font_family_overrides(
481        runs: &mut [TextRun],
482        overrides: &[(Range<usize>, SharedString)],
483    ) {
484        let mut byte_offset = 0;
485        let mut override_idx = 0;
486        for run in runs.iter_mut() {
487            let run_end = byte_offset + run.len;
488            while override_idx < overrides.len() && overrides[override_idx].0.end <= byte_offset {
489                override_idx += 1;
490            }
491            if override_idx < overrides.len() {
492                let (ref range, ref family) = overrides[override_idx];
493                if byte_offset >= range.start && run_end <= range.end {
494                    run.font.family = family.clone();
495                }
496            }
497            byte_offset = run_end;
498        }
499    }
500
501    /// Set the text runs for this piece of text.
502    pub fn with_runs(mut self, runs: Vec<TextRun>) -> Self {
503        let mut text = &*self.text;
504        for run in &runs {
505            text = text.get(run.len..).unwrap_or_else(|| {
506                #[cfg(debug_assertions)]
507                panic!("invalid text run. Text: '{text}', run: {run:?}");
508                #[cfg(not(debug_assertions))]
509                panic!("invalid text run");
510            });
511        }
512        assert!(text.is_empty(), "invalid text run");
513        self.runs = Some(runs);
514        self
515    }
516}
517
518impl Element for StyledText {
519    type RequestLayoutState = ();
520    type PrepaintState = ();
521
522    fn id(&self) -> Option<ElementId> {
523        None
524    }
525
526    fn source_location(&self) -> Option<&'static core::panic::Location<'static>> {
527        None
528    }
529
530    fn request_layout(
531        &mut self,
532        _id: Option<&GlobalElementId>,
533        _inspector_id: Option<&InspectorElementId>,
534        window: &mut Window,
535        cx: &mut App,
536    ) -> (LayoutId, Self::RequestLayoutState) {
537        let font_family_overrides = self.delayed_font_family_overrides.take();
538        let mut runs = self.runs.take().or_else(|| {
539            self.delayed_highlights.take().map(|delayed_highlights| {
540                Self::compute_runs(&self.text, &window.text_style(), delayed_highlights)
541            })
542        });
543
544        if let Some(ref overrides) = font_family_overrides {
545            let runs =
546                runs.get_or_insert_with(|| vec![window.text_style().to_run(self.text.len())]);
547            Self::apply_font_family_overrides(runs, overrides);
548        }
549
550        let layout_id = self.layout.layout(self.text.clone(), runs, window, cx);
551        (layout_id, ())
552    }
553
554    fn prepaint(
555        &mut self,
556        _id: Option<&GlobalElementId>,
557        _inspector_id: Option<&InspectorElementId>,
558        bounds: Bounds<Pixels>,
559        _: &mut Self::RequestLayoutState,
560        _window: &mut Window,
561        _cx: &mut App,
562    ) {
563        self.layout.prepaint(bounds, &self.text)
564    }
565
566    fn paint(
567        &mut self,
568        _id: Option<&GlobalElementId>,
569        _inspector_id: Option<&InspectorElementId>,
570        _bounds: Bounds<Pixels>,
571        _: &mut Self::RequestLayoutState,
572        _: &mut Self::PrepaintState,
573        window: &mut Window,
574        cx: &mut App,
575    ) {
576        self.layout.paint(&self.text, window, cx)
577    }
578}
579
580/// The Layout for TextElement. This can be used to map indices to pixels and vice versa.
581#[derive(Default, Clone)]
582pub struct TextLayout(Rc<RefCell<Option<TextLayoutInner>>>);
583
584#[derive(Clone, Copy)]
585enum TextPaintPass {
586    All,
587    Background,
588    Foreground,
589}
590
591struct TextLayoutInner {
592    len: usize,
593    lines: SmallVec<[WrappedLine; 1]>,
594    line_height: Pixels,
595    wrap_width: Option<Pixels>,
596    truncate_width: Option<Pixels>,
597    size: Option<Size<Pixels>>,
598    bounds: Option<Bounds<Pixels>>,
599}
600
601/// What a text element's size depends on, and where its measurement is stored for
602/// painting.
603pub(crate) struct TextMeasure {
604    text: SharedString,
605    runs: Vec<TextRun>,
606    text_style: TextStyle,
607    font_size: Pixels,
608    line_height: Pixels,
609    scale_factor: f32,
610    font_generation: usize,
611    element_state: TextLayout,
612}
613
614impl TextMeasure {
615    /// Takes over the lines `previous` measured, so a text element that hasn't changed
616    /// since the last frame can paint without being measured again.
617    fn reuse_measurement(&mut self, previous: &mut TextMeasure) -> bool {
618        if self.text != previous.text
619            || self.font_size != previous.font_size
620            || self.line_height != previous.line_height
621            || self.scale_factor != previous.scale_factor
622            || self.font_generation != previous.font_generation
623            || self.runs != previous.runs
624            || self.text_style != previous.text_style
625        {
626            return false;
627        }
628        // Whoever holds the previous frame's layout, such as an element reading it in an
629        // event handler, keeps it; otherwise it is moved rather than copied.
630        let measured = if Rc::strong_count(&previous.element_state.0) == 1 {
631            previous.element_state.0.borrow_mut().take()
632        } else {
633            previous
634                .element_state
635                .0
636                .borrow()
637                .as_ref()
638                .map(TextLayoutInner::clone_measurement)
639        };
640        let Some(mut measured) = measured else {
641            return false;
642        };
643        measured.bounds = None;
644        *self.element_state.0.borrow_mut() = Some(measured);
645        true
646    }
647
648    /// Measures the text. The size only depends on the measure's inputs and the space
649    /// given, never on what was measured before.
650    ///
651    /// The final measurement's lines (`final_layout`, made after any sizing probes) are
652    /// kept for painting, since Taffy may serve that measurement from its cache instead
653    /// of measuring again, and a probe's lines would be painted in bounds that weren't
654    /// computed from them.
655    fn measure(
656        &self,
657        known_dimensions: Size<Option<Pixels>>,
658        available_space: Size<crate::AvailableSpace>,
659        final_layout: bool,
660        window: &mut Window,
661        cx: &mut App,
662    ) -> Size<Pixels> {
663        let Self {
664            text,
665            runs,
666            text_style,
667            font_size,
668            line_height,
669            element_state,
670            ..
671        } = self;
672        let font_size = *font_size;
673        let line_height = *line_height;
674        let wrap_width = if text_style.white_space == WhiteSpace::Normal {
675            known_dimensions.width.or(match available_space.width {
676                crate::AvailableSpace::Definite(x) => Some(x),
677                _ => None,
678            })
679        } else {
680            None
681        };
682
683        let (truncate_width, truncation_affix, truncate_from) =
684            if let Some(text_overflow) = text_style.text_overflow.clone() {
685                let width = known_dimensions.width.or(match available_space.width {
686                    crate::AvailableSpace::Definite(x) => match text_style.line_clamp {
687                        Some(max_lines) => Some(x * max_lines),
688                        None => Some(x),
689                    },
690                    _ => None,
691                });
692
693                match text_overflow {
694                    TextOverflow::Truncate(s) => (width, s, TruncateFrom::End),
695                    TextOverflow::TruncateStart(s) => (width, s, TruncateFrom::Start),
696                    TextOverflow::TruncateMiddle(s) => (width, s, TruncateFrom::Middle),
697                }
698            } else {
699                (None, "".into(), TruncateFrom::End)
700            };
701
702        if let Some(text_layout) = element_state.0.borrow().as_ref()
703            && let Some(size) = text_layout.size
704            && wrap_width == text_layout.wrap_width
705            && truncate_width == text_layout.truncate_width
706        {
707            return size;
708        }
709
710        let (text, runs) = if let Some(truncate_width) = truncate_width {
711            // Taking a wrapper from the pool locks it twice and moves its
712            // character width cache around, so only do it when truncating.
713            let mut line_wrapper = cx.text_system().line_wrapper(text_style.font(), font_size);
714            if let Some(max_lines) = text_style.line_clamp
715                && let Some(wrap_width) = wrap_width
716            {
717                line_wrapper.truncate_wrapped_line(
718                    text.clone(),
719                    wrap_width,
720                    max_lines,
721                    &truncation_affix,
722                    &runs,
723                    truncate_from,
724                )
725            } else if let Some(unclipped) = window
726                .text_system()
727                .shape_text(text.clone(), font_size, &runs, None, None)
728                .log_err()
729                && unclipped
730                    .iter()
731                    .all(|line| line.size(line_height).width <= truncate_width)
732            {
733                // The truncation decision below sums per-character advances,
734                // which overestimates the shaped width (no kerning), truncating
735                // text that fits exactly in its measured width. Skip truncation
736                // whenever the honestly-shaped text fits; the shaping result
737                // comes from the line layout cache when the same text was
738                // already measured untruncated this frame.
739                (text.clone(), Cow::Borrowed(runs.as_slice()))
740            } else {
741                line_wrapper.truncate_line(
742                    text.clone(),
743                    truncate_width,
744                    &truncation_affix,
745                    &runs,
746                    truncate_from,
747                )
748            }
749        } else {
750            (text.clone(), Cow::Borrowed(runs.as_slice()))
751        };
752        let len = text.len();
753
754        // Text that fails to shape is measured as empty.
755        let (lines, len) = window
756            .text_system()
757            .shape_text(
758                text,
759                font_size,
760                &runs,
761                wrap_width,            // Wrap if we know the width.
762                text_style.line_clamp, // Limit the number of lines if line_clamp is set.
763            )
764            .log_err()
765            .map(|lines| (lines, len))
766            .unwrap_or_default();
767
768        let mut size: Size<Pixels> = Size::default();
769        for line in &lines {
770            let line_size = line.size(line_height);
771            size.height += line_size.height;
772            size.width = size.width.max(line_size.width).ceil();
773        }
774        if final_layout || element_state.0.borrow().is_none() {
775            element_state.0.borrow_mut().replace(TextLayoutInner {
776                lines,
777                len,
778                line_height,
779                wrap_width,
780                truncate_width,
781                size: Some(size),
782                bounds: None,
783            });
784        }
785        size
786    }
787}
788
789impl TextLayoutInner {
790    fn clone_measurement(&self) -> Self {
791        Self {
792            len: self.len,
793            lines: self
794                .lines
795                .iter()
796                .map(|line| WrappedLine {
797                    layout: line.layout.clone(),
798                    text: line.text.clone(),
799                    decoration_runs: line.decoration_runs.clone(),
800                })
801                .collect(),
802            line_height: self.line_height,
803            wrap_width: self.wrap_width,
804            truncate_width: self.truncate_width,
805            size: self.size,
806            bounds: None,
807        }
808    }
809}
810
811impl TextLayout {
812    fn layout(
813        &self,
814        text: SharedString,
815        runs: Option<Vec<TextRun>>,
816        window: &mut Window,
817        _: &mut App,
818    ) -> LayoutId {
819        window.request_keyed_measure(
820            &crate::Style::default(),
821            self.measurement(text, runs, window),
822            TextMeasure::reuse_measurement,
823            TextMeasure::measure,
824        )
825    }
826
827    fn measurement(
828        &self,
829        text: SharedString,
830        runs: Option<Vec<TextRun>>,
831        window: &Window,
832    ) -> TextMeasure {
833        let text_style = window.text_style();
834        let font_size = text_style.font_size.to_pixels(window.rem_size());
835        let line_height = window.pixel_snap(
836            text_style
837                .line_height
838                .to_pixels(font_size.into(), window.rem_size()),
839        );
840
841        let runs = if let Some(runs) = runs {
842            runs
843        } else {
844            vec![text_style.to_run(text.len())]
845        };
846        TextMeasure {
847            text,
848            runs,
849            text_style,
850            font_size,
851            line_height,
852            scale_factor: window.scale_factor(),
853            font_generation: window.text_system().font_generation(),
854            element_state: self.clone(),
855        }
856    }
857
858    fn prepaint(&self, bounds: Bounds<Pixels>, text: &str) {
859        let mut element_state = self.0.borrow_mut();
860        let element_state = element_state
861            .as_mut()
862            .with_context(|| format!("measurement has not been performed on {text}"))
863            .unwrap();
864        element_state.bounds = Some(bounds);
865    }
866
867    fn paint(&self, text: &str, window: &mut Window, cx: &mut App) {
868        self.paint_lines(TextPaintPass::All, window, cx)
869            .with_context(|| format!("failed to paint {text}"))
870            .unwrap();
871    }
872
873    /// Paints the backgrounds of the text runs without the glyphs, so that callers can paint
874    /// content, such as highlights, between the backgrounds and the text. Follow it with
875    /// [`Self::paint_foreground`] to paint the glyphs.
876    pub fn paint_background(&self, window: &mut Window, cx: &mut App) -> anyhow::Result<()> {
877        self.paint_lines(TextPaintPass::Background, window, cx)
878    }
879
880    /// Paints the glyphs and decorations of the text without the run backgrounds.
881    pub fn paint_foreground(&self, window: &mut Window, cx: &mut App) -> anyhow::Result<()> {
882        self.paint_lines(TextPaintPass::Foreground, window, cx)
883    }
884
885    fn paint_lines(
886        &self,
887        pass: TextPaintPass,
888        window: &mut Window,
889        cx: &mut App,
890    ) -> anyhow::Result<()> {
891        let element_state = self.0.borrow();
892        let element_state = element_state
893            .as_ref()
894            .context("measurement has not been performed")?;
895        let bounds = element_state
896            .bounds
897            .context("prepaint has not been performed")?;
898
899        let line_height = element_state.line_height;
900        let mut line_origin = bounds.origin;
901        let text_style = window.text_style();
902        for line in &element_state.lines {
903            if matches!(pass, TextPaintPass::All | TextPaintPass::Background) {
904                line.paint_background(
905                    line_origin,
906                    line_height,
907                    text_style.text_align,
908                    Some(bounds),
909                    window,
910                    cx,
911                )
912                .log_err();
913            }
914            if matches!(pass, TextPaintPass::All | TextPaintPass::Foreground) {
915                line.paint(
916                    line_origin,
917                    line_height,
918                    text_style.text_align,
919                    Some(bounds),
920                    window,
921                    cx,
922                )
923                .log_err();
924            }
925            line_origin.y += line.size(line_height).height;
926        }
927        Ok(())
928    }
929
930    /// Get the byte index into the input of the pixel position.
931    pub fn index_for_position(&self, position: Point<Pixels>) -> Result<usize, usize> {
932        let element_state = self.0.borrow();
933        let element_state = element_state
934            .as_ref()
935            .expect("measurement has not been performed");
936        let bounds = element_state
937            .bounds
938            .expect("prepaint has not been performed");
939
940        if position.y < bounds.top() {
941            return Err(0);
942        }
943
944        let line_height = element_state.line_height;
945        let mut line_origin = bounds.origin;
946        let mut line_start_ix = 0;
947        for line in &element_state.lines {
948            let line_bottom = line_origin.y + line.size(line_height).height;
949            if position.y > line_bottom {
950                line_origin.y = line_bottom;
951                line_start_ix += line.len() + 1;
952            } else {
953                let position_within_line = position - line_origin;
954                match line.index_for_position(position_within_line, line_height) {
955                    Ok(index_within_line) => return Ok(line_start_ix + index_within_line),
956                    Err(index_within_line) => return Err(line_start_ix + index_within_line),
957                }
958            }
959        }
960
961        Err(line_start_ix.saturating_sub(1))
962    }
963
964    /// Get the pixel position for the given byte index.
965    pub fn position_for_index(&self, index: usize) -> Option<Point<Pixels>> {
966        let element_state = self.0.borrow();
967        let element_state = element_state
968            .as_ref()
969            .expect("measurement has not been performed");
970        let bounds = element_state
971            .bounds
972            .expect("prepaint has not been performed");
973        let line_height = element_state.line_height;
974
975        let mut line_origin = bounds.origin;
976        let mut line_start_ix = 0;
977
978        for line in &element_state.lines {
979            let line_end_ix = line_start_ix + line.len();
980            if index < line_start_ix {
981                break;
982            } else if index > line_end_ix {
983                line_origin.y += line.size(line_height).height;
984                line_start_ix = line_end_ix + 1;
985                continue;
986            } else {
987                let ix_within_line = index - line_start_ix;
988                return Some(line_origin + line.position_for_index(ix_within_line, line_height)?);
989            }
990        }
991
992        None
993    }
994
995    /// Retrieve the layout for the line containing the given byte index.
996    pub fn line_layout_for_index(&self, index: usize) -> Option<Arc<WrappedLineLayout>> {
997        let element_state = self.0.borrow();
998        let element_state = element_state
999            .as_ref()
1000            .expect("measurement has not been performed");
1001        let mut line_start_ix = 0;
1002
1003        for line in &element_state.lines {
1004            let line_end_ix = line_start_ix + line.len();
1005            if index < line_start_ix {
1006                break;
1007            } else if index > line_end_ix {
1008                line_start_ix = line_end_ix + 1;
1009                continue;
1010            } else {
1011                return Some(line.layout.clone());
1012            }
1013        }
1014
1015        None
1016    }
1017
1018    /// Retrieve all line layouts in source order.
1019    pub fn line_layouts(&self) -> SmallVec<[Arc<WrappedLineLayout>; 1]> {
1020        self.0
1021            .borrow()
1022            .as_ref()
1023            .expect("measurement has not been performed")
1024            .lines
1025            .iter()
1026            .map(|line| line.layout.clone())
1027            .collect()
1028    }
1029
1030    /// The bounds of this layout.
1031    pub fn bounds(&self) -> Bounds<Pixels> {
1032        self.0.borrow().as_ref().unwrap().bounds.unwrap()
1033    }
1034
1035    /// The line height for this layout.
1036    pub fn line_height(&self) -> Pixels {
1037        self.0.borrow().as_ref().unwrap().line_height
1038    }
1039
1040    /// The UTF-8 length of the underlying text.
1041    pub fn len(&self) -> usize {
1042        self.0.borrow().as_ref().unwrap().len
1043    }
1044
1045    /// The text for this layout.
1046    pub fn text(&self) -> String {
1047        self.0
1048            .borrow()
1049            .as_ref()
1050            .unwrap()
1051            .lines
1052            .iter()
1053            .map(|s| &s.text)
1054            .join("\n")
1055    }
1056
1057    /// The text for this layout (with soft-wraps as newlines)
1058    pub fn wrapped_text(&self) -> String {
1059        let mut accumulator = String::new();
1060
1061        for wrapped in self.0.borrow().as_ref().unwrap().lines.iter() {
1062            let mut seen = 0;
1063            for boundary in wrapped.layout.wrap_boundaries.iter() {
1064                let index = wrapped.layout.unwrapped_layout.runs[boundary.run_ix].glyphs
1065                    [boundary.glyph_ix]
1066                    .index;
1067
1068                accumulator.push_str(&wrapped.text[seen..index]);
1069                accumulator.push('\n');
1070                seen = index;
1071            }
1072            accumulator.push_str(&wrapped.text[seen..]);
1073            accumulator.push('\n');
1074        }
1075        // Remove trailing newline
1076        accumulator.pop();
1077        accumulator
1078    }
1079}
1080
1081/// A text element that can be interacted with.
1082pub struct InteractiveText {
1083    element_id: ElementId,
1084    text: StyledText,
1085    click_listener:
1086        Option<Box<dyn Fn(&[Range<usize>], InteractiveTextClickEvent, &mut Window, &mut App)>>,
1087    hover_listener: Option<Box<dyn Fn(Option<usize>, MouseMoveEvent, &mut Window, &mut App)>>,
1088    tooltip_builder: Option<Rc<dyn Fn(usize, &mut Window, &mut App) -> Option<AnyView>>>,
1089    tooltip_id: Option<TooltipId>,
1090    clickable_ranges: Vec<Range<usize>>,
1091}
1092
1093struct InteractiveTextClickEvent {
1094    mouse_down_index: usize,
1095    mouse_up_index: usize,
1096}
1097
1098#[doc(hidden)]
1099#[derive(Default)]
1100pub struct InteractiveTextState {
1101    mouse_down_index: Rc<Cell<Option<usize>>>,
1102    hovered_index: Rc<Cell<Option<usize>>>,
1103    active_tooltip: Rc<RefCell<Option<ActiveTooltip>>>,
1104    long_press_tooltip_active: Rc<Cell<bool>>,
1105}
1106
1107/// InteractiveTest is a wrapper around StyledText that adds mouse interactions.
1108impl InteractiveText {
1109    /// Creates a new InteractiveText from the given text.
1110    pub fn new(id: impl Into<ElementId>, text: StyledText) -> Self {
1111        Self {
1112            element_id: id.into(),
1113            text,
1114            click_listener: None,
1115            hover_listener: None,
1116            tooltip_builder: None,
1117            tooltip_id: None,
1118            clickable_ranges: Vec::new(),
1119        }
1120    }
1121
1122    /// on_click is called when the user clicks on one of the given ranges, passing the index of
1123    /// the clicked range.
1124    pub fn on_click(
1125        mut self,
1126        ranges: Vec<Range<usize>>,
1127        listener: impl Fn(usize, &mut Window, &mut App) + 'static,
1128    ) -> Self {
1129        self.click_listener = Some(Box::new(move |ranges, event, window, cx| {
1130            for (range_ix, range) in ranges.iter().enumerate() {
1131                if range.contains(&event.mouse_down_index) && range.contains(&event.mouse_up_index)
1132                {
1133                    listener(range_ix, window, cx);
1134                }
1135            }
1136        }));
1137        self.clickable_ranges = ranges;
1138        self
1139    }
1140
1141    /// on_hover is called when the mouse moves over a character within the text, passing the
1142    /// index of the hovered character, or None if the mouse leaves the text.
1143    pub fn on_hover(
1144        mut self,
1145        listener: impl Fn(Option<usize>, MouseMoveEvent, &mut Window, &mut App) + 'static,
1146    ) -> Self {
1147        self.hover_listener = Some(Box::new(listener));
1148        self
1149    }
1150
1151    /// tooltip lets you specify a tooltip for a given character index in the string.
1152    pub fn tooltip(
1153        mut self,
1154        builder: impl Fn(usize, &mut Window, &mut App) -> Option<AnyView> + 'static,
1155    ) -> Self {
1156        self.tooltip_builder = Some(Rc::new(builder));
1157        self
1158    }
1159}
1160
1161impl Element for InteractiveText {
1162    type RequestLayoutState = ();
1163    type PrepaintState = Hitbox;
1164
1165    fn id(&self) -> Option<ElementId> {
1166        Some(self.element_id.clone())
1167    }
1168
1169    fn source_location(&self) -> Option<&'static core::panic::Location<'static>> {
1170        None
1171    }
1172
1173    fn a11y_role(&self) -> Option<accesskit::Role> {
1174        Some(accesskit::Role::Label)
1175    }
1176
1177    fn write_a11y_info(&self, node: &mut accesskit::Node) {
1178        node.set_value(self.text.text.to_string());
1179    }
1180
1181    fn request_layout(
1182        &mut self,
1183        _id: Option<&GlobalElementId>,
1184        inspector_id: Option<&InspectorElementId>,
1185        window: &mut Window,
1186        cx: &mut App,
1187    ) -> (LayoutId, Self::RequestLayoutState) {
1188        self.text.request_layout(None, inspector_id, window, cx)
1189    }
1190
1191    fn prepaint(
1192        &mut self,
1193        global_id: Option<&GlobalElementId>,
1194        inspector_id: Option<&InspectorElementId>,
1195        bounds: Bounds<Pixels>,
1196        state: &mut Self::RequestLayoutState,
1197        window: &mut Window,
1198        cx: &mut App,
1199    ) -> Hitbox {
1200        window.with_optional_element_state::<InteractiveTextState, _>(
1201            global_id,
1202            |interactive_state, window| {
1203                let mut interactive_state = interactive_state
1204                    .map(|interactive_state| interactive_state.unwrap_or_default());
1205
1206                if let Some(interactive_state) = interactive_state.as_mut() {
1207                    if self.tooltip_builder.is_some() {
1208                        self.tooltip_id =
1209                            set_tooltip_on_window(&interactive_state.active_tooltip, window);
1210                    } else {
1211                        // If there is no longer a tooltip builder, remove the active tooltip.
1212                        interactive_state.long_press_tooltip_active.set(false);
1213                        interactive_state.active_tooltip.take();
1214                    }
1215                }
1216
1217                self.text
1218                    .prepaint(None, inspector_id, bounds, state, window, cx);
1219                let hitbox = window.insert_hitbox(bounds, HitboxBehavior::Normal);
1220                (hitbox, interactive_state)
1221            },
1222        )
1223    }
1224
1225    fn paint(
1226        &mut self,
1227        global_id: Option<&GlobalElementId>,
1228        inspector_id: Option<&InspectorElementId>,
1229        bounds: Bounds<Pixels>,
1230        _: &mut Self::RequestLayoutState,
1231        hitbox: &mut Hitbox,
1232        window: &mut Window,
1233        cx: &mut App,
1234    ) {
1235        let current_view = window.current_view();
1236        let text_layout = self.text.layout().clone();
1237        window.with_element_state::<InteractiveTextState, _>(
1238            global_id.unwrap(),
1239            |interactive_state, window| {
1240                let interactive_state = interactive_state.unwrap_or_default();
1241                if let Some(click_listener) = self.click_listener.take() {
1242                    let mouse_position = window.mouse_position();
1243                    if let Ok(ix) = text_layout.index_for_position(mouse_position)
1244                        && self
1245                            .clickable_ranges
1246                            .iter()
1247                            .any(|range| range.contains(&ix))
1248                    {
1249                        window.set_cursor_style(crate::CursorStyle::PointingHand, hitbox)
1250                    }
1251
1252                    let text_layout = text_layout.clone();
1253                    let mouse_down = interactive_state.mouse_down_index.clone();
1254                    if let Some(mouse_down_index) = mouse_down.get() {
1255                        let hitbox = hitbox.clone();
1256                        let clickable_ranges = mem::take(&mut self.clickable_ranges);
1257                        window.on_mouse_event(
1258                            move |event: &MouseUpEvent, phase, window: &mut Window, cx| {
1259                                if phase == DispatchPhase::Bubble && hitbox.is_hovered(window) {
1260                                    if let Ok(mouse_up_index) =
1261                                        text_layout.index_for_position(event.position)
1262                                    {
1263                                        click_listener(
1264                                            &clickable_ranges,
1265                                            InteractiveTextClickEvent {
1266                                                mouse_down_index,
1267                                                mouse_up_index,
1268                                            },
1269                                            window,
1270                                            cx,
1271                                        )
1272                                    }
1273
1274                                    mouse_down.take();
1275                                    window.refresh();
1276                                }
1277                            },
1278                        );
1279                    } else {
1280                        let hitbox = hitbox.clone();
1281                        window.on_mouse_event(move |event: &MouseDownEvent, phase, window, _| {
1282                            if phase == DispatchPhase::Bubble
1283                                && hitbox.is_hovered(window)
1284                                && let Ok(mouse_down_index) =
1285                                    text_layout.index_for_position(event.position)
1286                            {
1287                                mouse_down.set(Some(mouse_down_index));
1288                                window.refresh();
1289                            }
1290                        });
1291                    }
1292                }
1293
1294                window.on_mouse_event({
1295                    let hover_listener = self.hover_listener.take();
1296                    let hitbox = hitbox.clone();
1297                    let text_layout = text_layout.clone();
1298                    let hovered_index = interactive_state.hovered_index.clone();
1299                    move |event: &MouseMoveEvent, phase, window, cx| {
1300                        if phase == DispatchPhase::Bubble && hitbox.is_hovered(window) {
1301                            let current = hovered_index.get();
1302                            let updated = text_layout.index_for_position(event.position).ok();
1303                            if current != updated {
1304                                hovered_index.set(updated);
1305                                if let Some(hover_listener) = hover_listener.as_ref() {
1306                                    hover_listener(updated, event.clone(), window, cx);
1307                                }
1308                                cx.notify(current_view);
1309                            }
1310                        }
1311                    }
1312                });
1313
1314                if let Some(tooltip_builder) = self.tooltip_builder.clone() {
1315                    let active_tooltip = interactive_state.active_tooltip.clone();
1316                    let build_tooltip = Rc::new({
1317                        let tooltip_is_hoverable = false;
1318                        let text_layout = text_layout.clone();
1319                        move |window: &mut Window, cx: &mut App| {
1320                            text_layout
1321                                .index_for_position(window.mouse_position())
1322                                .ok()
1323                                .and_then(|position| tooltip_builder(position, window, cx))
1324                                .map(|view| (view, tooltip_is_hoverable))
1325                        }
1326                    });
1327
1328                    // Use bounds instead of testing hitbox since this is called during prepaint.
1329                    let check_is_hovered_during_prepaint = Rc::new({
1330                        let source_bounds = hitbox.bounds;
1331                        let text_layout = text_layout.clone();
1332                        let pending_mouse_down = interactive_state.mouse_down_index.clone();
1333                        move |window: &Window| {
1334                            text_layout
1335                                .index_for_position(window.mouse_position())
1336                                .is_ok()
1337                                && source_bounds.contains(&window.mouse_position())
1338                                && pending_mouse_down.get().is_none()
1339                        }
1340                    });
1341
1342                    let check_is_hovered = Rc::new({
1343                        let hitbox = hitbox.clone();
1344                        let text_layout = text_layout.clone();
1345                        let pending_mouse_down = interactive_state.mouse_down_index.clone();
1346                        move |window: &Window| {
1347                            text_layout
1348                                .index_for_position(window.mouse_position())
1349                                .is_ok()
1350                                && hitbox.is_hovered(window)
1351                                && pending_mouse_down.get().is_none()
1352                        }
1353                    });
1354
1355                    register_tooltip_mouse_handlers(
1356                        &active_tooltip,
1357                        self.tooltip_id,
1358                        build_tooltip,
1359                        check_is_hovered,
1360                        check_is_hovered_during_prepaint,
1361                        interactive_state.long_press_tooltip_active.clone(),
1362                        None,
1363                        window,
1364                    );
1365                }
1366
1367                self.text
1368                    .paint(None, inspector_id, bounds, &mut (), &mut (), window, cx);
1369
1370                ((), interactive_state)
1371            },
1372        );
1373    }
1374}
1375
1376#[cfg(test)]
1377mod tests {
1378    use super::*;
1379
1380    #[crate::test]
1381    fn text_measurement_depends_only_on_its_inputs(cx: &mut crate::TestAppContext) {
1382        let cx = cx.add_empty_window();
1383        cx.update(|window, cx| {
1384            let text = SharedString::from("Several words that wrap in a narrow parent");
1385            let narrow = Size {
1386                width: crate::AvailableSpace::Definite(crate::px(60.)),
1387                height: crate::AvailableSpace::MaxContent,
1388            };
1389            let wide = Size {
1390                width: crate::AvailableSpace::Definite(crate::px(2000.)),
1391                ..narrow
1392            };
1393            let unconstrained = Size {
1394                width: crate::AvailableSpace::MaxContent,
1395                ..narrow
1396            };
1397            // The height of the lines a layout would paint.
1398            let painted_height = |layout: &TextLayout| {
1399                layout.0.borrow().as_ref().map(|measured| {
1400                    measured
1401                        .lines
1402                        .iter()
1403                        .map(|line| line.size(measured.line_height).height)
1404                        .sum::<Pixels>()
1405                })
1406            };
1407            let fresh_size =
1408                |space: Size<crate::AvailableSpace>, window: &mut Window, cx: &mut App| {
1409                    TextLayout::default()
1410                        .measurement(text.clone(), None, window)
1411                        .measure(Size::default(), space, false, window, cx)
1412                };
1413
1414            let layout = TextLayout::default();
1415            let mut measure = layout.measurement(text.clone(), None, window);
1416            let narrow_size = measure.measure(Size::default(), narrow, true, window, cx);
1417            // An unconstrained probe measures the unwrapped text, rather than answering
1418            // with the size of whatever was measured before it.
1419            let unconstrained_size =
1420                measure.measure(Size::default(), unconstrained, false, window, cx);
1421            assert_eq!(unconstrained_size, fresh_size(unconstrained, window, cx));
1422            assert!(unconstrained_size.width > narrow_size.width);
1423            assert!(unconstrained_size.height < narrow_size.height);
1424
1425            // Probes don't replace the lines kept for painting; the final measurement does.
1426            assert_eq!(painted_height(&layout), Some(narrow_size.height));
1427            let wide_size = measure.measure(Size::default(), wide, false, window, cx);
1428            assert!(wide_size.height < narrow_size.height);
1429            assert_eq!(painted_height(&layout), Some(narrow_size.height));
1430            measure.measure(Size::default(), wide, true, window, cx);
1431            assert_eq!(painted_height(&layout), Some(wide_size.height));
1432
1433            // A measure with the same inputs takes over the lines, and measures the same
1434            // as one measuring from scratch.
1435            let next_layout = TextLayout::default();
1436            let mut next = next_layout.measurement(text.clone(), None, window);
1437            assert!(next.reuse_measurement(&mut measure));
1438            assert_eq!(painted_height(&next_layout), Some(wide_size.height));
1439            for space in [narrow, wide, unconstrained] {
1440                assert_eq!(
1441                    next.measure(Size::default(), space, false, window, cx),
1442                    fresh_size(space, window, cx)
1443                );
1444            }
1445
1446            let mut changed = TextLayout::default().measurement("Other text".into(), None, window);
1447            assert!(!changed.reuse_measurement(&mut next));
1448        });
1449    }
1450
1451    #[test]
1452    fn test_into_element_for() {
1453        use crate::{ParentElement as _, SharedString, div};
1454        use std::borrow::Cow;
1455
1456        let _ = div().child("static str");
1457        let _ = div().child("String".to_string());
1458        let _ = div().child(Cow::Borrowed("Cow"));
1459        let _ = div().child(SharedString::from("SharedString"));
1460    }
1461
1462    #[test]
1463    fn text_macro_id() {
1464        // one call to `text!` = one id
1465        fn make_text_stable_id(happy: bool) -> Text {
1466            text!(if happy { "happy" } else { "sad" })
1467        }
1468
1469        // two calls to `text!` = two ids
1470        fn make_text_unstable_id(happy: bool) -> Text {
1471            if happy { text!("happy") } else { text!("sad") }
1472        }
1473
1474        assert_eq!(make_text_stable_id(false).id, make_text_stable_id(true).id);
1475        assert_ne!(
1476            make_text_unstable_id(false).id,
1477            make_text_unstable_id(true).id
1478        );
1479    }
1480}