1use std::{cell::RefCell, ops::Range, sync::Arc, time::Duration};
2
3use gpui::{
4 App, AppContext, ClickEvent, Context, ElementId, Empty, Entity, FontWeight, Global,
5 HighlightStyle, Hsla, InteractiveElement, IntoElement, ParentElement, Refineable, Rems, Render,
6 RenderOnce, Role, SharedString, StatefulInteractiveElement, StyleRefinement, Styled,
7 Subscription, TextAlign, Window, div, px, rems,
8};
9use gpui_base::{
10 SelectionFormat as BaseSelectionFormat, TaskToggleEvent as BaseTaskToggleEvent, TestSupportExt,
11 TextView as BaseTextView, TextViewMotion as BaseTextViewMotion,
12 TextViewState as BaseTextViewState, TextViewStyle as BaseTextViewStyle,
13};
14use gpui_material_foundation::{
15 color, current_material_theme, font_cache_revision, font_for_style,
16};
17use gpui_material_theme::{
18 Appearance, ColorRole, CornerRole, Direction, LayoutPolicy, MaterialTheme, TypeRole,
19 TypographyEmphasis,
20};
21
22#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
24pub enum RichTextSelectionFormat {
25 #[default]
27 Plain,
28 Source,
30 SourceAcrossStyles,
32}
33
34impl From<RichTextSelectionFormat> for BaseSelectionFormat {
35 fn from(format: RichTextSelectionFormat) -> Self {
36 match format {
37 RichTextSelectionFormat::Plain => Self::Plain,
38 RichTextSelectionFormat::Source => Self::Source,
39 RichTextSelectionFormat::SourceAcrossStyles => Self::SourceAcrossStyles,
40 }
41 }
42}
43
44#[derive(Clone, Debug, PartialEq, Eq)]
46pub struct RichTextTaskToggle {
47 checked: bool,
48 item_range: Range<usize>,
49 marker_range: Range<usize>,
50}
51
52impl RichTextTaskToggle {
53 fn from_base(event: &BaseTaskToggleEvent) -> Self {
54 Self {
55 checked: event.checked(),
56 item_range: event.item_range(),
57 marker_range: event.marker_range(),
58 }
59 }
60
61 pub fn checked(&self) -> bool {
63 self.checked
64 }
65
66 pub fn item_range(&self) -> Range<usize> {
68 self.item_range.clone()
69 }
70
71 pub fn marker_range(&self) -> Range<usize> {
73 self.marker_range.clone()
74 }
75}
76
77#[derive(Clone, Debug, Default, PartialEq)]
80pub struct RichTextStyle {
81 pub body_color: Option<Hsla>,
83 pub muted_color: Option<Hsla>,
85 pub link_color: Option<Hsla>,
87 pub selection_color: Option<Hsla>,
89 pub code_background: Option<Hsla>,
91 pub code_color: Option<Hsla>,
93 pub border_color: Option<Hsla>,
95 pub blockquote_border_color: Option<Hsla>,
97 pub table_row_hover: Option<Hsla>,
99 pub paragraph_gap: Option<Rems>,
101 pub code_font_family: Option<SharedString>,
103}
104
105pub struct RichTextState {
108 base: Entity<BaseTextViewState>,
109 _subscription: Subscription,
110}
111
112impl RichTextState {
113 pub fn markdown(text: &str, cx: &mut Context<Self>) -> Self {
115 let base = cx.new(|cx| BaseTextViewState::markdown(text, cx).selectable(true));
116 let subscription = cx.observe(&base, |_, _, cx| cx.notify());
117 Self {
118 base,
119 _subscription: subscription,
120 }
121 }
122
123 pub fn html(text: &str, cx: &mut Context<Self>) -> Self {
125 let base = cx.new(|cx| BaseTextViewState::html(text, cx).selectable(true));
126 let subscription = cx.observe(&base, |_, _, cx| cx.notify());
127 Self {
128 base,
129 _subscription: subscription,
130 }
131 }
132
133 pub fn set_text(&mut self, text: &str, cx: &mut Context<Self>) {
136 self.base.update(cx, |base, cx| base.set_text(text, cx));
137 cx.notify();
138 }
139
140 pub fn push_str(&mut self, chunk: &str, cx: &mut Context<Self>) {
142 self.base.update(cx, |base, cx| base.push_str(chunk, cx));
143 cx.notify();
144 }
145
146 pub fn selected_text(&self, cx: &App) -> String {
148 self.base.read(cx).selected_text()
149 }
150
151 pub fn rendered_text(&self, cx: &App) -> String {
153 self.base.read(cx).rendered_text().as_str().to_owned()
154 }
155
156 pub fn is_clamped(&self, cx: &App) -> bool {
158 self.base.read(cx).is_clamped()
159 }
160
161 pub fn set_selectable(&mut self, selectable: bool, cx: &mut Context<Self>) {
163 self.base
164 .update(cx, |base, cx| base.set_selectable(selectable, cx));
165 cx.notify();
166 }
167
168 pub fn set_scrollable(&mut self, scrollable: bool, cx: &mut Context<Self>) {
170 self.base
171 .update(cx, |base, cx| base.set_scrollable(scrollable, cx));
172 cx.notify();
173 }
174
175 pub fn set_selection_format(
177 &mut self,
178 format: RichTextSelectionFormat,
179 cx: &mut Context<Self>,
180 ) {
181 self.base
182 .update(cx, |base, cx| base.set_selection_format(format.into(), cx));
183 cx.notify();
184 }
185}
186
187impl Render for RichTextState {
188 fn render(&mut self, _: &mut Window, _: &mut Context<Self>) -> impl IntoElement {
189 Empty
190 }
191}
192
193type LinkClickHandler = dyn Fn(&SharedString, &ClickEvent, &mut Window, &mut App) + Send + Sync;
194type TaskToggleHandler = dyn Fn(RichTextTaskToggle, &mut Window, &mut App) + Send + Sync;
195
196enum RichTextSource {
197 Markdown(SharedString),
198 Html(SharedString),
199 State(Entity<RichTextState>),
200}
201
202#[derive(IntoElement)]
209pub struct RichText {
210 id: ElementId,
211 source: RichTextSource,
212 body_role: TypeRole,
213 font_scale: f32,
214 rich_style: RichTextStyle,
215 selectable: bool,
216 selection_format: RichTextSelectionFormat,
217 scrollable: bool,
218 max_lines: Option<usize>,
219 stream_fade: bool,
220 on_link_click: Option<Arc<LinkClickHandler>>,
221 on_task_toggle: Option<Arc<TaskToggleHandler>>,
222 accessible_label: Option<SharedString>,
223 style: StyleRefinement,
224}
225
226impl RichText {
227 pub fn markdown(id: impl Into<ElementId>, source: impl Into<SharedString>) -> Self {
229 Self::with_source(id.into(), RichTextSource::Markdown(source.into()))
230 }
231
232 pub fn html(id: impl Into<ElementId>, source: impl Into<SharedString>) -> Self {
234 Self::with_source(id.into(), RichTextSource::Html(source.into()))
235 }
236
237 pub fn from_state(id: impl Into<ElementId>, state: &Entity<RichTextState>) -> Self {
239 Self::with_source(id.into(), RichTextSource::State(state.clone()))
240 }
241
242 fn with_source(id: ElementId, source: RichTextSource) -> Self {
243 Self {
244 id,
245 source,
246 body_role: TypeRole::BodyLarge,
247 font_scale: 1.0,
248 rich_style: RichTextStyle::default(),
249 selectable: true,
250 selection_format: RichTextSelectionFormat::Plain,
251 scrollable: false,
252 max_lines: None,
253 stream_fade: false,
254 on_link_click: None,
255 on_task_toggle: None,
256 accessible_label: None,
257 style: StyleRefinement::default(),
258 }
259 }
260
261 pub fn body_role(mut self, role: TypeRole) -> Self {
263 self.body_role = role;
264 self
265 }
266
267 pub fn font_scale(mut self, scale: f32) -> Self {
270 if scale.is_finite() && scale > 0.0 {
271 self.font_scale = scale;
272 }
273 self
274 }
275
276 pub fn rich_style(mut self, style: RichTextStyle) -> Self {
278 self.rich_style = style;
279 self
280 }
281
282 pub fn selectable(mut self, selectable: bool) -> Self {
284 self.selectable = selectable;
285 self
286 }
287
288 pub fn selection_format(mut self, format: RichTextSelectionFormat) -> Self {
290 self.selection_format = format;
291 self
292 }
293
294 pub fn scrollable(mut self, scrollable: bool) -> Self {
296 self.scrollable = scrollable;
297 self
298 }
299
300 pub fn max_lines(mut self, lines: usize) -> Self {
302 self.max_lines = Some(lines.max(1));
303 self
304 }
305
306 pub fn stream_fade(mut self, enabled: bool) -> Self {
308 self.stream_fade = enabled;
309 self
310 }
311
312 pub fn on_link_click<F>(mut self, handler: F) -> Self
314 where
315 F: Fn(&SharedString, &ClickEvent, &mut Window, &mut App) + Send + Sync + 'static,
316 {
317 self.on_link_click = Some(Arc::new(handler));
318 self
319 }
320
321 pub fn on_task_toggle<F>(mut self, handler: F) -> Self
323 where
324 F: Fn(RichTextTaskToggle, &mut Window, &mut App) + Send + Sync + 'static,
325 {
326 self.on_task_toggle = Some(Arc::new(handler));
327 self
328 }
329
330 pub fn accessible_label(mut self, label: impl Into<SharedString>) -> Self {
332 self.accessible_label = Some(label.into());
333 self
334 }
335}
336
337impl Styled for RichText {
338 fn style(&mut self) -> &mut StyleRefinement {
339 &mut self.style
340 }
341}
342
343impl RenderOnce for RichText {
344 fn render(self, window: &mut Window, cx: &mut App) -> impl IntoElement {
345 if !cx.has_global::<MonospaceCache>() {
346 cx.set_global(MonospaceCache(RefCell::new(None)));
347 }
348 let theme = current_material_theme(window, cx);
349 let rtl = theme.layout.direction == Direction::Rtl;
350 let body_type = LayoutPolicy::scale_text(
351 theme
352 .typography
353 .style(self.body_role, TypographyEmphasis::Baseline),
354 self.font_scale,
355 );
356 let body_font = font_for_style(&theme.typography, body_type, cx);
357 let tv_style = project_text_view_style(&theme, &self.rich_style, self.font_scale, cx);
358
359 let motion = if self.stream_fade && !cx.reduce_motion() {
360 BaseTextViewMotion::default().with_stream_fade(Duration::from_millis(120))
361 } else {
362 BaseTextViewMotion::default()
363 };
364
365 let view_id = (self.id.clone(), "view");
366 let mut view = match self.source {
367 RichTextSource::Markdown(source) => BaseTextView::markdown(view_id, source),
368 RichTextSource::Html(source) => BaseTextView::html(view_id, source),
369 RichTextSource::State(state) => BaseTextView::new(&state.read(cx).base),
370 }
371 .style(tv_style)
372 .selectable(self.selectable)
373 .selection_format(self.selection_format.into())
374 .scrollable(self.scrollable)
375 .motion(motion)
376 .font(body_font)
377 .text_size(px(body_type.size))
378 .line_height(px(body_type.line_height))
379 .text_align(if rtl {
380 TextAlign::Right
381 } else {
382 TextAlign::Left
383 });
384
385 if let Some(max_lines) = self.max_lines {
386 view = view.max_lines(max_lines);
387 }
388 if let Some(handler) = self.on_link_click {
389 view = view.on_link_click(move |url, event, window, cx| {
390 handler(url, event, window, cx);
391 });
392 }
393 if let Some(handler) = self.on_task_toggle {
394 view = view.on_task_toggle(move |event, window, cx| {
395 handler(RichTextTaskToggle::from_base(event), window, cx);
396 });
397 }
398
399 let mut container = div()
400 .id(self.id)
401 .test_support()
402 .role(Role::Document)
403 .min_w_0()
404 .w_full();
405 if let Some(label) = self.accessible_label {
406 container = container.aria_label(label);
407 }
408 container.style().refine(&self.style);
409 container.child(view)
410 }
411}
412
413fn project_text_view_style(
414 theme: &MaterialTheme,
415 overrides: &RichTextStyle,
416 font_scale: f32,
417 cx: &App,
418) -> BaseTextViewStyle {
419 let is_dark = theme.colors.appearance() == Appearance::Dark;
420 let body_color = overrides
421 .body_color
422 .unwrap_or_else(|| color(theme.colors.color(ColorRole::OnSurface)));
423 let muted_color = overrides
424 .muted_color
425 .unwrap_or_else(|| color(theme.colors.color(ColorRole::OnSurfaceVariant)));
426 let link_color = overrides
427 .link_color
428 .unwrap_or_else(|| color(theme.colors.color(ColorRole::Primary)));
429 let selection_color = overrides
430 .selection_color
431 .unwrap_or_else(|| color(theme.colors.color(ColorRole::PrimaryContainer)).opacity(0.75));
432 let code_bg = overrides
433 .code_background
434 .unwrap_or_else(|| color(theme.colors.color(ColorRole::SurfaceContainerHighest)));
435 let code_fg = overrides.code_color.unwrap_or(body_color);
436 let border_color = overrides
437 .border_color
438 .unwrap_or_else(|| color(theme.colors.color(ColorRole::OutlineVariant)));
439 let blockquote_border = overrides.blockquote_border_color.unwrap_or(border_color);
440 let table_head_bg = color(theme.colors.color(ColorRole::SurfaceContainerHigh));
441 let table_row_hover = overrides
442 .table_row_hover
443 .unwrap_or_else(|| color(theme.colors.color(ColorRole::SurfaceContainerLow)));
444 let paragraph_gap = overrides.paragraph_gap.unwrap_or(rems(0.75));
445 let code_family = overrides
446 .code_font_family
447 .clone()
448 .unwrap_or_else(|| resolve_monospace_family(cx));
449
450 let heading_roles = [
451 TypeRole::HeadlineLarge,
452 TypeRole::HeadlineMedium,
453 TypeRole::HeadlineSmall,
454 TypeRole::TitleLarge,
455 TypeRole::TitleMedium,
456 TypeRole::TitleSmall,
457 ];
458 let headings: [StyleRefinement; 6] = heading_roles.map(|role| {
459 let style = LayoutPolicy::scale_text(
460 theme.typography.style(role, TypographyEmphasis::Emphasized),
461 font_scale,
462 );
463 let font = font_for_style(&theme.typography, style, cx);
464 let mut refinement = StyleRefinement::default()
465 .font(font)
466 .text_size(px(style.size))
467 .line_height(px(style.line_height))
468 .font_weight(FontWeight(f32::from(style.weight)))
469 .text_color(body_color);
470 refinement.margin.top = Some(px(8.).into());
471 refinement.margin.bottom = Some(px(4.).into());
472 refinement
473 });
474
475 let code_radius = px(CornerRole::Medium
476 .shape()
477 .radii(200., 80., theme.layout.direction)[0]);
478 let inline_code_radius =
479 px(CornerRole::ExtraSmall
480 .shape()
481 .radii(40., 20., theme.layout.direction)[0]);
482 let code_type = LayoutPolicy::scale_text(
483 theme
484 .typography
485 .style(TypeRole::BodyMedium, TypographyEmphasis::Baseline),
486 font_scale,
487 );
488
489 let code_block_style = StyleRefinement::default()
490 .bg(code_bg)
491 .text_color(code_fg)
492 .font_family(code_family.clone())
493 .text_size(px(code_type.size))
494 .line_height(px(code_type.line_height))
495 .rounded(code_radius)
496 .border_1()
497 .border_color(border_color)
498 .p_3();
499
500 let inline_code_style = StyleRefinement::default()
501 .bg(code_bg)
502 .text_color(code_fg)
503 .font_family(code_family)
504 .rounded(inline_code_radius)
505 .px_1();
506
507 let blockquote_style = StyleRefinement::default()
508 .text_color(muted_color)
509 .border_l(px(3.))
510 .border_color(blockquote_border)
511 .pl_3();
512
513 let table_style = StyleRefinement::default()
514 .rounded(code_radius)
515 .border_1()
516 .border_color(border_color);
517
518 let table_head_style = StyleRefinement::default()
519 .bg(table_head_bg)
520 .text_color(body_color)
521 .font_weight(FontWeight::MEDIUM);
522
523 BaseTextViewStyle::default()
524 .with_foreground(body_color)
525 .with_muted_foreground(muted_color)
526 .with_link(link_color)
527 .with_selection(selection_color)
528 .with_code_background(code_bg)
529 .with_border(border_color)
530 .with_paragraph_gap(paragraph_gap)
531 .with_heading(move |level| {
532 let idx = level.clamp(1, 6) as usize - 1;
533 headings[idx].clone()
534 })
535 .with_code_block(code_block_style)
536 .with_inline_code(HighlightStyle {
537 color: Some(code_fg),
538 background_color: Some(code_bg),
539 ..Default::default()
540 })
541 .with_inline_code_style(inline_code_style)
542 .with_blockquote_style(blockquote_style)
543 .with_table(table_style)
544 .with_table_head(table_head_style)
545 .with_table_row_hover(table_row_hover)
546 .with_dark(is_dark)
547}
548
549struct MonospaceCache(RefCell<Option<(u64, SharedString)>>);
550
551impl Global for MonospaceCache {}
552
553fn resolve_monospace_family(cx: &App) -> SharedString {
554 const CANDIDATES: [&str; 6] = [
555 "Cascadia Mono",
556 "JetBrains Mono",
557 "Consolas",
558 "SF Mono",
559 "DejaVu Sans Mono",
560 "Liberation Mono",
561 ];
562 let revision = font_cache_revision(cx);
563 if let Some(cache) = cx.try_global::<MonospaceCache>()
564 && let Some((cached_rev, family)) = cache.0.borrow().as_ref()
565 && *cached_rev == revision
566 {
567 return family.clone();
568 }
569 let installed = cx.text_system().all_font_names();
570 let resolved = CANDIDATES
571 .iter()
572 .find(|candidate| {
573 installed
574 .iter()
575 .any(|name| name.eq_ignore_ascii_case(candidate))
576 })
577 .copied()
578 .map(SharedString::new_static)
579 .unwrap_or_else(|| SharedString::new_static("monospace"));
580 if let Some(cache) = cx.try_global::<MonospaceCache>() {
581 *cache.0.borrow_mut() = Some((revision, resolved.clone()));
582 }
583 resolved
584}
585
586#[cfg(test)]
587mod tests {
588 use super::*;
589
590 #[test]
591 fn selection_format_maps_all_variants() {
592 assert_eq!(
593 BaseSelectionFormat::from(RichTextSelectionFormat::Plain),
594 BaseSelectionFormat::Plain
595 );
596 assert_eq!(
597 BaseSelectionFormat::from(RichTextSelectionFormat::Source),
598 BaseSelectionFormat::Source
599 );
600 assert_eq!(
601 BaseSelectionFormat::from(RichTextSelectionFormat::SourceAcrossStyles),
602 BaseSelectionFormat::SourceAcrossStyles
603 );
604 }
605
606 #[test]
607 fn rich_text_builders_sanitize_scale_and_max_lines() {
608 let view = RichText::markdown("doc", "# Hello")
609 .font_scale(-2.0)
610 .font_scale(f32::NAN)
611 .max_lines(0);
612 assert_eq!(view.font_scale, 1.0);
613 assert_eq!(view.max_lines, Some(1));
614 }
615}