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
15const STREAM_FADE: Duration = Duration::from_millis(280);
31const STREAM_FADE_STAGGER: Duration = Duration::from_millis(10);
32
33#[derive(Clone)]
40pub struct TextView {
41 id: ElementId,
42 inner: gpui_base::TextView,
43 text_style: Option<TextViewStyle>,
44 motion: Option<TextViewMotion>,
45 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 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 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 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 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 pub fn style(mut self, style: TextViewStyle) -> Self {
103 self.text_style = Some(style);
104 self
105 }
106 pub fn selectable(mut self, value: bool) -> Self {
108 self.inner = self.inner.selectable(value);
109 self
110 }
111 pub fn inline_code_style(mut self, style: StyleRefinement) -> Self {
115 self.inner = self.inner.inline_code_style(style);
116 self
117 }
118 pub fn list_style(mut self, style: StyleRefinement) -> Self {
122 self.inner = self.inner.list_style(style);
123 self
124 }
125 pub fn blockquote_style(mut self, style: StyleRefinement) -> Self {
128 self.inner = self.inner.blockquote_style(style);
129 self
130 }
131 pub fn selection_format(mut self, value: SelectionFormat) -> Self {
133 self.inner = self.inner.selection_format(value);
134 self
135 }
136 pub fn scrollable(mut self, value: bool) -> Self {
138 self.inner = self.inner.scrollable(value);
139 self
140 }
141 pub fn stream_fade(mut self, value: bool) -> Self {
148 self.stream_fade = Some(value);
149 self
150 }
151 pub fn motion(mut self, motion: TextViewMotion) -> Self {
154 self.motion = Some(motion);
155 self
156 }
157 pub fn max_lines(mut self, value: usize) -> Self {
159 self.inner = self.inner.max_lines(value);
160 self
161 }
162 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 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 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 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 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 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 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 pub fn markdown_extensions(mut self, value: MarkdownExtensions) -> Self {
229 self.inner = self.inner.markdown_extensions(value);
230 self
231 }
232 pub fn markdown_mdx(mut self) -> Self {
234 self.inner = self.inner.markdown_mdx();
235 self
236 }
237
238 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 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 pub fn plugin<P>(self, plugin: P) -> Self
264 where
265 P: TextViewPlugin,
266 {
267 plugin.setup(self)
268 }
269}
270
271#[cfg(not(feature = "gpui-fast"))]
272impl IntoElement for TextView {
273 type Element = Self;
274
275 fn into_element(self) -> Self::Element {
276 self
277 }
278}
279
280pub struct TextViewLayoutState {
282 element: AnyElement,
283}
284
285pub struct TextViewPrepaintState;
287
288impl Element for TextView {
289 type RequestLayoutState = TextViewLayoutState;
290 type PrepaintState = TextViewPrepaintState;
291
292 fn id(&self) -> Option<ElementId> {
293 Some(self.id.clone())
294 }
295
296 fn source_location(&self) -> Option<&'static std::panic::Location<'static>> {
297 None
298 }
299
300 fn request_layout(
301 &mut self,
302 _: Option<&GlobalElementId>,
303 _: Option<&InspectorElementId>,
304 window: &mut Window,
305 cx: &mut App,
306 ) -> (LayoutId, Self::RequestLayoutState) {
307 let mut inner = self.inner.clone();
308 if let Some(style) = self.text_style.clone() {
309 #[cfg(any(feature = "tree-sitter", feature = "syntect"))]
314 if !std::sync::Arc::ptr_eq(
315 &style.highlight_theme,
316 &crate::highlighter::HighlightTheme::default_light(),
317 ) {
318 inner = inner.shared_code_block_highlighter(super::shared_code_block_highlighter(
319 &style.highlight_theme,
320 ));
321 }
322 inner = inner.style(resolve_component_style(
323 crate::ActiveTheme::theme(cx),
324 style,
325 ));
326 }
327 let motion = self.motion.clone().or_else(|| {
328 self.stream_fade.map(|fade| {
329 if !fade {
330 return TextViewMotion::default();
331 }
332 TextViewMotion::default()
333 .with_stream_fade(STREAM_FADE)
334 .with_stream_fade_stagger(STREAM_FADE_STAGGER)
335 .with_stream_fade_easing(Easing::EaseOut)
336 })
337 });
338 if let Some(motion) = motion {
339 inner = inner.motion(motion);
340 }
341 let mut element = inner.into_any_element();
342 let layout_id = element.request_layout(window, cx);
343 (layout_id, TextViewLayoutState { element })
344 }
345
346 fn prepaint(
347 &mut self,
348 _: Option<&GlobalElementId>,
349 _: Option<&InspectorElementId>,
350 _: Bounds<Pixels>,
351 element: &mut Self::RequestLayoutState,
352 window: &mut Window,
353 cx: &mut App,
354 ) -> Self::PrepaintState {
355 element.element.prepaint(window, cx);
356 TextViewPrepaintState
357 }
358
359 fn paint(
360 &mut self,
361 _: Option<&GlobalElementId>,
362 _: Option<&InspectorElementId>,
363 _: Bounds<Pixels>,
364 element: &mut Self::RequestLayoutState,
365 _: &mut Self::PrepaintState,
366 window: &mut Window,
367 cx: &mut App,
368 ) {
369 element.element.paint(window, cx);
370 }
371}
372
373pub(super) fn resolve_component_style(
380 theme: &crate::Theme,
381 legacy: TextViewStyle,
382) -> gpui_base::TextViewStyle {
383 let themed = super::base_text_view_style(theme);
384
385 let refined = |mut base: gpui::StyleRefinement, overlay: &StyleRefinement| {
386 base.refine(overlay);
387 base
388 };
389 let code_block = refined(themed.code_block().clone(), &legacy.code_block);
390 let table = refined(themed.table().clone(), &legacy.table);
391 let table_head = refined(themed.table_head().clone(), &legacy.table_head);
392 let table_cell = refined(themed.table_cell().clone(), &legacy.table_cell);
393
394 let mut inline_code = themed.inline_code();
395 refine_highlight_style(&mut inline_code, legacy.inline_code);
396
397 let is_dark = themed.is_dark() || legacy.is_dark;
401
402 let heading_base_font_size = legacy.heading_base_font_size;
403 let heading_font_size = legacy.heading_font_size;
404 let pins_heading_size = heading_font_size.is_some()
408 || heading_base_font_size != TextViewStyle::default().heading_base_font_size;
409 let style = themed
410 .with_paragraph_gap(legacy.paragraph_gap)
411 .with_heading(move |level| {
412 if !pins_heading_size {
413 return StyleRefinement::default();
414 }
415 let default_size = match level {
416 1 => gpui::rems(2.),
417 2 => gpui::rems(1.5),
418 3 => gpui::rems(1.25),
419 4 => gpui::rems(1.125),
420 _ => gpui::rems(1.),
421 }
422 .to_pixels(heading_base_font_size);
423 let text_size = heading_font_size.as_ref().map_or(default_size, |resolve| {
424 resolve(level, heading_base_font_size)
425 });
426 StyleRefinement::default().text_size(text_size)
427 })
428 .with_code_block(code_block)
429 .with_table(table)
430 .with_table_head(table_head)
431 .with_table_cell(table_cell)
432 .with_inline_code(inline_code)
433 .with_dark(is_dark);
434 style
435}
436
437fn refine_highlight_style(style: &mut HighlightStyle, refinement: HighlightStyle) {
438 if refinement.color.is_some() {
439 style.color = refinement.color;
440 }
441 if refinement.font_weight.is_some() {
442 style.font_weight = refinement.font_weight;
443 }
444 if refinement.font_style.is_some() {
445 style.font_style = refinement.font_style;
446 }
447 if refinement.background_color.is_some() {
448 style.background_color = refinement.background_color;
449 }
450 if refinement.underline.is_some() {
451 style.underline = refinement.underline;
452 }
453 if refinement.strikethrough.is_some() {
454 style.strikethrough = refinement.strikethrough;
455 }
456 if refinement.fade_out.is_some() {
457 style.fade_out = refinement.fade_out;
458 }
459}
460
461pub trait TextViewPlugin {
463 fn setup(self, text_view: TextView) -> TextView;
465}
466impl<P> TextViewPlugin for P
467where
468 P: MarkdownPlugin,
469{
470 fn setup(self, mut text_view: TextView) -> TextView {
471 text_view.inner = text_view.inner.plugin(self);
472 text_view
473 }
474}
475
476#[derive(IntoElement, Clone)]
478pub enum Text {
479 String(SharedString),
480 TextView(Box<TextView>),
481}
482impl From<SharedString> for Text {
483 fn from(value: SharedString) -> Self {
484 Self::String(value)
485 }
486}
487impl From<String> for Text {
488 fn from(value: String) -> Self {
489 Self::String(value.into())
490 }
491}
492impl From<&str> for Text {
493 fn from(value: &str) -> Self {
494 Self::String(value.to_string().into())
495 }
496}
497impl From<TextView> for Text {
498 fn from(value: TextView) -> Self {
499 Self::TextView(Box::new(value))
500 }
501}
502impl Text {
503 pub fn style(self, style: TextViewStyle) -> Self {
505 match self {
506 Self::String(value) => Self::String(value),
507 Self::TextView(view) => Self::TextView(Box::new(view.style(style))),
508 }
509 }
510 pub(crate) fn get_text(&self, cx: &App) -> SharedString {
511 match self {
512 Self::String(value) => value.clone(),
513 Self::TextView(view) => gpui_base::Text::from(view.inner.clone()).get_text(cx),
514 }
515 }
516}
517impl RenderOnce for Text {
518 fn render(self, _: &mut Window, _: &mut App) -> impl IntoElement {
519 match self {
520 Self::String(value) => value.into_any_element(),
521 Self::TextView(view) => view.into_any_element(),
522 }
523 }
524}
525
526#[track_caller]
528pub fn markdown(source: impl Into<SharedString>) -> TextView {
529 TextView::markdown(
530 ElementId::CodeLocation(*std::panic::Location::caller()),
531 source,
532 )
533}
534#[track_caller]
536pub fn html(source: impl Into<SharedString>) -> TextView {
537 TextView::html(
538 ElementId::CodeLocation(*std::panic::Location::caller()),
539 source,
540 )
541}
542
543#[cfg(test)]
544mod tests {
545 use std::sync::{
546 Arc,
547 atomic::{AtomicUsize, Ordering},
548 };
549
550 use gpui::{
551 Context, IntoElement, ParentElement as _, Render, TestAppContext, VisualTestContext, div,
552 };
553
554 struct StatelessMarkdown {
555 renders: Arc<AtomicUsize>,
556 }
557
558 impl Render for StatelessMarkdown {
559 fn render(&mut self, _: &mut gpui::Window, _: &mut Context<Self>) -> impl IntoElement {
560 self.renders.fetch_add(1, Ordering::Relaxed);
561 div().child(
562 super::markdown(include_str!("../../../../examples/fixtures/test.md"))
563 .markdown_block_parser(|_, _| None),
564 )
565 }
566 }
567
568 #[gpui::test]
569 fn stateless_markdown_facade_settles_after_parsing(cx: &mut TestAppContext) {
570 cx.update(crate::init);
571 let renders = Arc::new(AtomicUsize::new(0));
572 let (_, cx) = cx.add_window_view({
573 let renders = renders.clone();
574 move |_, _| StatelessMarkdown { renders }
575 });
576 let cx: &mut VisualTestContext = cx;
577
578 cx.run_until_parked();
579 cx.update(|window, cx| window.draw(cx).clear(cx));
580 let renders_after_redraw = renders.load(Ordering::Relaxed);
581 cx.run_until_parked();
582 assert_eq!(
583 renders.load(Ordering::Relaxed),
584 renders_after_redraw,
585 "an unchanged compatibility TextView must not schedule another render after its parse",
586 );
587 }
588}