use std::cell::RefCell;
use std::fmt;
use std::collections::HashSet;
use rushdown::as_kind_data;
use rushdown::ast::{self, Arena, KindData, NodeKind, NodeRef, NodeType, PrettyPrint, pp_indent};
use rushdown::parser::{
self, BlockParser, Context, InlineParser, NoParserOptions, Parser, ParserExtension, State,
};
use rushdown::renderer::html;
use rushdown::renderer::{
self as renderer, BoxRenderNode, NoRendererOptions, NodeRenderer, NodeRendererRegistry,
RenderNode, TextWrite,
};
use rushdown::text::{self, Reader};
use rushdown_emoji::Emoji;
use rushdown_meta::{MetaParserOptions, meta_parser_extension};
use crate::html_render::{html_escape, is_renderable_attribute};
#[derive(Debug)]
pub(crate) struct BlockComponent {
pub(crate) name: String,
pub(crate) props: Option<ast::Meta>,
pub(crate) colons: usize,
pub(crate) open: bool,
}
impl NodeKind for BlockComponent {
fn typ(&self) -> NodeType {
NodeType::ContainerBlock
}
fn kind_name(&self) -> &'static str {
"BlockComponent"
}
}
impl PrettyPrint for BlockComponent {
fn pretty_print(&self, w: &mut dyn fmt::Write, _source: &str, level: usize) -> fmt::Result {
writeln!(w, "{}name: {}", pp_indent(level), self.name)?;
if let Some(ast::Meta::Mapping(map)) = &self.props {
writeln!(w, "{}props: {}", pp_indent(level), map.len())?;
}
Ok(())
}
}
impl From<BlockComponent> for KindData {
fn from(e: BlockComponent) -> Self {
KindData::Extension(Box::new(e))
}
}
#[derive(Debug)]
pub(crate) struct InlineComponent {
pub(crate) name: String,
}
impl NodeKind for InlineComponent {
fn typ(&self) -> NodeType {
NodeType::Inline
}
fn kind_name(&self) -> &'static str {
"InlineComponent"
}
}
impl PrettyPrint for InlineComponent {
fn pretty_print(&self, w: &mut dyn fmt::Write, _source: &str, level: usize) -> fmt::Result {
writeln!(w, "{}name: {}", pp_indent(level), self.name)
}
}
impl From<InlineComponent> for KindData {
fn from(e: InlineComponent) -> Self {
KindData::Extension(Box::new(e))
}
}
#[derive(Debug)]
pub(crate) struct Slot {
pub(crate) name: String,
}
impl NodeKind for Slot {
fn typ(&self) -> NodeType {
NodeType::ContainerBlock
}
fn kind_name(&self) -> &'static str {
"Slot"
}
}
impl PrettyPrint for Slot {
fn pretty_print(&self, w: &mut dyn fmt::Write, _source: &str, level: usize) -> fmt::Result {
writeln!(w, "{}name: {}", pp_indent(level), self.name)
}
}
impl From<Slot> for KindData {
fn from(e: Slot) -> Self {
KindData::Extension(Box::new(e))
}
}
#[derive(Debug)]
pub(crate) struct SpanAttributes;
impl NodeKind for SpanAttributes {
fn typ(&self) -> NodeType {
NodeType::Inline
}
fn kind_name(&self) -> &'static str {
"SpanAttributes"
}
}
impl PrettyPrint for SpanAttributes {
fn pretty_print(&self, _w: &mut dyn fmt::Write, _source: &str, _level: usize) -> fmt::Result {
Ok(())
}
}
impl From<SpanAttributes> for KindData {
fn from(e: SpanAttributes) -> Self {
KindData::Extension(Box::new(e))
}
}
#[derive(Debug)]
struct BlockComponentParser;
fn colon_run_len(trimmed: &str) -> Option<usize> {
if trimmed.len() >= 2 && trimmed.bytes().all(|b| b == b':') {
Some(trimmed.len())
} else {
None
}
}
fn as_block_component(arena: &Arena, node_ref: NodeRef) -> Option<&BlockComponent> {
match arena[node_ref].kind_data() {
KindData::Extension(ext) => {
(ext.as_ref() as &dyn std::any::Any).downcast_ref::<BlockComponent>()
}
_ => None,
}
}
fn has_open_descendant_with_colons(arena: &Arena, node_ref: NodeRef, colons: usize) -> bool {
let mut current = arena[node_ref].last_child();
while let Some(node) = current {
if let Some(component) = as_block_component(arena, node) {
if !component.open {
return false;
}
if component.colons == colons {
return true;
}
}
current = arena[node].last_child();
}
false
}
impl BlockParser for BlockComponentParser {
fn trigger(&self) -> &[u8] {
b":"
}
fn open(
&self,
arena: &mut Arena,
_parent_ref: NodeRef,
reader: &mut text::BasicReader,
_ctx: &mut Context,
) -> Option<(NodeRef, State)> {
let (line_bytes, _seg) = reader.peek_line_bytes()?;
let line = std::str::from_utf8(&line_bytes).ok()?;
let trimmed = line.trim();
let colons = trimmed.bytes().take_while(|&b| b == b':').count();
if colons < 2 {
return None;
}
let rest = trimmed[colons..].trim();
if rest.is_empty() {
return None;
}
let (name, attr_str) = if let Some(brace_start) = rest.find('{') {
if !rest.ends_with('}') {
return None;
}
let name = rest[..brace_start].trim();
let attrs = &rest[brace_start + 1..rest.len() - 1];
(name, Some(attrs))
} else {
(rest, None)
};
if name.is_empty()
|| !name
.chars()
.all(|c| c.is_alphanumeric() || c == '-' || c == '_')
{
return None;
}
let name = name.to_string();
let attr_str = attr_str.map(str::to_string);
reader.advance_line();
let props = consume_block_props(reader).and_then(|body| parse_props_yaml(&body));
let node_ref = arena.new_node(BlockComponent {
name,
props,
colons,
open: true,
});
if let Some(attrs) = attr_str {
parse_component_attributes(&attrs, &mut arena[node_ref]);
}
Some((node_ref, State::HAS_CHILDREN))
}
fn cont(
&self,
arena: &mut Arena,
node_ref: NodeRef,
reader: &mut text::BasicReader,
_ctx: &mut Context,
) -> Option<State> {
let (line_bytes, _seg) = reader.peek_line_bytes()?;
let line = std::str::from_utf8(&line_bytes).ok()?;
let trimmed = line.trim();
if let Some(colons) = colon_run_len(trimmed) {
let matches = as_block_component(arena, node_ref)
.is_some_and(|component| component.colons == colons);
if matches && !has_open_descendant_with_colons(arena, node_ref, colons) {
reader.advance_to_eol();
return None; }
}
Some(State::HAS_CHILDREN)
}
fn close(
&self,
arena: &mut Arena,
node_ref: NodeRef,
_reader: &mut text::BasicReader,
_ctx: &mut Context,
) {
if let Some(node) = arena.get_mut(node_ref)
&& let KindData::Extension(ext) = node.kind_data_mut()
&& let Some(component) =
(ext.as_mut() as &mut dyn std::any::Any).downcast_mut::<BlockComponent>()
{
component.open = false;
}
}
fn can_interrupt_paragraph(&self) -> bool {
true
}
}
pub(crate) fn block_component_parser_extension() -> impl ParserExtension {
parser::ParserExtensionFn::new(|parser: &mut Parser| {
parser.add_block_parser(
|| Box::new(BlockComponentParser) as Box<dyn BlockParser>,
NoParserOptions,
650,
);
})
}
fn build_props_parser() -> Parser {
let extensions = meta_parser_extension(MetaParserOptions::default());
Parser::with_extensions(parser::Options::default(), extensions)
}
thread_local! {
static PROPS_PARSER: RefCell<Parser> = RefCell::new(build_props_parser());
}
fn parse_props_yaml(body: &str) -> Option<ast::Meta> {
let source = format!("---\n{body}\n---\n");
PROPS_PARSER.with(|parser| {
let parser = parser.borrow();
let mut reader = text::BasicReader::new(&source);
let (arena, document_ref) = parser.parse(&mut reader);
let meta = as_kind_data!(arena, document_ref, Document).metadata();
if meta.is_empty() {
None
} else {
Some(ast::Meta::Mapping(meta.clone()))
}
})
}
fn consume_block_props(reader: &mut text::BasicReader) -> Option<String> {
let saved = reader.position();
let (line_bytes, _seg) = reader.peek_line_bytes()?;
let line = std::str::from_utf8(&line_bytes).ok()?;
let trimmed = line.trim();
let closing: ClosingMarker = if trimmed == "---" {
ClosingMarker::Frontmatter
} else if is_yaml_props_fence(trimmed) {
ClosingMarker::Fence
} else {
return None;
};
reader.advance_line();
let mut body = String::new();
loop {
let Some((line_bytes, _seg)) = reader.peek_line_bytes() else {
reader.set_position(saved.0, saved.1);
return None;
};
let Ok(line) = std::str::from_utf8(&line_bytes) else {
reader.set_position(saved.0, saved.1);
return None;
};
let trimmed = line.trim();
if colon_run_len(trimmed).is_some() {
reader.set_position(saved.0, saved.1);
return None;
}
let is_close = match closing {
ClosingMarker::Frontmatter => trimmed == "---",
ClosingMarker::Fence => trimmed == "```",
};
if is_close {
reader.advance_to_eol();
return Some(body);
}
body.push_str(line);
if !line.ends_with('\n') {
body.push('\n');
}
reader.advance_line();
}
}
enum ClosingMarker {
Frontmatter,
Fence,
}
fn is_yaml_props_fence(trimmed: &str) -> bool {
let Some(info) = trimmed.strip_prefix("```") else {
return false;
};
if info.starts_with('`') {
return false;
}
let mut tokens = info.split_whitespace();
matches!(
(tokens.next(), tokens.next(), tokens.next()),
(Some("yaml"), Some("[props]"), None)
)
}
fn slot_marker_name(line: &str) -> Option<&str> {
let trimmed = line.trim();
let name = trimmed.strip_prefix('#')?;
let mut chars = name.chars();
let first = chars.next()?;
if !first.is_ascii_alphabetic() {
return None;
}
if chars.all(|c| c.is_ascii_alphanumeric() || c == '-' || c == '_') {
Some(name)
} else {
None
}
}
fn is_block_component(arena: &Arena, node_ref: NodeRef) -> bool {
as_block_component(arena, node_ref).is_some()
}
#[derive(Debug)]
struct SlotParser;
impl BlockParser for SlotParser {
fn trigger(&self) -> &[u8] {
b"#"
}
fn open(
&self,
arena: &mut Arena,
parent_ref: NodeRef,
reader: &mut text::BasicReader,
_ctx: &mut Context,
) -> Option<(NodeRef, State)> {
if !is_block_component(arena, parent_ref) {
return None;
}
let (line_bytes, _seg) = reader.peek_line_bytes()?;
let line = std::str::from_utf8(&line_bytes).ok()?;
let name = slot_marker_name(line)?;
let node_ref = arena.new_node(Slot {
name: name.to_string(),
});
reader.advance_line();
Some((node_ref, State::HAS_CHILDREN))
}
fn cont(
&self,
arena: &mut Arena,
node_ref: NodeRef,
reader: &mut text::BasicReader,
_ctx: &mut Context,
) -> Option<State> {
let (line_bytes, _seg) = reader.peek_line_bytes()?;
let line = std::str::from_utf8(&line_bytes).ok()?;
let trimmed = line.trim();
if slot_marker_name(line).is_some() {
return None;
}
if let Some(colons) = colon_run_len(trimmed)
&& !has_open_descendant_with_colons(arena, node_ref, colons)
{
return None;
}
Some(State::HAS_CHILDREN)
}
fn can_interrupt_paragraph(&self) -> bool {
true
}
}
pub(crate) fn slot_parser_extension() -> impl ParserExtension {
parser::ParserExtensionFn::new(|parser: &mut Parser| {
parser.add_block_parser(
|| Box::new(SlotParser) as Box<dyn BlockParser>,
NoParserOptions,
550,
);
})
}
#[derive(Debug)]
struct InlineComponentParser;
impl InlineParser for InlineComponentParser {
fn trigger(&self) -> &[u8] {
b":"
}
fn parse(
&self,
arena: &mut Arena,
_parent_ref: NodeRef,
reader: &mut text::BlockReader,
_ctx: &mut Context,
) -> Option<NodeRef> {
let start_pos = reader.position();
if reader.peek_byte() != b':' {
return None;
}
reader.advance(1);
let next = reader.peek_byte();
if next == b':' || next == text::EOS || !is_name_start(next) {
reader.set_position(start_pos.0, start_pos.1);
return None;
}
let name_start = reader.position();
while {
let b = reader.peek_byte();
b != text::EOS && is_name_char(b)
} {
reader.advance(1);
}
let name_end = reader.position();
let name = &reader.source()[name_start.1.start()..name_end.1.start()];
if name.is_empty() {
reader.set_position(start_pos.0, start_pos.1);
return None;
}
let has_bracket = reader.peek_byte() == b'[';
let node_ref = arena.new_node(InlineComponent {
name: name.to_string(),
});
if has_bracket {
reader.advance(1);
let mut depth: usize = 1;
let content_start = reader.position();
loop {
let b = reader.peek_byte();
if b == text::EOS {
reader.set_position(start_pos.0, start_pos.1);
return None;
}
if b == b'[' {
depth += 1;
} else if b == b']' {
depth -= 1;
if depth == 0 {
break;
}
}
reader.advance(1);
}
let content_end = reader.position();
let content = &reader.source()[content_start.1.start()..content_end.1.start()];
if !content.is_empty() {
let text_ref = arena.new_node(ast::Text::new(text::Segment::new(
content_start.1.start(),
content_end.1.start(),
)));
node_ref.append_child(arena, text_ref);
}
reader.advance(1); }
if reader.peek_byte() == b'{' {
reader.advance(1);
let attr_start = reader.position();
let mut brace_depth: usize = 1;
loop {
let b = reader.peek_byte();
if b == text::EOS {
reader.set_position(start_pos.0, start_pos.1);
return None;
}
if b == b'{' {
brace_depth += 1;
} else if b == b'}' {
brace_depth -= 1;
if brace_depth == 0 {
break;
}
}
reader.advance(1);
}
let attr_end = reader.position();
let attr_str = &reader.source()[attr_start.1.start()..attr_end.1.start()];
parse_component_attributes(attr_str, &mut arena[node_ref]);
reader.advance(1); } else if !has_bracket {
reader.set_position(start_pos.0, start_pos.1);
return None;
}
Some(node_ref)
}
}
pub(crate) fn inline_component_parser_extension() -> impl ParserExtension {
parser::ParserExtensionFn::new(|parser: &mut Parser| {
parser.add_inline_parser(
|| Box::new(InlineComponentParser) as Box<dyn InlineParser>,
NoParserOptions,
450,
);
})
}
#[derive(Debug)]
struct SpanAttributeParser;
impl InlineParser for SpanAttributeParser {
fn trigger(&self) -> &[u8] {
b"["
}
fn parse(
&self,
arena: &mut Arena,
_parent_ref: NodeRef,
reader: &mut text::BlockReader,
_ctx: &mut Context,
) -> Option<NodeRef> {
let start_pos = reader.position();
if reader.peek_byte() != b'[' {
return None;
}
reader.advance(1);
let mut depth: usize = 1;
let content_start = reader.position();
loop {
let b = reader.peek_byte();
if b == text::EOS {
reader.set_position(start_pos.0, start_pos.1);
return None;
}
if b == b'[' {
depth += 1;
} else if b == b']' {
depth -= 1;
if depth == 0 {
break;
}
}
reader.advance(1);
}
let content_end = reader.position();
let content = &reader.source()[content_start.1.start()..content_end.1.start()];
reader.advance(1);
if reader.peek_byte() != b'{' {
reader.set_position(start_pos.0, start_pos.1);
return None;
}
reader.advance(1);
let attr_start = reader.position();
let mut brace_depth: usize = 1;
loop {
let b = reader.peek_byte();
if b == text::EOS {
reader.set_position(start_pos.0, start_pos.1);
return None;
}
if b == b'{' {
brace_depth += 1;
} else if b == b'}' {
brace_depth -= 1;
if brace_depth == 0 {
break;
}
}
reader.advance(1);
}
let attr_end = reader.position();
let attr_str = &reader.source()[attr_start.1.start()..attr_end.1.start()];
if attr_str.trim().is_empty() {
reader.set_position(start_pos.0, start_pos.1);
return None;
}
let node_ref = arena.new_node(SpanAttributes);
if !content.is_empty() {
let text_ref = arena.new_node(ast::Text::new(text::Segment::new(
content_start.1.start(),
content_end.1.start(),
)));
node_ref.append_child(arena, text_ref);
}
parse_component_attributes(attr_str, &mut arena[node_ref]);
reader.advance(1);
Some(node_ref)
}
}
pub(crate) fn span_attribute_parser_extension() -> impl ParserExtension {
parser::ParserExtensionFn::new(|parser: &mut Parser| {
parser.add_inline_parser(
|| Box::new(SpanAttributeParser) as Box<dyn InlineParser>,
NoParserOptions,
150,
);
})
}
pub(crate) fn parse_component_attributes(attr_str: &str, node: &mut ast::Node) {
let mut classes = Vec::new();
let input = attr_str.trim();
let bytes = input.as_bytes();
let mut i = 0;
while i < bytes.len() {
if bytes[i].is_ascii_whitespace() {
i += 1;
continue;
}
if bytes[i] == b'.' {
i += 1;
let start = i;
while i < bytes.len()
&& !bytes[i].is_ascii_whitespace()
&& bytes[i] != b'.'
&& bytes[i] != b'#'
&& bytes[i] != b'}'
{
i += 1;
}
if i > start {
classes.push(input[start..i].to_string());
}
} else if bytes[i] == b'#' {
i += 1;
let start = i;
while i < bytes.len()
&& !bytes[i].is_ascii_whitespace()
&& bytes[i] != b'.'
&& bytes[i] != b'#'
&& bytes[i] != b'}'
{
i += 1;
}
if i > start {
node.attributes_mut().insert(
"id",
text::MultilineValue::from(input[start..i].to_string()),
);
}
} else {
let key_start = i;
while i < bytes.len()
&& bytes[i] != b'='
&& !bytes[i].is_ascii_whitespace()
&& bytes[i] != b'}'
{
i += 1;
}
let key = &input[key_start..i];
if key.is_empty() {
i += 1;
continue;
}
if i < bytes.len() && bytes[i] == b'=' {
i += 1; let value = if i < bytes.len() && (bytes[i] == b'"' || bytes[i] == b'\'') {
let quote = bytes[i];
i += 1;
let val_start = i;
while i < bytes.len() && bytes[i] != quote {
i += 1;
}
let val = &input[val_start..i];
if i < bytes.len() {
i += 1; }
val
} else {
let val_start = i;
while i < bytes.len() && !bytes[i].is_ascii_whitespace() && bytes[i] != b'}' {
i += 1;
}
&input[val_start..i]
};
node.attributes_mut()
.insert(key, text::MultilineValue::from(value.to_string()));
} else {
let key = format!(":{key}");
node.attributes_mut()
.insert(key, text::MultilineValue::from("true".to_string()));
}
}
}
if !classes.is_empty() {
node.attributes_mut()
.insert("class", text::MultilineValue::from(classes.join(" ")));
}
}
fn is_name_start(b: u8) -> bool {
b.is_ascii_alphabetic() || b == b'_'
}
fn is_name_char(b: u8) -> bool {
b.is_ascii_alphanumeric() || b == b'-' || b == b'_'
}
pub(crate) fn assign_heading_anchors(arena: &mut Arena, root: NodeRef, source: &str) {
let mut used: HashSet<String> = HashSet::new();
let mut headings: Vec<NodeRef> = Vec::new();
collect_headings(arena, root, &mut headings);
for &heading_ref in &headings {
if let Some(id) = arena[heading_ref]
.attributes()
.get("id")
.map(|v| v.str(source).to_string())
{
used.insert(id);
}
}
for &heading_ref in &headings {
if arena[heading_ref].attributes().get("id").is_some() {
continue;
}
let text = heading_text(arena, heading_ref, source);
let slug = crate::slug::slugify_unique(&text, &mut used);
arena[heading_ref]
.attributes_mut()
.insert("id", text::MultilineValue::from(slug));
}
}
pub(crate) fn collect_headings(arena: &Arena, node_ref: NodeRef, out: &mut Vec<NodeRef>) {
if matches!(arena[node_ref].kind_data(), KindData::Heading(_)) {
out.push(node_ref);
}
let mut child = arena[node_ref].first_child();
while let Some(child_ref) = child {
collect_headings(arena, child_ref, out);
child = arena[child_ref].next_sibling();
}
}
pub(crate) fn heading_text(arena: &Arena, node_ref: NodeRef, source: &str) -> String {
let mut out = String::new();
collect_heading_text(arena, node_ref, source, &mut out);
out
}
fn collect_heading_text(arena: &Arena, node_ref: NodeRef, source: &str, out: &mut String) {
match arena[node_ref].kind_data() {
KindData::Text(t) => out.push_str(t.str(source)),
KindData::RawHtml(h) => out.push_str(&h.str(source)),
KindData::Extension(ext) => {
if let Some(emoji) = (ext.as_ref() as &dyn std::any::Any).downcast_ref::<Emoji>()
&& let Some(sc) = emoji.shortcode()
{
out.push_str(sc);
}
}
_ => {}
}
let mut child = arena[node_ref].first_child();
while let Some(child_ref) = child {
collect_heading_text(arena, child_ref, source, out);
child = arena[child_ref].next_sibling();
}
}
pub(crate) fn is_more_marker(arena: &Arena, node_ref: NodeRef, source: &str) -> bool {
let raw = match arena[node_ref].kind_data() {
KindData::HtmlBlock(block) => {
let mut text = String::new();
for line in block.value().iter(source) {
text.push_str(&line);
}
text
}
KindData::RawHtml(html) => html.str(source).to_string(),
_ => return false,
};
is_more_comment(&raw)
}
fn is_more_comment(raw: &str) -> bool {
let trimmed = raw.trim();
let Some(inner) = trimmed
.strip_prefix("<!--")
.and_then(|s| s.strip_suffix("-->"))
else {
return false;
};
inner.trim().eq_ignore_ascii_case("more")
}
fn write_component_attributes<W: TextWrite>(
writer: &mut W,
source: &str,
node: &ast::Node,
) -> rushdown::Result<()> {
let mut attrs: Vec<(String, String)> = node
.attributes()
.iter()
.filter(|(key, _)| is_renderable_attribute(key))
.map(|(key, value)| (key.to_string(), value.str(source).to_string()))
.collect();
attrs.sort_unstable_by(|a, b| a.0.cmp(&b.0));
for (key, value) in &attrs {
writer.write_str(" ")?;
writer.write_str(key)?;
writer.write_str("=\"")?;
writer.write_str(&html_escape(value))?;
writer.write_str("\"")?;
}
Ok(())
}
#[derive(Debug)]
struct BlockComponentHtmlRenderer;
impl<W: TextWrite> RenderNode<W> for BlockComponentHtmlRenderer {
fn render_node<'a>(
&self,
writer: &mut W,
source: &'a str,
arena: &'a Arena,
node_ref: NodeRef,
entering: bool,
_context: &mut renderer::Context,
) -> rushdown::Result<ast::WalkStatus> {
let node = &arena[node_ref];
if entering {
writer.write_str("<div")?;
write_component_attributes(writer, source, node)?;
writer.write_str(">\n")?;
} else {
writer.write_str("</div>\n")?;
}
Ok(ast::WalkStatus::Continue)
}
}
impl<'r, W: TextWrite> NodeRenderer<'r, W> for BlockComponentHtmlRenderer {
fn register_node_renderer_fn(self, nrr: &mut impl NodeRendererRegistry<'r, W>) {
nrr.register_node_renderer_fn(
std::any::TypeId::of::<BlockComponent>(),
BoxRenderNode::new(self),
);
}
}
pub(crate) fn block_component_html_renderer_extension()
-> impl html::RendererExtension<'static, String> {
html::RendererExtensionFn::new(|renderer: &mut html::Renderer<'_, String>| {
renderer.add_node_renderer(|| BlockComponentHtmlRenderer, NoRendererOptions);
})
}
#[derive(Debug)]
struct SlotHtmlRenderer;
impl<W: TextWrite> RenderNode<W> for SlotHtmlRenderer {
fn render_node<'a>(
&self,
writer: &mut W,
_source: &'a str,
arena: &'a Arena,
node_ref: NodeRef,
entering: bool,
_context: &mut renderer::Context,
) -> rushdown::Result<ast::WalkStatus> {
if entering {
let name = match arena[node_ref].kind_data() {
KindData::Extension(ext) => (ext.as_ref() as &dyn std::any::Any)
.downcast_ref::<Slot>()
.map(|slot| slot.name.as_str())
.unwrap_or_default(),
_ => "",
};
writer.write_str("<div data-slot=\"")?;
writer.write_str(&html_escape(name))?;
writer.write_str("\">\n")?;
} else {
writer.write_str("</div>\n")?;
}
Ok(ast::WalkStatus::Continue)
}
}
impl<'r, W: TextWrite> NodeRenderer<'r, W> for SlotHtmlRenderer {
fn register_node_renderer_fn(self, nrr: &mut impl NodeRendererRegistry<'r, W>) {
nrr.register_node_renderer_fn(std::any::TypeId::of::<Slot>(), BoxRenderNode::new(self));
}
}
pub(crate) fn slot_html_renderer_extension() -> impl html::RendererExtension<'static, String> {
html::RendererExtensionFn::new(|renderer: &mut html::Renderer<'_, String>| {
renderer.add_node_renderer(|| SlotHtmlRenderer, NoRendererOptions);
})
}
#[derive(Debug)]
struct InlineComponentHtmlRenderer;
impl<W: TextWrite> RenderNode<W> for InlineComponentHtmlRenderer {
fn render_node<'a>(
&self,
writer: &mut W,
source: &'a str,
arena: &'a Arena,
node_ref: NodeRef,
entering: bool,
_context: &mut renderer::Context,
) -> rushdown::Result<ast::WalkStatus> {
let node = &arena[node_ref];
if entering {
writer.write_str("<span")?;
write_component_attributes(writer, source, node)?;
writer.write_str(">")?;
} else {
writer.write_str("</span>")?;
}
Ok(ast::WalkStatus::Continue)
}
}
impl<'r, W: TextWrite> NodeRenderer<'r, W> for InlineComponentHtmlRenderer {
fn register_node_renderer_fn(self, nrr: &mut impl NodeRendererRegistry<'r, W>) {
nrr.register_node_renderer_fn(
std::any::TypeId::of::<InlineComponent>(),
BoxRenderNode::new(self),
);
}
}
pub(crate) fn inline_component_html_renderer_extension()
-> impl html::RendererExtension<'static, String> {
html::RendererExtensionFn::new(|renderer: &mut html::Renderer<'_, String>| {
renderer.add_node_renderer(|| InlineComponentHtmlRenderer, NoRendererOptions);
})
}
#[derive(Debug)]
struct SpanAttributeHtmlRenderer;
impl<W: TextWrite> RenderNode<W> for SpanAttributeHtmlRenderer {
fn render_node<'a>(
&self,
writer: &mut W,
source: &'a str,
arena: &'a Arena,
node_ref: NodeRef,
entering: bool,
_context: &mut renderer::Context,
) -> rushdown::Result<ast::WalkStatus> {
let node = &arena[node_ref];
if entering {
writer.write_str("<span")?;
write_component_attributes(writer, source, node)?;
writer.write_str(">")?;
} else {
writer.write_str("</span>")?;
}
Ok(ast::WalkStatus::Continue)
}
}
impl<'r, W: TextWrite> NodeRenderer<'r, W> for SpanAttributeHtmlRenderer {
fn register_node_renderer_fn(self, nrr: &mut impl NodeRendererRegistry<'r, W>) {
nrr.register_node_renderer_fn(
std::any::TypeId::of::<SpanAttributes>(),
BoxRenderNode::new(self),
);
}
}
pub(crate) fn span_attribute_html_renderer_extension()
-> impl html::RendererExtension<'static, String> {
html::RendererExtensionFn::new(|renderer: &mut html::Renderer<'_, String>| {
renderer.add_node_renderer(|| SpanAttributeHtmlRenderer, NoRendererOptions);
})
}