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
+61 -1
View File
@@ -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 {