use crate::lex::ast::elements::inlines::{InlineContent, InlineNode, ReferenceInline};
use crate::lex::ast::TextContent;
use lex_extension::wire::{RefKind, WireInline};
pub(crate) fn text_content_to_wire(tc: &TextContent) -> Vec<WireInline> {
if let Some(nodes) = tc.inline_nodes() {
return nodes.iter().map(inline_node_to_wire).collect();
}
let raw = tc.as_string();
if raw.is_empty() {
return Vec::new();
}
vec![WireInline::Text {
text: raw.to_string(),
}]
}
pub(crate) fn inline_nodes_to_wire(nodes: &InlineContent) -> Vec<WireInline> {
nodes.iter().map(inline_node_to_wire).collect()
}
fn inline_node_to_wire(node: &InlineNode) -> WireInline {
match node {
InlineNode::Plain { text, .. } => WireInline::Text { text: text.clone() },
InlineNode::Strong { content, .. } => WireInline::Bold {
children: inline_nodes_to_wire(content),
},
InlineNode::Emphasis { content, .. } => WireInline::Italic {
children: inline_nodes_to_wire(content),
},
InlineNode::Code { text, .. } => WireInline::Code { text: text.clone() },
InlineNode::Math { text, .. } => WireInline::Math { text: text.clone() },
InlineNode::Reference { data, .. } => reference_to_wire(data),
}
}
fn reference_to_wire(data: &ReferenceInline) -> WireInline {
WireInline::Reference {
ref_kind: RefKind::General,
target: data.raw.clone(),
label: None,
}
}
pub(crate) fn text_content_from_wire(inlines: &[WireInline]) -> TextContent {
let mut buf = String::new();
for inline in inlines {
write_inline_source(inline, &mut buf);
}
TextContent::from_string(buf, None)
}
fn write_inline_source(inline: &WireInline, buf: &mut String) {
match inline {
WireInline::Text { text } => buf.push_str(text),
WireInline::Bold { children } => {
buf.push('*');
for c in children {
write_inline_source(c, buf);
}
buf.push('*');
}
WireInline::Italic { children } => {
buf.push('_');
for c in children {
write_inline_source(c, buf);
}
buf.push('_');
}
WireInline::Code { text } => {
buf.push('`');
buf.push_str(text);
buf.push('`');
}
WireInline::Math { text } => {
buf.push('#');
buf.push_str(text);
buf.push('#');
}
WireInline::Reference { target, label, .. } => {
buf.push('[');
buf.push_str(label.as_deref().unwrap_or(target));
buf.push(']');
}
_ => {}
}
}