Skip to content
Open
Show file tree
Hide file tree
Changes from 2 commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
24 changes: 24 additions & 0 deletions crates/base/src/text/format/html.rs
Original file line number Diff line number Diff line change
Expand Up @@ -468,6 +468,30 @@ fn parse_node(
paragraph: &mut HtmlParagraph,
cx: &mut NodeContext,
) -> Option<BlockNode> {
// Custom HTML block parsers get first claim on every element, before the
// built-in tag handling; the first Some() wins and the element never
// reaches the local_name match below. Inline-only elements folded into
// paragraphs by parse_paragraph do not pass through here.
if let NodeData::Element { .. } = node.data {
if let Some(custom) = cx.markdown_extensions.parse_html_block(node) {
let mut children = vec![];
consume_paragraph(&mut children, paragraph);
let custom = BlockNode::Custom {
node: custom,
state: node::BlockState::default(),
};
return if children.is_empty() {
Some(custom)
} else {
children.push(custom);
Some(BlockNode::Root {
children,
span: None,
})
};
}
}

match node.data {
NodeData::Text { ref contents } => {
let text = contents.borrow().to_string();
Expand Down
41 changes: 41 additions & 0 deletions crates/base/src/text/markdown_ext.rs
Original file line number Diff line number Diff line change
Expand Up @@ -32,6 +32,15 @@ pub type MarkdownBlockParserFn =
pub type MarkdownBlockRenderFn =
dyn Fn(&MarkdownNode, &mut Window, &mut App) -> AnyElement + Send + Sync;

/// Type for a custom HTML block parser.
///
/// Parsers run on the parsed DOM during HTML conversion, on the same thread as
/// [`super::format::html`]. They must not depend on [`Window`] or [`App`];
/// return parsed, reusable data in a [`MarkdownNode`] and render it later with
/// a block renderer registered under the same name.
pub type HtmlBlockParserFn =
dyn Fn(&markup5ever_rcdom::Node) -> Option<MarkdownNode> + Send + Sync;

/// Builds the container of a [block surface](MarkdownExtensions::block_surface).
pub type BlockSurfaceRenderFn = dyn Fn(&mut Window, &mut App) -> Div + Send + Sync;

Expand Down Expand Up @@ -255,6 +264,7 @@ pub struct MarkdownExtensions {
inline_parsers: Vec<Arc<MarkdownInlineParserFn>>,
inline_renderers: HashMap<SharedString, Arc<MarkdownInlineRenderFn>>,
block_surfaces: HashMap<SharedString, Arc<BlockSurfaceRenderFn>>,
html_block_parsers: Vec<Arc<HtmlBlockParserFn>>,
revision: u64,
parser_revision: u64,
}
Expand Down Expand Up @@ -457,6 +467,37 @@ impl MarkdownExtensions {
self.bump_revision();
}

/// Register a custom HTML block parser.
///
/// During HTML parsing the parser sees every element node before the
/// built-in tag handling; returning a [`MarkdownNode`] claims the element
/// as a custom block, rendered later with a block renderer registered
/// under the same name (see [`Self::block_renderer`]). Returning `None`
/// leaves the element to the built-in handling.
pub fn push_html_block_parser<F>(&mut self, parser: F)
where
F: Fn(&markup5ever_rcdom::Node) -> Option<MarkdownNode> + Send + Sync + 'static,
{
self.html_block_parsers.push(Arc::new(parser));
self.bump_revision();
}

/// Whether the HTML block parsers match, so an HTML document need not be
/// reparsed when render handles are refreshed.
///
/// Length-only, mirroring the Markdown block-parser shape check: render
/// methods commonly rebuild equivalent parser closures every frame, and
/// fresh `Arc`s must not read as a configuration change.
pub(crate) fn has_same_html_block_parsers(&self, other: &Self) -> bool {
self.html_block_parsers.len() == other.html_block_parsers.len()
}

/// Offer an element to the custom HTML block parsers; the first
/// `Some` claims it.
pub(crate) fn parse_html_block(&self, node: &markup5ever_rcdom::Node) -> Option<MarkdownNode> {
self.html_block_parsers.iter().find_map(|p| p(node))
}

pub(crate) fn push_block_renderer<F, E>(&mut self, name: impl Into<SharedString>, renderer: F)
where
F: Fn(&MarkdownNode, &mut Window, &mut App) -> E + Send + Sync + 'static,
Expand Down
33 changes: 31 additions & 2 deletions crates/base/src/text/state.rs
Original file line number Diff line number Diff line change
Expand Up @@ -194,8 +194,31 @@ impl TextViewState {
Self::new(TextViewFormat::Html, text, cx)
}

/// Create a HTML TextViewState with extensions registered before the
/// initial parse — custom HTML block parsers claim their elements on the
/// first parse, with no element-driven re-parse afterwards.
pub fn html_with_extensions(
text: &str,
markdown_extensions: Arc<MarkdownExtensions>,
cx: &mut Context<Self>,
) -> Self {
Self::new_with_extensions(TextViewFormat::Html, text, Some(markdown_extensions), cx)
}

/// Create a new TextViewState.
fn new(format: TextViewFormat, text: &str, cx: &mut Context<Self>) -> Self {
Self::new_with_extensions(format, text, None, cx)
}

/// [`Self::new`] with extensions registered before the initial parse, so
/// custom HTML block parsers apply to the first parse instead of forcing
/// a re-parse once the element registers them.
fn new_with_extensions(
format: TextViewFormat,
text: &str,
markdown_extensions: Option<Arc<MarkdownExtensions>>,
cx: &mut Context<Self>,
) -> Self {
let focus_handle = cx.focus_handle();
let selection_adapter = TextViewSelectionAdapter::new(cx.entity().downgrade(), cx);

Expand Down Expand Up @@ -255,7 +278,7 @@ impl TextViewState {
link_tooltip_target: None,
task_toggle_handler: None,
image_source: None,
markdown_extensions: Arc::default(),
markdown_extensions: markdown_extensions.unwrap_or_default(),
is_selecting: false,
preserve_inline_selection: false,
auto_scroll: AutoScroll::default(),
Expand Down Expand Up @@ -415,8 +438,14 @@ impl TextViewState {
let parser_configuration_changed = !self
.markdown_extensions
.has_same_parser_configuration(&markdown_extensions);
let html_block_parsers_changed = self.format == TextViewFormat::Html
&& !self
.markdown_extensions
.has_same_html_block_parsers(&markdown_extensions);
self.markdown_extensions = markdown_extensions;
if parser_configuration_changed && self.format == TextViewFormat::Markdown {
if (parser_configuration_changed && self.format == TextViewFormat::Markdown)
|| html_block_parsers_changed
{
let text = self.text.clone();
self.increment_update(&text, false, cx);
}
Expand Down
98 changes: 98 additions & 0 deletions crates/base/src/text/text_view.rs
Original file line number Diff line number Diff line change
Expand Up @@ -680,6 +680,37 @@ impl TextView {
self
}

/// Register a custom block-level HTML parser.
///
/// The parser sees every element of the parsed DOM before the built-in
/// tag handling and must be independent of [`Window`] / [`App`]. Store
/// any parsed data in a [`MarkdownNode`] and render it later with
/// [`Self::html_block_renderer`]. Returning `None` leaves the element to
/// the built-in handling.
pub fn html_block_parser<F>(mut self, parser: F) -> Self
where
F: Fn(&markup5ever_rcdom::Node) -> Option<MarkdownNode> + Send + Sync + 'static,
{
Arc::make_mut(&mut self.markdown_extensions).push_html_block_parser(parser);
self
}

/// Register a renderer for a custom block-level HTML node name.
///
/// Custom HTML blocks share the name-keyed renderer registry with custom
/// Markdown blocks; registering the same name replaces the prior entry.
pub fn html_block_renderer<F, E>(
self,
name: impl Into<SharedString>,
renderer: F,
) -> Self
where
F: Fn(&MarkdownNode, &mut Window, &mut App) -> E + Send + Sync + 'static,
E: IntoElement,
{
self.markdown_block_renderer(name, renderer)
}

/// Apply a reusable text view plugin.
pub fn plugin<P>(self, plugin: P) -> Self
where
Expand Down Expand Up @@ -2898,6 +2929,73 @@ mod tests {
assert!(view.selectable);
}

#[gpui::test]
fn html_block_parser_claims_elements_before_builtin_handling(cx: &mut TestAppContext) {
use crate::MarkdownNode;
cx.update(crate::init);
let renders = Arc::new(AtomicUsize::new(0));
struct HtmlBlockRoot {
view: Entity<TextViewState>,
renders: Arc<AtomicUsize>,
}
impl Render for HtmlBlockRoot {
fn render(&mut self, _window: &mut Window, _cx: &mut Context<Self>) -> impl IntoElement {
let renders = self.renders.clone();
div()
.w(px(300.))
.h(px(400.))
.text_size(px(16.))
.child(crate::TextSelectionLayer)
.child(
TextView::new(&self.view).html_block_parser(|node| {
let markup5ever_rcdom::NodeData::Element { ref name, ref attrs, .. } =
node.data
else {
return None;
};
let claimed = &*name.local == "div"
&& attrs
.borrow()
.iter()
.any(|attr| &*attr.name.local == "data-mb");
claimed.then(|| {
MarkdownNode::new("mail-block", 7usize).text("claimed text")
})
})
.html_block_renderer("mail-block", move |node: &MarkdownNode, _w, _c| {
assert_eq!(node.data::<usize>(), Some(&7));
renders.fetch_add(1, Ordering::Relaxed);
div()
.debug_selector(|| "html-block-marker".into())
.w(px(40.))
.h(px(20.))
}),
)
}
}
let (_root, cx) = cx.add_window_view(|_, cx| HtmlBlockRoot {
view: cx.new(|cx| {
TextViewState::html("<p>leading</p><div data-mb=\"7\"></div>", cx)
}),
renders: renders.clone(),
});
cx.run_until_parked();
// First draw registers the extensions on the state and schedules the
// re-parse; the second draws the reparsed document.
cx.update(|window, cx| window.draw(cx).clear(cx));
cx.run_until_parked();
cx.update(|window, cx| window.draw(cx).clear(cx));

let marker = cx
.debug_bounds("html-block-marker")
.expect("custom html block should render");
assert!(marker.size.height > px(0.));
assert!(
renders.load(Ordering::Relaxed) > 0,
"custom html block renderer should have run"
);
}

#[test]
fn syntax_highlighting_is_opt_in() {
let default_view = TextView::markdown("default-code", "```rust\nfn main() {}\n```");
Expand Down
Loading