chore: improve markdown component

This commit is contained in:
2026-11-11 08:58:17 +07:00
parent a952e6cb30
commit 6d6861a766
5 changed files with 387 additions and 288 deletions
+16
View File
@@ -1,5 +1,7 @@
//! The checkbox: a controlled on/off value with an optional label. //! The checkbox: a controlled on/off value with an optional label.
use std::rc::Rc;
use gpui::prelude::FluentBuilder as _; use gpui::prelude::FluentBuilder as _;
use gpui::{ use gpui::{
App, ElementId, InteractiveElement as _, IntoElement, ParentElement as _, RenderOnce, Role, App, ElementId, InteractiveElement as _, IntoElement, ParentElement as _, RenderOnce, Role,
@@ -23,6 +25,7 @@ pub struct Checkbox {
checked: bool, checked: bool,
size: Size, size: Size,
disabled: bool, disabled: bool,
debug_selector: Option<Rc<dyn Fn() -> String>>,
a11y_label: Option<SharedString>, a11y_label: Option<SharedString>,
on_change: Option<ChangeHandler>, on_change: Option<ChangeHandler>,
} }
@@ -39,6 +42,7 @@ impl Checkbox {
checked: false, checked: false,
size: Size::default(), size: Size::default(),
disabled: false, disabled: false,
debug_selector: None,
a11y_label: None, a11y_label: None,
on_change: None, on_change: None,
} }
@@ -65,6 +69,15 @@ impl Checkbox {
self self
} }
/// Sets the debug-bounds selector, for headless tests.
pub fn debug_selector<F>(mut self, selector: F) -> Self
where
F: Fn() -> String + 'static,
{
self.debug_selector = Some(Rc::new(selector));
self
}
/// Overrides the accessibility label, which defaults to the visible label. /// Overrides the accessibility label, which defaults to the visible label.
pub fn accessibility_label<L>(mut self, label: L) -> Self pub fn accessibility_label<L>(mut self, label: L) -> Self
where where
@@ -104,6 +117,9 @@ impl RenderOnce for Checkbox {
.id(self.id) .id(self.id)
.gap_1p5() .gap_1p5()
.text_size(metrics.text_size) .text_size(metrics.text_size)
.when_some(self.debug_selector, |checkbox, selector| {
checkbox.debug_selector(move || selector())
})
.role(Role::CheckBox) .role(Role::CheckBox)
.when_some(a11y_label, |checkbox, label| checkbox.aria_label(label)) .when_some(a11y_label, |checkbox, label| checkbox.aria_label(label))
.aria_toggled(Toggled::from(self.checked)) .aria_toggled(Toggled::from(self.checked))
+1 -1
View File
@@ -44,9 +44,9 @@ diff_view = ["code_view"]
markdown_view = [ markdown_view = [
"dep:gpui-native-core", "dep:gpui-native-core",
"gpui-native-core/button", "gpui-native-core/button",
"gpui-native-core/checkbox",
"gpui-native-core/scrollbar", "gpui-native-core/scrollbar",
"dep:pulldown-cmark", "dep:pulldown-cmark",
"dep:gpui-native-icons",
] ]
rust = ["dep:tree-sitter-rust"] rust = ["dep:tree-sitter-rust"]
typescript = ["dep:tree-sitter-typescript"] typescript = ["dep:tree-sitter-typescript"]
+284 -286
View File
@@ -17,9 +17,10 @@ use gpui::{
actions, div, img, list, px, relative, actions, div, img, list, px, relative,
}; };
use gpui_native_core::button::{Button, ButtonVariant}; use gpui_native_core::button::{Button, ButtonVariant};
use gpui_native_core::checkbox::Checkbox;
use gpui_native_core::common::Sizable as _;
use gpui_native_core::scrollbar::{Scrollbar, ScrollbarVisibility}; use gpui_native_core::scrollbar::{Scrollbar, ScrollbarVisibility};
use gpui_native_icons::{IconRole, icon}; use gpui_native_theme::{ActiveTheme as _, BORDER_WIDTH, CODE_OVERSCROLL_MAX, Size};
use gpui_native_theme::{ActiveTheme as _, BORDER_WIDTH, CODE_OVERSCROLL_MAX};
use pulldown_cmark::{CodeBlockKind, Event, HeadingLevel, Options, Parser, Tag, TagEnd}; use pulldown_cmark::{CodeBlockKind, Event, HeadingLevel, Options, Parser, Tag, TagEnd};
use std::borrow::Borrow as _; use std::borrow::Borrow as _;
@@ -51,6 +52,15 @@ const CODE_LINE_HEIGHT: f32 = 1.5;
const IMAGE_MAX_HEIGHT: f32 = 14.0; const IMAGE_MAX_HEIGHT: f32 = 14.0;
/// The side of an inline image atom relative to the body text size. /// The side of an inline image atom relative to the body text size.
const INLINE_IMAGE_SCALE: f32 = 1.15; const INLINE_IMAGE_SCALE: f32 = 1.15;
/// The key context the text view declares while it holds focus.
pub const TEXT_VIEW_CONTEXT: &str = "TextView";
/// The callback a view invokes when the user clicks a markdown link.
pub type LinkClickHandler = Arc<dyn Fn(&SharedString, &mut Window, &mut App)>;
/// The callback a view invokes when the user toggles a task checkbox.
pub type TaskToggleHandler = Arc<dyn Fn(usize, bool, &mut Window, &mut App)>;
actions!(text_view, [Copy]);
/// A heading level, 1 to 6. /// A heading level, 1 to 6.
#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)] #[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
@@ -88,13 +98,6 @@ pub enum ListMarker {
Task(bool), Task(bool),
} }
/// One run of inline text sharing a style.
#[derive(Clone, Debug, PartialEq, Eq, Hash)]
pub struct InlineSpan {
pub text: SharedString,
pub style: InlineStyle,
}
/// One inline item of a paragraph or list item: styled text or an image. /// One inline item of a paragraph or list item: styled text or an image.
#[derive(Clone, Debug, PartialEq, Eq, Hash)] #[derive(Clone, Debug, PartialEq, Eq, Hash)]
pub enum InlineItem { pub enum InlineItem {
@@ -121,25 +124,6 @@ pub enum InlineStyle {
}, },
} }
/// One cell of a table row.
#[derive(Clone, Debug, Default, PartialEq, Eq, Hash)]
pub struct MarkdownTableCell {
pub spans: Vec<InlineSpan>,
}
/// A table row; the header row precedes the body rows.
#[derive(Clone, Debug, Default, PartialEq, Eq, Hash)]
pub struct MarkdownTableRow {
pub cells: Vec<MarkdownTableCell>,
pub header: bool,
}
/// A table, header row first.
#[derive(Clone, Debug, Default, PartialEq, Eq, Hash)]
pub struct MarkdownTable {
pub rows: Vec<MarkdownTableRow>,
}
/// One rendered block of a markdown document. /// One rendered block of a markdown document.
#[derive(Clone, Debug, PartialEq, Eq, Hash)] #[derive(Clone, Debug, PartialEq, Eq, Hash)]
pub enum MarkdownBlock { pub enum MarkdownBlock {
@@ -202,26 +186,30 @@ impl MarkdownBlock {
} }
} }
/// The key context the text view declares while it holds focus. /// One run of inline text sharing a style.
pub const TEXT_VIEW_CONTEXT: &str = "TextView"; #[derive(Clone, Debug, PartialEq, Eq, Hash)]
pub struct InlineSpan {
pub text: SharedString,
pub style: InlineStyle,
}
/// The callback a view invokes when the user clicks a markdown link. /// One cell of a table row.
pub type LinkClickHandler = Arc<dyn Fn(&SharedString, &mut Window, &mut App)>; #[derive(Clone, Debug, Default, PartialEq, Eq, Hash)]
/// The callback a view invokes when the user toggles a task checkbox. pub struct MarkdownTableCell {
pub type TaskToggleHandler = Arc<dyn Fn(usize, bool, &mut Window, &mut App)>; pub spans: Vec<InlineSpan>,
}
actions!(text_view, [Copy]); /// A table row; the header row precedes the body rows.
#[derive(Clone, Debug, Default, PartialEq, Eq, Hash)]
pub struct MarkdownTableRow {
pub cells: Vec<MarkdownTableCell>,
pub header: bool,
}
/// Binds the text view's copy chord: cmd-c on macOS, ctrl-c elsewhere. /// A table, header row first.
/// #[derive(Clone, Debug, Default, PartialEq, Eq, Hash)]
/// Call once at startup. Without it, selection copy has no key. pub struct MarkdownTable {
pub fn bind_text_view_keys(cx: &mut App) { pub rows: Vec<MarkdownTableRow>,
let context = Some(TEXT_VIEW_CONTEXT);
#[cfg(target_os = "macos")]
let copy = "cmd-c";
#[cfg(not(target_os = "macos"))]
let copy = "ctrl-c";
cx.bind_keys([KeyBinding::new(copy, Copy, context)]);
} }
/// Retained state for a markdown view. /// Retained state for a markdown view.
@@ -543,72 +531,6 @@ struct PieceContext {
pressed_on_piece: std::rc::Rc<std::cell::Cell<bool>>, pressed_on_piece: std::rc::Rc<std::cell::Cell<bool>>,
} }
/// The view's base container: selection wiring, focus, and copy.
fn view_container(frame: &ViewFrame) -> Div {
let clear_flag = frame.pressed_on_piece.clone();
div()
.w_full()
.flex()
.flex_col()
.key_context(TEXT_VIEW_CONTEXT)
.track_focus(&frame.focus_handle)
.on_action({
let state = frame.state.clone();
move |_: &Copy, _window, cx| {
if let Some(text) = state.read(cx).selected_text() {
cx.write_to_clipboard(ClipboardItem::new_string(text));
}
}
})
.on_mouse_down(MouseButton::Left, {
let state = frame.state.clone();
move |_, window, cx| {
let focus_handle = state.update(cx, |view, cx| view.focus_handle(cx));
window.focus(&focus_handle, cx);
if !clear_flag.replace(false) {
state.update(cx, |view, cx| {
if view.selection.take().is_some() {
cx.notify();
}
});
}
}
})
.on_mouse_up(MouseButton::Left, {
let state = frame.state.clone();
move |_, _, cx| {
if state.read(cx).selecting {
state.update(cx, |view, cx| {
view.selecting = false;
cx.notify();
});
}
}
})
}
/// Renders every block stacked, without virtualization or scrolling.
fn render_blocks(
blocks: &[MarkdownBlock],
frame: &ViewFrame,
doc: &TextDocument,
block_ids: &[ElementId],
cx: &App,
) -> Div {
view_container(frame).children(blocks.iter().zip(block_ids).enumerate().map(
|(block_index, (block, block_id))| {
let ctx = BlockContext {
frame,
doc,
block_index,
block_id,
};
render_block(block, block_index, &ctx, cx)
},
))
}
/// One selectable stretch of rendered text. /// One selectable stretch of rendered text.
#[derive(Clone, Debug)] #[derive(Clone, Debug)]
pub struct TextPiece { pub struct TextPiece {
@@ -662,78 +584,6 @@ impl TextDocument {
} }
} }
fn spans_text_of(spans: &[InlineSpan]) -> String {
spans.iter().map(|span| span.text.as_ref()).collect()
}
/// The selectable text units of a block.
fn block_text_units(block: &MarkdownBlock) -> Vec<String> {
match block {
MarkdownBlock::Heading { spans, .. } => vec![spans_text_of(spans)],
MarkdownBlock::Paragraph { items, .. } | MarkdownBlock::ListItem { items, .. } => {
let mut units: Vec<String> = Vec::new();
for item in items {
match item {
InlineItem::Text(span) => match units.last_mut() {
// Consecutive text items share the unit between images.
Some(unit) => unit.push_str(&span.text),
None => units.push(span.text.as_ref().to_string()),
},
// An image starts the next unit; the render emits no
// element for it.
InlineItem::Image { .. } => units.push(String::new()),
}
}
units
}
MarkdownBlock::Code { lines, .. } => lines.lines.iter().map(|line| line.text()).collect(),
MarkdownBlock::Table { table, .. } => table
.rows
.iter()
.flat_map(|row| row.cells.iter())
.map(|cell| spans_text_of(&cell.spans))
.collect(),
MarkdownBlock::Image { .. } | MarkdownBlock::ThematicBreak { .. } => Vec::new(),
}
}
/// Enumerates the selectable text pieces of `blocks`, in render order.
fn text_document(blocks: &[MarkdownBlock]) -> TextDocument {
let mut pieces = Vec::new();
let mut len = 0usize;
for (block_index, block) in blocks.iter().enumerate() {
// Paragraphs render no element for an empty unit.
let skip_empty = matches!(
block,
MarkdownBlock::Paragraph { .. } | MarkdownBlock::ListItem { .. }
);
for (sub_index, unit) in block_text_units(block).into_iter().enumerate() {
if unit.is_empty() && skip_empty {
continue;
}
let mut range = len..len;
if !unit.is_empty() {
if len > 0 {
len += 1; // The newline that joins pieces.
}
range = len..len + unit.len();
len = range.end;
}
pieces.push(TextPiece {
block_index,
sub_index,
range,
});
}
}
TextDocument { pieces, len }
}
/// An embeddable markdown text view: fit-content height, no scrolling. /// An embeddable markdown text view: fit-content height, no scrolling.
pub struct TextView { pub struct TextView {
id: ElementId, id: ElementId,
@@ -965,6 +815,156 @@ impl InlineBuilder {
} }
} }
/// Binds the text view's copy chord: cmd-c on macOS, ctrl-c elsewhere.
///
/// Call once at startup. Without it, selection copy has no key.
pub fn bind_text_view_keys(cx: &mut App) {
let context = Some(TEXT_VIEW_CONTEXT);
#[cfg(target_os = "macos")]
let copy = "cmd-c";
#[cfg(not(target_os = "macos"))]
let copy = "ctrl-c";
cx.bind_keys([KeyBinding::new(copy, Copy, context)]);
}
/// The view's base container: selection wiring, focus, and copy.
fn view_container(frame: &ViewFrame) -> Div {
let clear_flag = frame.pressed_on_piece.clone();
div()
.w_full()
.flex()
.flex_col()
.key_context(TEXT_VIEW_CONTEXT)
.track_focus(&frame.focus_handle)
.on_action({
let state = frame.state.clone();
move |_: &Copy, _window, cx| {
if let Some(text) = state.read(cx).selected_text() {
cx.write_to_clipboard(ClipboardItem::new_string(text));
}
}
})
.on_mouse_down(MouseButton::Left, {
let state = frame.state.clone();
move |_, window, cx| {
let focus_handle = state.update(cx, |view, cx| view.focus_handle(cx));
window.focus(&focus_handle, cx);
if !clear_flag.replace(false) {
state.update(cx, |view, cx| {
if view.selection.take().is_some() {
cx.notify();
}
});
}
}
})
.on_mouse_up(MouseButton::Left, {
let state = frame.state.clone();
move |_, _, cx| {
if state.read(cx).selecting {
state.update(cx, |view, cx| {
view.selecting = false;
cx.notify();
});
}
}
})
}
/// Renders every block stacked, without virtualization or scrolling.
fn render_blocks(
blocks: &[MarkdownBlock],
frame: &ViewFrame,
doc: &TextDocument,
block_ids: &[ElementId],
cx: &App,
) -> Div {
view_container(frame).children(blocks.iter().zip(block_ids).enumerate().map(
|(block_index, (block, block_id))| {
let ctx = BlockContext {
frame,
doc,
block_index,
block_id,
};
render_block(block, block_index, &ctx, cx)
},
))
}
fn spans_text_of(spans: &[InlineSpan]) -> String {
spans.iter().map(|span| span.text.as_ref()).collect()
}
/// The selectable text units of a block.
fn block_text_units(block: &MarkdownBlock) -> Vec<String> {
match block {
MarkdownBlock::Heading { spans, .. } => vec![spans_text_of(spans)],
MarkdownBlock::Paragraph { items, .. } | MarkdownBlock::ListItem { items, .. } => {
let mut units: Vec<String> = Vec::new();
for item in items {
match item {
InlineItem::Text(span) => match units.last_mut() {
// Consecutive text items share the unit between images.
Some(unit) => unit.push_str(&span.text),
None => units.push(span.text.as_ref().to_string()),
},
// An image starts the next unit; the render emits no
// element for it.
InlineItem::Image { .. } => units.push(String::new()),
}
}
units
}
MarkdownBlock::Code { lines, .. } => lines.lines.iter().map(|line| line.text()).collect(),
MarkdownBlock::Table { table, .. } => table
.rows
.iter()
.flat_map(|row| row.cells.iter())
.map(|cell| spans_text_of(&cell.spans))
.collect(),
MarkdownBlock::Image { .. } | MarkdownBlock::ThematicBreak { .. } => Vec::new(),
}
}
/// Enumerates the selectable text pieces of `blocks`, in render order.
fn text_document(blocks: &[MarkdownBlock]) -> TextDocument {
let mut pieces = Vec::new();
let mut len = 0usize;
for (block_index, block) in blocks.iter().enumerate() {
// Paragraphs render no element for an empty unit.
let skip_empty = matches!(
block,
MarkdownBlock::Paragraph { .. } | MarkdownBlock::ListItem { .. }
);
for (sub_index, unit) in block_text_units(block).into_iter().enumerate() {
if unit.is_empty() && skip_empty {
continue;
}
let mut range = len..len;
if !unit.is_empty() {
if len > 0 {
len += 1; // The newline that joins pieces.
}
range = len..len + unit.len();
len = range.end;
}
pieces.push(TextPiece {
block_index,
sub_index,
range,
});
}
}
TextDocument { pieces, len }
}
/// The markdown extensions the view parses, on top of CommonMark. /// The markdown extensions the view parses, on top of CommonMark.
fn options() -> Options { fn options() -> Options {
let mut options = Options::empty(); let mut options = Options::empty();
@@ -1450,17 +1450,10 @@ fn render_block(
} }
} }
/// The shared block frame: ambient text style, indent, spacing, quote bar. /// The shared block frame: ambient text style, spacing, quote bar.
fn block_frame( fn block_frame(quote: bool, top: Pixels, bottom: Pixels, id: &ElementId, cx: &App) -> Div {
indent: usize,
quote: bool,
top: Pixels,
bottom: Pixels,
id: &ElementId,
cx: &App,
) -> Div {
let theme = cx.theme(); let theme = cx.theme();
let content = div() div()
.debug_selector({ .debug_selector({
let id = id.clone(); let id = id.clone();
move || id.to_string() move || id.to_string()
@@ -1479,13 +1472,17 @@ fn block_frame(
.border_l_2() .border_l_2()
.border_color(theme.colors.border) .border_color(theme.colors.border)
.pl(theme.root_font_size * QUOTE_INSET) .pl(theme.root_font_size * QUOTE_INSET)
}); })
}
/// Wraps the finished block in the list indent.
fn indented_frame(indent: usize, frame: Div, cx: &App) -> Div {
let indent_px = cx.theme().root_font_size * INDENT_STEP * indent as f32;
let indent_px = theme.root_font_size * INDENT_STEP * indent as f32;
if indent_px > px(0.) { if indent_px > px(0.) {
div().w_full().pl(indent_px).child(content) div().w_full().pl(indent_px).child(frame)
} else { } else {
content frame
} }
} }
@@ -1502,18 +1499,21 @@ fn heading_row(
let theme = cx.theme(); let theme = cx.theme();
let scale = HEADING_SCALES[(level.level() - 1).min(HEADING_SCALES.len() - 1)]; let scale = HEADING_SCALES[(level.level() - 1).min(HEADING_SCALES.len() - 1)];
block_frame( indented_frame(
indent, indent,
quote, block_frame(
top, quote,
theme.root_font_size * BLOCK_GAP, top,
ctx.block_id, theme.root_font_size * BLOCK_GAP,
ctx.block_id,
cx,
)
.text_size(theme.root_font_size * scale)
.line_height(relative(1.3))
.font_weight(FontWeight::SEMIBOLD)
.child(text_child(spans, ctx.block_id, ctx.piece_context(0), cx)),
cx, cx,
) )
.text_size(theme.root_font_size * scale)
.line_height(relative(1.3))
.font_weight(FontWeight::SEMIBOLD)
.child(text_child(spans, ctx.block_id, ctx.piece_context(0), cx))
.into_any_element() .into_any_element()
} }
@@ -1528,8 +1528,9 @@ fn text_row(
) -> AnyElement { ) -> AnyElement {
let theme = cx.theme(); let theme = cx.theme();
block_frame(indent, quote, px(0.), bottom, ctx.block_id, cx) indented_frame(
.map(|frame| match marker { indent,
block_frame(quote, px(0.), bottom, ctx.block_id, cx).map(|frame| match marker {
Some(marker) => { Some(marker) => {
let line_height = theme.sizes.small.text_size * BODY_LINE_HEIGHT; let line_height = theme.sizes.small.text_size * BODY_LINE_HEIGHT;
let marker_cell = div() let marker_cell = div()
@@ -1550,7 +1551,7 @@ fn text_row(
.whitespace_nowrap() .whitespace_nowrap()
.child(format!("{number}.")) .child(format!("{number}."))
.into_any_element(), .into_any_element(),
ListMarker::Task(checked) => task_toggle(checked, ctx, cx), ListMarker::Task(checked) => task_toggle(checked, item_text(items), ctx),
}); });
frame.child( frame.child(
@@ -1563,30 +1564,44 @@ fn text_row(
) )
} }
None => frame.child(paragraph_child(items, ctx, cx)), None => frame.child(paragraph_child(items, ctx, cx)),
}) }),
.into_any_element() cx,
)
.into_any_element()
} }
/// The task marker: a clickable checkbox when the view toggles tasks. /// The task marker: a checkbox that reports toggles when a handler is set.
fn task_toggle(checked: bool, ctx: &BlockContext, cx: &App) -> AnyElement { fn task_toggle(checked: bool, label: SharedString, ctx: &BlockContext) -> AnyElement {
let block_index = ctx.block_index;
let selector = SharedString::from(format!("task-toggle-{block_index}"));
let checkbox = Checkbox::new((ctx.block_id.clone(), "task"))
.debug_selector(move || selector.to_string())
.checked(checked)
.with_size(Size::Small)
.accessibility_label(label);
match ctx.frame.task_toggle.clone() { match ctx.frame.task_toggle.clone() {
Some(handler) => { Some(handler) => checkbox
let block_index = ctx.block_index; .on_change(move |next, window, cx| handler(block_index, next, window, cx))
let selector = SharedString::from(format!("task-toggle-{block_index}")); .into_any_element(),
div() None => checkbox.disabled(true).into_any_element(),
.id((ctx.block_id.clone(), "task"))
.debug_selector(move || selector.to_string())
.flex_none()
.child(task_box(checked, cx))
.on_click(move |_, window, cx| handler(block_index, !checked, window, cx))
.into_any_element()
}
None => task_box(checked, cx),
} }
} }
/// Builds a paragraph's content: one text run, or a wrapping flow of text /// The item's plain text, for the checkbox's accessibility label.
/// segments and image atoms when the paragraph holds images. fn item_text(items: &[InlineItem]) -> SharedString {
let text = items
.iter()
.filter_map(|item| match item {
InlineItem::Text(span) => Some(span.text.as_ref()),
InlineItem::Image { .. } => None,
})
.collect::<Vec<_>>()
.join("");
SharedString::from(text)
}
/// Builds a paragraph's content.
fn paragraph_child(items: &[InlineItem], ctx: &BlockContext, cx: &App) -> AnyElement { fn paragraph_child(items: &[InlineItem], ctx: &BlockContext, cx: &App) -> AnyElement {
let has_image = items let has_image = items
.iter() .iter()
@@ -1649,21 +1664,24 @@ fn image_row(
cx: &App, cx: &App,
) -> AnyElement { ) -> AnyElement {
let theme = cx.theme(); let theme = cx.theme();
block_frame( indented_frame(
indent, indent,
quote, block_frame(
px(0.), quote,
theme.root_font_size * BLOCK_GAP, px(0.),
ctx.block_id, theme.root_font_size * BLOCK_GAP,
ctx.block_id,
cx,
)
.child(
img(source.clone())
.max_h(theme.root_font_size * IMAGE_MAX_HEIGHT)
.max_w_full()
.rounded(theme.radius.control)
.overflow_hidden(),
),
cx, cx,
) )
.child(
img(source.clone())
.max_h(theme.root_font_size * IMAGE_MAX_HEIGHT)
.max_w_full()
.rounded(theme.radius.control)
.overflow_hidden(),
)
.id((ctx.block_id.clone(), "image")) .id((ctx.block_id.clone(), "image"))
.when(!alt.is_empty(), |frame| frame.aria_label(alt.clone())) .when(!alt.is_empty(), |frame| frame.aria_label(alt.clone()))
.into_any_element() .into_any_element()
@@ -1674,35 +1692,6 @@ fn text_segment_id(id: &ElementId, segment_index: usize) -> ElementId {
ElementId::from(SharedString::from(format!("{id}-text-{segment_index}"))) ElementId::from(SharedString::from(format!("{id}-text-{segment_index}")))
} }
/// A read-only task item indicator, matching the checkbox component.
fn task_box(checked: bool, cx: &App) -> AnyElement {
let theme = cx.theme();
let side = theme.sizes.small.dense_icon_size;
let glyph = side * 0.8;
div()
.flex_none()
.size(side)
.rounded(theme.radius.sm)
.border_1()
.when(checked, |box_element| {
box_element
.bg(theme.ramps.primary.base)
.border_color(theme.ramps.primary.base)
.child(
icon(IconRole::Check)
.size(glyph)
.color(theme.colors.primary_foreground),
)
})
.when(!checked, |box_element| {
box_element
.bg(theme.colors.input)
.border_color(theme.colors.border)
})
.into_any_element()
}
fn code_row( fn code_row(
lines: &HighlightedCode, lines: &HighlightedCode,
language: Option<&SharedString>, language: Option<&SharedString>,
@@ -1770,29 +1759,35 @@ fn code_row(
) )
})); }));
block_frame( indented_frame(
indent, indent,
quote, block_frame(
px(0.), quote,
theme.root_font_size * BLOCK_GAP, px(0.),
ctx.block_id, theme.root_font_size * BLOCK_GAP,
ctx.block_id,
cx,
)
.child(plate),
cx, cx,
) )
.child(plate)
.into_any_element() .into_any_element()
} }
fn rule_row(indent: usize, quote: bool, ctx: &BlockContext, cx: &App) -> AnyElement { fn rule_row(indent: usize, quote: bool, ctx: &BlockContext, cx: &App) -> AnyElement {
let theme = cx.theme(); let theme = cx.theme();
block_frame( indented_frame(
indent, indent,
quote, block_frame(
px(0.), quote,
theme.root_font_size * BLOCK_GAP, px(0.),
ctx.block_id, theme.root_font_size * BLOCK_GAP,
ctx.block_id,
cx,
)
.child(div().h(BORDER_WIDTH).w_full().bg(theme.colors.border)),
cx, cx,
) )
.child(div().h(BORDER_WIDTH).w_full().bg(theme.colors.border))
.into_any_element() .into_any_element()
} }
@@ -1859,15 +1854,18 @@ fn table_row(
) )
})); }));
block_frame( indented_frame(
indent, indent,
quote, block_frame(
px(0.), quote,
theme.root_font_size * BLOCK_GAP, px(0.),
ctx.block_id, theme.root_font_size * BLOCK_GAP,
ctx.block_id,
cx,
)
.child(grid),
cx, cx,
) )
.child(grid)
.into_any_element() .into_any_element()
} }
+25
View File
@@ -488,6 +488,31 @@ fn blocks_render_virtualized_and_scroll_to_a_block() {
); );
} }
#[test]
fn indented_blocks_render_inside_the_frame_text_style() {
let (_cx, mut visual, state) =
view_window("- top task\n - nested task\n\n1. outer\n 1. inner\n");
let ids = _cx.update(|cx| [0, 1, 2, 3].map(|index| block_id(&state, cx, index)));
let mut height = |id: &'static str| {
visual
.debug_bounds(id)
.map(|bounds| bounds.size.height)
.expect("the block renders")
};
assert_eq!(
height(ids[0]),
height(ids[1]),
"the nested task must keep the frame's text metrics"
);
assert_eq!(
height(ids[2]),
height(ids[3]),
"the nested ordered item must keep the frame's text metrics"
);
}
#[test] #[test]
fn clicking_a_link_opens_its_destination() { fn clicking_a_link_opens_its_destination() {
let (_cx, mut visual, state) = view_window("[click me](https://example.com/welcome)"); let (_cx, mut visual, state) = view_window("[click me](https://example.com/welcome)");
+61 -1
View File
@@ -1,3 +1,4 @@
use std::sync::Arc;
use std::time::Duration; use std::time::Duration;
use gpui::prelude::FluentBuilder as _; use gpui::prelude::FluentBuilder as _;
@@ -46,7 +47,7 @@ use gpui_native_data::tree::{Tree, TreeItem};
use gpui_native_editor::code_view::CodeViewState; use gpui_native_editor::code_view::CodeViewState;
use gpui_native_editor::diff_view::{DiffRowKind, DiffViewState}; use gpui_native_editor::diff_view::{DiffRowKind, DiffViewState};
use gpui_native_editor::highlight::Language; use gpui_native_editor::highlight::Language;
use gpui_native_editor::markdown::{MarkdownBlock, MarkdownViewState, TextView}; use gpui_native_editor::markdown::{ListMarker, MarkdownBlock, MarkdownViewState, TextView};
use gpui_native_icons::{IconAssets, IconRole, icon}; use gpui_native_icons::{IconAssets, IconRole, icon};
use gpui_native_layout::dock::{Dock, DockSidebar, DockState, PanelDescriptor, SplitDirection}; use gpui_native_layout::dock::{Dock, DockSidebar, DockState, PanelDescriptor, SplitDirection};
use gpui_native_layout::resizable::{Resizable, ResizableState}; use gpui_native_layout::resizable::{Resizable, ResizableState};
@@ -3640,6 +3641,12 @@ impl MarkdownViewDemo {
// The panel is a cached view in the dock: it re-renders only when // The panel is a cached view in the dock: it re-renders only when
// the markdown state it renders is notified. // the markdown state it renders is notified.
let subscription = cx.observe(&view, |_, _, cx| cx.notify()); let subscription = cx.observe(&view, |_, _, cx| cx.notify());
let demo = cx.entity();
view.update(cx, |view, _cx| {
view.set_task_toggle_handler(Arc::new(move |block_index, checked, _window, cx| {
demo.update(cx, |demo, cx| demo.toggle_task(block_index, checked, cx));
}));
});
Self { Self {
view, view,
sample: MarkdownSample::Guide, sample: MarkdownSample::Guide,
@@ -3648,6 +3655,59 @@ impl MarkdownViewDemo {
} }
} }
/// Rewrites the toggled task's source line and re-renders the view.
fn toggle_task(&mut self, block_index: usize, checked: bool, cx: &mut App) {
let source = match self.sample {
MarkdownSample::Guide => MARKDOWN_SAMPLE.to_string(),
MarkdownSample::Large => self.large_source.to_string(),
};
// Blocks render in source order, so the block's rank among task
// blocks names the task line to rewrite.
let task_rank = self
.view
.read(cx)
.blocks()
.iter()
.take(block_index + 1)
.filter(|block| {
matches!(
block,
MarkdownBlock::ListItem {
marker: ListMarker::Task(_),
..
}
)
})
.count()
.saturating_sub(1);
let mut lines: Vec<String> = source.lines().map(String::from).collect();
let trailing_newline = source.ends_with('\n');
let mut seen = 0usize;
for line in &mut lines {
let trimmed = line.trim_start();
if !trimmed.starts_with("- [ ] ") && !trimmed.starts_with("- [x] ") {
continue;
}
if seen < task_rank {
seen += 1;
continue;
}
let Some(marker_at) = line.find('[') else {
continue;
};
line.replace_range(
marker_at + 1..marker_at + 2,
if checked { "x" } else { " " },
);
break;
}
let mut source = lines.join("\n");
if trailing_newline {
source.push('\n');
}
self.view.update(cx, |view, cx| view.set_source(source, cx));
}
/// Generates a long markdown document, so scrolling the view can be /// Generates a long markdown document, so scrolling the view can be
/// exercised on realistic content. /// exercised on realistic content.
fn large_markdown(sections: usize) -> String { fn large_markdown(sections: usize) -> String {