Skip to main content

gpui_component/text/
compat.rs

1use gpui::{
2    AnyElement, AnyView, App, Bounds, ClickEvent, Element, ElementId, Entity, GlobalElementId,
3    HighlightStyle, InspectorElementId, IntoElement, LayoutId, Pixels, Refineable as _, RenderOnce,
4    SharedString, StyleRefinement, Styled, Window,
5};
6
7use std::time::Duration;
8
9use super::{
10    MarkdownExtensions, MarkdownNode, MarkdownParseContext, MarkdownPlugin, SelectionFormat,
11    TableData, TaskToggleEvent, TextViewMotion, TextViewState, TextViewStyle,
12};
13use gpui_base::{Easing, text::CodeBlock};
14
15/// How long a word of streamed text takes to reach full color, and how much later each further
16/// word of the same chunk starts. Measured frame by frame from claude.ai: a chunk lands as
17/// ~6 words every ~100 ms and goes from transparent to solid in ~250-300 ms, its words lighting
18/// up a few milliseconds apart rather than all at once.
19///
20/// The two pull in opposite directions and both matter.
21///
22/// `stagger × words` is how long a chunk takes to light up end to end, and it has to stay well
23/// under the interval between chunks: let it reach that and chunks overlap into one continuous
24/// drip of single words, which is what staggering was meant to avoid. At 10 ms a 6-word chunk
25/// lights up in 60 ms -- one gesture, with a visible gradient inside it.
26///
27/// The fade has to outlast that interval instead. How many words are visibly mid-fade at any
28/// moment is the reveal rate times the fade, so a short fade leaves a couple of grey glyphs on
29/// the tail and no gradient to speak of.
30const STREAM_FADE: Duration = Duration::from_millis(280);
31const STREAM_FADE_STAGGER: Duration = Duration::from_millis(10);
32
33/// The component-level rich text element.
34///
35/// The rendering, parsing and selection all live in [`gpui_base::TextView`];
36/// this wrapper exists so that the component API -- `TextViewStyle`, the
37/// component `HighlightTheme`, and the element's associated types -- keeps
38/// working unchanged.
39#[derive(Clone)]
40pub struct TextView {
41    id: ElementId,
42    inner: gpui_base::TextView,
43    text_style: Option<TextViewStyle>,
44    motion: Option<TextViewMotion>,
45    /// `None` leaves the state's own policy alone; `Some(false)` turns a
46    /// fade off that an earlier frame turned on.
47    stream_fade: Option<bool>,
48}
49
50impl Styled for TextView {
51    fn style(&mut self) -> &mut StyleRefinement {
52        gpui::Styled::style(&mut self.inner)
53    }
54}
55
56impl TextView {
57    /// Creates a text view rendering an existing [`TextViewState`].
58    pub fn new(state: &Entity<TextViewState>) -> Self {
59        Self {
60            id: ElementId::Name(state.entity_id().to_string().into()),
61            inner: gpui_base::TextView::new(state),
62            text_style: None,
63            motion: None,
64            stream_fade: None,
65        }
66    }
67    /// Creates a text view that parses `text` as Markdown.
68    pub fn markdown(id: impl Into<ElementId>, text: impl Into<SharedString>) -> Self {
69        let id = id.into();
70        Self {
71            id: id.clone(),
72            inner: gpui_base::TextView::markdown(id, text),
73            text_style: None,
74            motion: None,
75            stream_fade: None,
76        }
77    }
78    /// Creates a text view that parses `text` as HTML.
79    pub fn html(id: impl Into<ElementId>, text: impl Into<SharedString>) -> Self {
80        let id = id.into();
81        Self {
82            id: id.clone(),
83            inner: gpui_base::TextView::html(id, text),
84            text_style: None,
85            motion: None,
86            stream_fade: None,
87        }
88    }
89    /// Overrides the source of every document image, including embedded data URLs.
90    ///
91    /// Used for both rendering and intrinsic-size measurement. The returned source
92    /// is authoritative: pending or failed loads never fall back to the document URL.
93    /// Without this override, images use Base's default URI and data URL handling.
94    pub fn image_source<F>(mut self, resolver: F) -> Self
95    where
96        F: Fn(&gpui::SharedUri) -> gpui::ImageSource + Send + Sync + 'static,
97    {
98        self.inner = self.inner.image_source(resolver);
99        self
100    }
101    /// Sets the style, folded onto the one derived from the active theme.
102    pub fn style(mut self, style: TextViewStyle) -> Self {
103        self.text_style = Some(style);
104        self
105    }
106    /// Sets whether the text can be selected with the mouse.
107    pub fn selectable(mut self, value: bool) -> Self {
108        self.inner = self.inner.selectable(value);
109        self
110    }
111    /// Refines inline code typography, background, border, radius, and padding
112    /// over the resolved theme or explicit style. Other layout properties are
113    /// ignored. Unspecified properties are inherited.
114    pub fn inline_code_style(mut self, style: StyleRefinement) -> Self {
115        self.inner = self.inner.inline_code_style(style);
116        self
117    }
118    /// Refines bullet and number list markers over the resolved theme or
119    /// explicit style. The text color also outlines unchecked task-list
120    /// checkboxes. Unspecified properties are inherited.
121    pub fn list_style(mut self, style: StyleRefinement) -> Self {
122        self.inner = self.inner.list_style(style);
123        self
124    }
125    /// Refines the blockquote container, including its left border, over the
126    /// resolved theme or explicit style. Unspecified properties are inherited.
127    pub fn blockquote_style(mut self, style: StyleRefinement) -> Self {
128        self.inner = self.inner.blockquote_style(style);
129        self
130    }
131    /// Sets whether a copied selection carries Markdown source or plain text.
132    pub fn selection_format(mut self, value: SelectionFormat) -> Self {
133        self.inner = self.inner.selection_format(value);
134        self
135    }
136    /// Sets whether the view scrolls its own content.
137    pub fn scrollable(mut self, value: bool) -> Self {
138        self.inner = self.inner.scrollable(value);
139        self
140    }
141    /// Fades streamed text in the way Claude reveals a reply: the words a `set_text` or
142    /// `push_str` adds start transparent and light up one after another, each reaching full
143    /// color over 280 ms. A chunk far larger than one keystroke burst -- a backfill, a replay --
144    /// fades as a whole instead, since nobody typed it. Text that replaces rather than extends
145    /// the current content shows at once, and reduced motion disables the fade. Use
146    /// [`Self::motion`] for other timing.
147    pub fn stream_fade(mut self, value: bool) -> Self {
148        self.stream_fade = Some(value);
149        self
150    }
151    /// Sets the motion policy explicitly, overriding [`Self::stream_fade`]'s
152    /// theme timing.
153    pub fn motion(mut self, motion: TextViewMotion) -> Self {
154        self.motion = Some(motion);
155        self
156    }
157    /// Clamps the rendered content to `value` lines.
158    pub fn max_lines(mut self, value: usize) -> Self {
159        self.inner = self.inner.max_lines(value);
160        self
161    }
162    /// Renders an element in the corner of every fenced code block.
163    pub fn code_block_actions<F, E>(mut self, f: F) -> Self
164    where
165        F: Fn(&CodeBlock, &mut Window, &mut App) -> E + Send + Sync + 'static,
166        E: IntoElement,
167    {
168        self.inner = self.inner.code_block_actions(f);
169        self
170    }
171    /// Renders an element in the corner of every table.
172    pub fn table_actions<F, E>(mut self, f: F) -> Self
173    where
174        F: Fn(&TableData, &mut Window, &mut App) -> E + Send + Sync + 'static,
175        E: IntoElement,
176    {
177        self.inner = self.inner.table_actions(f);
178        self
179    }
180    /// Handles link clicks instead of opening the URL.
181    pub fn on_link_click<F>(mut self, f: F) -> Self
182    where
183        F: Fn(&SharedString, &ClickEvent, &mut Window, &mut App) + Send + Sync + 'static,
184    {
185        self.inner = self.inner.on_link_click(f);
186        self
187    }
188    /// Replaces each link before it is drawn; `None` draws it as plain text.
189    /// See [`gpui_base::text::TextView::link`].
190    pub fn link<F>(mut self, f: F) -> Self
191    where
192        F: Fn(&gpui_base::text::Link, &App) -> Option<gpui_base::text::Link>
193            + Send
194            + Sync
195            + 'static,
196    {
197        self.inner = self.inner.link(f);
198        self
199    }
200    /// Shows an application-supplied tooltip beside the pointer over a link.
201    /// The tooltip is cached until a different destination is shown.
202    pub fn link_tooltip<F>(mut self, builder: F) -> Self
203    where
204        F: Fn(&SharedString, &mut Window, &mut App) -> AnyView + Send + Sync + 'static,
205    {
206        self.inner = self.inner.link_tooltip(builder);
207        self
208    }
209    /// Makes Markdown task list checkboxes clickable, reporting the clicked
210    /// item's new checked state and where it and its marker are in the source.
211    pub fn on_task_toggle<F>(mut self, f: F) -> Self
212    where
213        F: Fn(&TaskToggleEvent, &mut Window, &mut App) + Send + Sync + 'static,
214    {
215        self.inner = self.inner.on_task_toggle(f);
216        self
217    }
218    /// Scrolls a container that ignores scroll requests to the line of
219    /// `TextViewState::reveal_range`, with the line's window bounds.
220    pub fn on_reveal<F>(mut self, f: F) -> Self
221    where
222        F: Fn(Bounds<Pixels>, &mut Window, &mut App) + 'static,
223    {
224        self.inner = self.inner.on_reveal(f);
225        self
226    }
227    /// Sets which Markdown extensions the parser accepts.
228    pub fn markdown_extensions(mut self, value: MarkdownExtensions) -> Self {
229        self.inner = self.inner.markdown_extensions(value);
230        self
231    }
232    /// Enables the MDX Markdown extensions.
233    pub fn markdown_mdx(mut self) -> Self {
234        self.inner = self.inner.markdown_mdx();
235        self
236    }
237
238    /// Parses custom block nodes out of the Markdown AST.
239    pub fn markdown_block_parser<F>(mut self, parser: F) -> Self
240    where
241        F: for<'a> Fn(&markdown::mdast::Node, &MarkdownParseContext<'a>) -> Option<MarkdownNode>
242            + Send
243            + Sync
244            + 'static,
245    {
246        self.inner = self.inner.markdown_block_parser(parser);
247        self
248    }
249    /// Renders the custom block nodes named `name`.
250    pub fn markdown_block_renderer<F, E>(
251        mut self,
252        name: impl Into<SharedString>,
253        renderer: F,
254    ) -> Self
255    where
256        F: Fn(&MarkdownNode, &mut Window, &mut App) -> E + Send + Sync + 'static,
257        E: IntoElement,
258    {
259        self.inner = self.inner.markdown_block_renderer(name, renderer);
260        self
261    }
262    /// Applies a plugin, which may install any of the hooks above.
263    pub fn plugin<P>(self, plugin: P) -> Self
264    where
265        P: TextViewPlugin,
266    {
267        plugin.setup(self)
268    }
269}
270
271/// Layout state retained for source compatibility with the original component TextView.
272pub struct TextViewLayoutState {
273    element: AnyElement,
274}
275
276/// Prepaint state retained for source compatibility with the original component TextView.
277pub struct TextViewPrepaintState;
278
279impl Element for TextView {
280    type RequestLayoutState = TextViewLayoutState;
281    type PrepaintState = TextViewPrepaintState;
282
283    fn id(&self) -> Option<ElementId> {
284        Some(self.id.clone())
285    }
286
287    fn source_location(&self) -> Option<&'static std::panic::Location<'static>> {
288        None
289    }
290
291    fn request_layout(
292        &mut self,
293        _: Option<&GlobalElementId>,
294        _: Option<&InspectorElementId>,
295        window: &mut Window,
296        cx: &mut App,
297    ) -> (LayoutId, Self::RequestLayoutState) {
298        let mut inner = self.inner.clone();
299        if let Some(style) = self.text_style.clone() {
300            // `request_layout` runs every frame, so this asks whether the
301            // caller ever replaced the theme -- a pointer comparison against
302            // the shared default -- rather than comparing two whole themes
303            // field by field.
304            #[cfg(any(feature = "tree-sitter", feature = "syntect"))]
305            if !std::sync::Arc::ptr_eq(
306                &style.highlight_theme,
307                &crate::highlighter::HighlightTheme::default_light(),
308            ) {
309                inner = inner.shared_code_block_highlighter(super::shared_code_block_highlighter(
310                    &style.highlight_theme,
311                ));
312            }
313            inner = inner.style(resolve_component_style(
314                crate::ActiveTheme::theme(cx),
315                style,
316            ));
317        }
318        let motion = self.motion.clone().or_else(|| {
319            self.stream_fade.map(|fade| {
320                if !fade {
321                    return TextViewMotion::default();
322                }
323                TextViewMotion::default()
324                    .with_stream_fade(STREAM_FADE)
325                    .with_stream_fade_stagger(STREAM_FADE_STAGGER)
326                    .with_stream_fade_easing(Easing::EaseOut)
327            })
328        });
329        if let Some(motion) = motion {
330            inner = inner.motion(motion);
331        }
332        let mut element = inner.into_any_element();
333        let layout_id = element.request_layout(window, cx);
334        (layout_id, TextViewLayoutState { element })
335    }
336
337    fn prepaint(
338        &mut self,
339        _: Option<&GlobalElementId>,
340        _: Option<&InspectorElementId>,
341        _: Bounds<Pixels>,
342        element: &mut Self::RequestLayoutState,
343        window: &mut Window,
344        cx: &mut App,
345    ) -> Self::PrepaintState {
346        element.element.prepaint(window, cx);
347        TextViewPrepaintState
348    }
349
350    fn paint(
351        &mut self,
352        _: Option<&GlobalElementId>,
353        _: Option<&InspectorElementId>,
354        _: Bounds<Pixels>,
355        element: &mut Self::RequestLayoutState,
356        _: &mut Self::PrepaintState,
357        window: &mut Window,
358        cx: &mut App,
359    ) {
360        element.element.paint(window, cx);
361    }
362}
363
364/// Folds a component [`TextViewStyle`] onto the one the theme already derived.
365///
366/// The legacy type carries `StyleRefinement`s that callers filled in
367/// partially, so each one is refined onto the themed value rather than
368/// replacing it -- a caller who set only `white_space` keeps the themed
369/// padding and colors.
370pub(super) fn resolve_component_style(
371    theme: &crate::Theme,
372    legacy: TextViewStyle,
373) -> gpui_base::TextViewStyle {
374    let themed = super::base_text_view_style(theme);
375
376    let refined = |mut base: gpui::StyleRefinement, overlay: &StyleRefinement| {
377        base.refine(overlay);
378        base
379    };
380    let code_block = refined(themed.code_block().clone(), &legacy.code_block);
381    let table = refined(themed.table().clone(), &legacy.table);
382    let table_head = refined(themed.table_head().clone(), &legacy.table_head);
383    let table_cell = refined(themed.table_cell().clone(), &legacy.table_cell);
384
385    let mut inline_code = themed.inline_code();
386    refine_highlight_style(&mut inline_code, legacy.inline_code);
387
388    // `is_dark` only ever turns on: the component theme already answered the
389    // question, and a legacy style left at its `false` default must not undo
390    // a dark theme.
391    let is_dark = themed.is_dark() || legacy.is_dark;
392
393    let heading_base_font_size = legacy.heading_base_font_size;
394    let heading_font_size = legacy.heading_font_size;
395    // A style that never touched heading sizes keeps the Base default, which
396    // scales headings with the body text; only an explicit base size or
397    // resolver pins them to pixels.
398    let pins_heading_size = heading_font_size.is_some()
399        || heading_base_font_size != TextViewStyle::default().heading_base_font_size;
400    let style = themed
401        .with_paragraph_gap(legacy.paragraph_gap)
402        .with_heading(move |level| {
403            if !pins_heading_size {
404                return StyleRefinement::default();
405            }
406            let default_size = match level {
407                1 => gpui::rems(2.),
408                2 => gpui::rems(1.5),
409                3 => gpui::rems(1.25),
410                4 => gpui::rems(1.125),
411                _ => gpui::rems(1.),
412            }
413            .to_pixels(heading_base_font_size);
414            let text_size = heading_font_size.as_ref().map_or(default_size, |resolve| {
415                resolve(level, heading_base_font_size)
416            });
417            StyleRefinement::default().text_size(text_size)
418        })
419        .with_code_block(code_block)
420        .with_table(table)
421        .with_table_head(table_head)
422        .with_table_cell(table_cell)
423        .with_inline_code(inline_code)
424        .with_dark(is_dark);
425    style
426}
427
428fn refine_highlight_style(style: &mut HighlightStyle, refinement: HighlightStyle) {
429    if refinement.color.is_some() {
430        style.color = refinement.color;
431    }
432    if refinement.font_weight.is_some() {
433        style.font_weight = refinement.font_weight;
434    }
435    if refinement.font_style.is_some() {
436        style.font_style = refinement.font_style;
437    }
438    if refinement.background_color.is_some() {
439        style.background_color = refinement.background_color;
440    }
441    if refinement.underline.is_some() {
442        style.underline = refinement.underline;
443    }
444    if refinement.strikethrough.is_some() {
445        style.strikethrough = refinement.strikethrough;
446    }
447    if refinement.fade_out.is_some() {
448        style.fade_out = refinement.fade_out;
449    }
450}
451
452/// A bundle of [`TextView`] configuration that can be applied in one call.
453pub trait TextViewPlugin {
454    /// Applies this plugin's configuration to `text_view`.
455    fn setup(self, text_view: TextView) -> TextView;
456}
457impl<P> TextViewPlugin for P
458where
459    P: MarkdownPlugin,
460{
461    fn setup(self, mut text_view: TextView) -> TextView {
462        text_view.inner = text_view.inner.plugin(self);
463        text_view
464    }
465}
466
467/// Either a plain string or a rich [`TextView`].
468#[derive(IntoElement, Clone)]
469pub enum Text {
470    String(SharedString),
471    TextView(Box<TextView>),
472}
473impl From<SharedString> for Text {
474    fn from(value: SharedString) -> Self {
475        Self::String(value)
476    }
477}
478impl From<String> for Text {
479    fn from(value: String) -> Self {
480        Self::String(value.into())
481    }
482}
483impl From<&str> for Text {
484    fn from(value: &str) -> Self {
485        Self::String(value.to_string().into())
486    }
487}
488impl From<TextView> for Text {
489    fn from(value: TextView) -> Self {
490        Self::TextView(Box::new(value))
491    }
492}
493impl Text {
494    /// Sets the style for the [`TextView`]. Does nothing for a plain string.
495    pub fn style(self, style: TextViewStyle) -> Self {
496        match self {
497            Self::String(value) => Self::String(value),
498            Self::TextView(view) => Self::TextView(Box::new(view.style(style))),
499        }
500    }
501    pub(crate) fn get_text(&self, cx: &App) -> SharedString {
502        match self {
503            Self::String(value) => value.clone(),
504            Self::TextView(view) => gpui_base::Text::from(view.inner.clone()).get_text(cx),
505        }
506    }
507}
508impl RenderOnce for Text {
509    fn render(self, _: &mut Window, _: &mut App) -> impl IntoElement {
510        match self {
511            Self::String(value) => value.into_any_element(),
512            Self::TextView(view) => view.into_any_element(),
513        }
514    }
515}
516
517/// Creates a Markdown text view identified by the caller's code location.
518#[track_caller]
519pub fn markdown(source: impl Into<SharedString>) -> TextView {
520    TextView::markdown(
521        ElementId::CodeLocation(*std::panic::Location::caller()),
522        source,
523    )
524}
525/// Creates an HTML text view identified by the caller's code location.
526#[track_caller]
527pub fn html(source: impl Into<SharedString>) -> TextView {
528    TextView::html(
529        ElementId::CodeLocation(*std::panic::Location::caller()),
530        source,
531    )
532}
533
534#[cfg(test)]
535mod tests {
536    use std::sync::{
537        Arc,
538        atomic::{AtomicUsize, Ordering},
539    };
540
541    use gpui::{
542        Context, IntoElement, ParentElement as _, Render, TestAppContext, VisualTestContext, div,
543    };
544
545    struct StatelessMarkdown {
546        renders: Arc<AtomicUsize>,
547    }
548
549    impl Render for StatelessMarkdown {
550        fn render(&mut self, _: &mut gpui::Window, _: &mut Context<Self>) -> impl IntoElement {
551            self.renders.fetch_add(1, Ordering::Relaxed);
552            div().child(
553                super::markdown(include_str!("../../../../examples/fixtures/test.md"))
554                    .markdown_block_parser(|_, _| None),
555            )
556        }
557    }
558
559    #[gpui::test]
560    fn stateless_markdown_facade_settles_after_parsing(cx: &mut TestAppContext) {
561        cx.update(crate::init);
562        let renders = Arc::new(AtomicUsize::new(0));
563        let (_, cx) = cx.add_window_view({
564            let renders = renders.clone();
565            move |_, _| StatelessMarkdown { renders }
566        });
567        let cx: &mut VisualTestContext = cx;
568
569        cx.run_until_parked();
570        cx.update(|window, cx| window.draw(cx).clear(cx));
571        let renders_after_redraw = renders.load(Ordering::Relaxed);
572        cx.run_until_parked();
573        assert_eq!(
574            renders.load(Ordering::Relaxed),
575            renders_after_redraw,
576            "an unchanged compatibility TextView must not schedule another render after its parse",
577        );
578    }
579}