chore: improve markdown component
This commit is contained in:
@@ -1,5 +1,7 @@
|
||||
//! The checkbox: a controlled on/off value with an optional label.
|
||||
|
||||
use std::rc::Rc;
|
||||
|
||||
use gpui::prelude::FluentBuilder as _;
|
||||
use gpui::{
|
||||
App, ElementId, InteractiveElement as _, IntoElement, ParentElement as _, RenderOnce, Role,
|
||||
@@ -23,6 +25,7 @@ pub struct Checkbox {
|
||||
checked: bool,
|
||||
size: Size,
|
||||
disabled: bool,
|
||||
debug_selector: Option<Rc<dyn Fn() -> String>>,
|
||||
a11y_label: Option<SharedString>,
|
||||
on_change: Option<ChangeHandler>,
|
||||
}
|
||||
@@ -39,6 +42,7 @@ impl Checkbox {
|
||||
checked: false,
|
||||
size: Size::default(),
|
||||
disabled: false,
|
||||
debug_selector: None,
|
||||
a11y_label: None,
|
||||
on_change: None,
|
||||
}
|
||||
@@ -65,6 +69,15 @@ impl Checkbox {
|
||||
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.
|
||||
pub fn accessibility_label<L>(mut self, label: L) -> Self
|
||||
where
|
||||
@@ -104,6 +117,9 @@ impl RenderOnce for Checkbox {
|
||||
.id(self.id)
|
||||
.gap_1p5()
|
||||
.text_size(metrics.text_size)
|
||||
.when_some(self.debug_selector, |checkbox, selector| {
|
||||
checkbox.debug_selector(move || selector())
|
||||
})
|
||||
.role(Role::CheckBox)
|
||||
.when_some(a11y_label, |checkbox, label| checkbox.aria_label(label))
|
||||
.aria_toggled(Toggled::from(self.checked))
|
||||
|
||||
@@ -44,9 +44,9 @@ diff_view = ["code_view"]
|
||||
markdown_view = [
|
||||
"dep:gpui-native-core",
|
||||
"gpui-native-core/button",
|
||||
"gpui-native-core/checkbox",
|
||||
"gpui-native-core/scrollbar",
|
||||
"dep:pulldown-cmark",
|
||||
"dep:gpui-native-icons",
|
||||
]
|
||||
rust = ["dep:tree-sitter-rust"]
|
||||
typescript = ["dep:tree-sitter-typescript"]
|
||||
|
||||
+251
-253
@@ -17,9 +17,10 @@ use gpui::{
|
||||
actions, div, img, list, px, relative,
|
||||
};
|
||||
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_icons::{IconRole, icon};
|
||||
use gpui_native_theme::{ActiveTheme as _, BORDER_WIDTH, CODE_OVERSCROLL_MAX};
|
||||
use gpui_native_theme::{ActiveTheme as _, BORDER_WIDTH, CODE_OVERSCROLL_MAX, Size};
|
||||
use pulldown_cmark::{CodeBlockKind, Event, HeadingLevel, Options, Parser, Tag, TagEnd};
|
||||
|
||||
use std::borrow::Borrow as _;
|
||||
@@ -51,6 +52,15 @@ const CODE_LINE_HEIGHT: f32 = 1.5;
|
||||
const IMAGE_MAX_HEIGHT: f32 = 14.0;
|
||||
/// The side of an inline image atom relative to the body text size.
|
||||
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.
|
||||
#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
|
||||
@@ -88,13 +98,6 @@ pub enum ListMarker {
|
||||
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.
|
||||
#[derive(Clone, Debug, PartialEq, Eq, Hash)]
|
||||
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.
|
||||
#[derive(Clone, Debug, PartialEq, Eq, Hash)]
|
||||
pub enum MarkdownBlock {
|
||||
@@ -202,26 +186,30 @@ impl MarkdownBlock {
|
||||
}
|
||||
}
|
||||
|
||||
/// The key context the text view declares while it holds focus.
|
||||
pub const TEXT_VIEW_CONTEXT: &str = "TextView";
|
||||
/// One run of inline text sharing a style.
|
||||
#[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.
|
||||
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)>;
|
||||
/// One cell of a table row.
|
||||
#[derive(Clone, Debug, Default, PartialEq, Eq, Hash)]
|
||||
pub struct MarkdownTableCell {
|
||||
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.
|
||||
///
|
||||
/// 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)]);
|
||||
/// A table, header row first.
|
||||
#[derive(Clone, Debug, Default, PartialEq, Eq, Hash)]
|
||||
pub struct MarkdownTable {
|
||||
pub rows: Vec<MarkdownTableRow>,
|
||||
}
|
||||
|
||||
/// Retained state for a markdown view.
|
||||
@@ -543,72 +531,6 @@ struct PieceContext {
|
||||
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.
|
||||
#[derive(Clone, Debug)]
|
||||
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.
|
||||
pub struct TextView {
|
||||
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.
|
||||
fn options() -> Options {
|
||||
let mut options = Options::empty();
|
||||
@@ -1450,17 +1450,10 @@ fn render_block(
|
||||
}
|
||||
}
|
||||
|
||||
/// The shared block frame: ambient text style, indent, spacing, quote bar.
|
||||
fn block_frame(
|
||||
indent: usize,
|
||||
quote: bool,
|
||||
top: Pixels,
|
||||
bottom: Pixels,
|
||||
id: &ElementId,
|
||||
cx: &App,
|
||||
) -> Div {
|
||||
/// The shared block frame: ambient text style, spacing, quote bar.
|
||||
fn block_frame(quote: bool, top: Pixels, bottom: Pixels, id: &ElementId, cx: &App) -> Div {
|
||||
let theme = cx.theme();
|
||||
let content = div()
|
||||
div()
|
||||
.debug_selector({
|
||||
let id = id.clone();
|
||||
move || id.to_string()
|
||||
@@ -1479,13 +1472,17 @@ fn block_frame(
|
||||
.border_l_2()
|
||||
.border_color(theme.colors.border)
|
||||
.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.) {
|
||||
div().w_full().pl(indent_px).child(content)
|
||||
div().w_full().pl(indent_px).child(frame)
|
||||
} else {
|
||||
content
|
||||
frame
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1502,8 +1499,9 @@ fn heading_row(
|
||||
let theme = cx.theme();
|
||||
let scale = HEADING_SCALES[(level.level() - 1).min(HEADING_SCALES.len() - 1)];
|
||||
|
||||
block_frame(
|
||||
indented_frame(
|
||||
indent,
|
||||
block_frame(
|
||||
quote,
|
||||
top,
|
||||
theme.root_font_size * BLOCK_GAP,
|
||||
@@ -1513,7 +1511,9 @@ fn heading_row(
|
||||
.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))
|
||||
.child(text_child(spans, ctx.block_id, ctx.piece_context(0), cx)),
|
||||
cx,
|
||||
)
|
||||
.into_any_element()
|
||||
}
|
||||
|
||||
@@ -1528,8 +1528,9 @@ fn text_row(
|
||||
) -> AnyElement {
|
||||
let theme = cx.theme();
|
||||
|
||||
block_frame(indent, quote, px(0.), bottom, ctx.block_id, cx)
|
||||
.map(|frame| match marker {
|
||||
indented_frame(
|
||||
indent,
|
||||
block_frame(quote, px(0.), bottom, ctx.block_id, cx).map(|frame| match marker {
|
||||
Some(marker) => {
|
||||
let line_height = theme.sizes.small.text_size * BODY_LINE_HEIGHT;
|
||||
let marker_cell = div()
|
||||
@@ -1550,7 +1551,7 @@ fn text_row(
|
||||
.whitespace_nowrap()
|
||||
.child(format!("{number}."))
|
||||
.into_any_element(),
|
||||
ListMarker::Task(checked) => task_toggle(checked, ctx, cx),
|
||||
ListMarker::Task(checked) => task_toggle(checked, item_text(items), ctx),
|
||||
});
|
||||
|
||||
frame.child(
|
||||
@@ -1563,30 +1564,44 @@ fn text_row(
|
||||
)
|
||||
}
|
||||
None => frame.child(paragraph_child(items, ctx, cx)),
|
||||
})
|
||||
}),
|
||||
cx,
|
||||
)
|
||||
.into_any_element()
|
||||
}
|
||||
|
||||
/// The task marker: a clickable checkbox when the view toggles tasks.
|
||||
fn task_toggle(checked: bool, ctx: &BlockContext, cx: &App) -> AnyElement {
|
||||
match ctx.frame.task_toggle.clone() {
|
||||
Some(handler) => {
|
||||
/// The task marker: a checkbox that reports toggles when a handler is set.
|
||||
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}"));
|
||||
div()
|
||||
.id((ctx.block_id.clone(), "task"))
|
||||
let checkbox = Checkbox::new((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),
|
||||
.checked(checked)
|
||||
.with_size(Size::Small)
|
||||
.accessibility_label(label);
|
||||
|
||||
match ctx.frame.task_toggle.clone() {
|
||||
Some(handler) => checkbox
|
||||
.on_change(move |next, window, cx| handler(block_index, next, window, cx))
|
||||
.into_any_element(),
|
||||
None => checkbox.disabled(true).into_any_element(),
|
||||
}
|
||||
}
|
||||
|
||||
/// Builds a paragraph's content: one text run, or a wrapping flow of text
|
||||
/// segments and image atoms when the paragraph holds images.
|
||||
/// The item's plain text, for the checkbox's accessibility label.
|
||||
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 {
|
||||
let has_image = items
|
||||
.iter()
|
||||
@@ -1649,8 +1664,9 @@ fn image_row(
|
||||
cx: &App,
|
||||
) -> AnyElement {
|
||||
let theme = cx.theme();
|
||||
block_frame(
|
||||
indented_frame(
|
||||
indent,
|
||||
block_frame(
|
||||
quote,
|
||||
px(0.),
|
||||
theme.root_font_size * BLOCK_GAP,
|
||||
@@ -1663,6 +1679,8 @@ fn image_row(
|
||||
.max_w_full()
|
||||
.rounded(theme.radius.control)
|
||||
.overflow_hidden(),
|
||||
),
|
||||
cx,
|
||||
)
|
||||
.id((ctx.block_id.clone(), "image"))
|
||||
.when(!alt.is_empty(), |frame| frame.aria_label(alt.clone()))
|
||||
@@ -1674,35 +1692,6 @@ fn text_segment_id(id: &ElementId, segment_index: usize) -> ElementId {
|
||||
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(
|
||||
lines: &HighlightedCode,
|
||||
language: Option<&SharedString>,
|
||||
@@ -1770,29 +1759,35 @@ fn code_row(
|
||||
)
|
||||
}));
|
||||
|
||||
block_frame(
|
||||
indented_frame(
|
||||
indent,
|
||||
block_frame(
|
||||
quote,
|
||||
px(0.),
|
||||
theme.root_font_size * BLOCK_GAP,
|
||||
ctx.block_id,
|
||||
cx,
|
||||
)
|
||||
.child(plate)
|
||||
.child(plate),
|
||||
cx,
|
||||
)
|
||||
.into_any_element()
|
||||
}
|
||||
|
||||
fn rule_row(indent: usize, quote: bool, ctx: &BlockContext, cx: &App) -> AnyElement {
|
||||
let theme = cx.theme();
|
||||
block_frame(
|
||||
indented_frame(
|
||||
indent,
|
||||
block_frame(
|
||||
quote,
|
||||
px(0.),
|
||||
theme.root_font_size * BLOCK_GAP,
|
||||
ctx.block_id,
|
||||
cx,
|
||||
)
|
||||
.child(div().h(BORDER_WIDTH).w_full().bg(theme.colors.border))
|
||||
.child(div().h(BORDER_WIDTH).w_full().bg(theme.colors.border)),
|
||||
cx,
|
||||
)
|
||||
.into_any_element()
|
||||
}
|
||||
|
||||
@@ -1859,15 +1854,18 @@ fn table_row(
|
||||
)
|
||||
}));
|
||||
|
||||
block_frame(
|
||||
indented_frame(
|
||||
indent,
|
||||
block_frame(
|
||||
quote,
|
||||
px(0.),
|
||||
theme.root_font_size * BLOCK_GAP,
|
||||
ctx.block_id,
|
||||
cx,
|
||||
)
|
||||
.child(grid)
|
||||
.child(grid),
|
||||
cx,
|
||||
)
|
||||
.into_any_element()
|
||||
}
|
||||
|
||||
|
||||
@@ -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]
|
||||
fn clicking_a_link_opens_its_destination() {
|
||||
let (_cx, mut visual, state) = view_window("[click me](https://example.com/welcome)");
|
||||
|
||||
@@ -1,3 +1,4 @@
|
||||
use std::sync::Arc;
|
||||
use std::time::Duration;
|
||||
|
||||
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::diff_view::{DiffRowKind, DiffViewState};
|
||||
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_layout::dock::{Dock, DockSidebar, DockState, PanelDescriptor, SplitDirection};
|
||||
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 markdown state it renders is notified.
|
||||
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 {
|
||||
view,
|
||||
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
|
||||
/// exercised on realistic content.
|
||||
fn large_markdown(sections: usize) -> String {
|
||||
|
||||
Reference in New Issue
Block a user