use crate::converter::walk::{CaptureEnd, Child, ChildHook, Close, HookSite, Open};
use std::rc::Rc;
type Context = crate::converter::Context;
pub fn open(
node_handle: &crate::dom::NodeHandle,
parser: &crate::dom::Parser,
output: &str,
context: &Context,
children: &mut Vec<crate::dom::NodeHandle>,
) -> Option<Open> {
let Some(crate::dom::Node::Tag(tag)) = node_handle.get(parser) else {
return None;
};
let tag_sequence = ruby_tag_sequence(tag, parser);
let has_rtc = tag_sequence.iter().any(|tag| tag == "rtc");
let interleaved = !has_rtc && tag_sequence.windows(2).any(|tags| tags[0] == "rb" && tags[1] == "rt");
let mut parts = Vec::new();
for child_handle in tag.children().top() {
let part = match child_handle.get(parser) {
Some(crate::dom::Node::Tag(child_tag)) => {
match crate::converter::normalized_tag_name(child_tag.name().as_utf8_str()).as_ref() {
"rt" => RubyPart::Annotation,
"rp" => continue,
"rb" if interleaved => RubyPart::NextBase,
"rtc" if !interleaved => RubyPart::Container,
_ => RubyPart::Base,
}
}
Some(crate::dom::Node::Raw(_)) => RubyPart::Base,
_ => continue,
};
children.push(*child_handle);
parts.push(part);
}
Some(Open {
scope: None,
close: Close::Hooked(Box::new(RubyHook {
scope: Rc::new(context.inline_buffer(output, false)),
parts,
interleaved,
has_rtc,
grouped: GroupedRuby::default(),
})),
})
}
#[derive(Clone, Copy)]
enum RubyPart {
Base,
NextBase,
Annotation,
Container,
}
struct RubyHook {
scope: Rc<Context>,
parts: Vec<RubyPart>,
interleaved: bool,
has_rtc: bool,
grouped: GroupedRuby,
}
impl ChildHook for RubyHook {
fn before_child(&mut self, index: usize, element: &mut HookSite<'_>) -> Child {
let buffer = match self.parts[index] {
RubyPart::Annotation => String::new(),
RubyPart::NextBase => {
flush_base(&mut self.grouped.base_text, element.output);
std::mem::take(&mut self.grouped.base_text)
}
RubyPart::Base => std::mem::take(&mut self.grouped.base_text),
RubyPart::Container => std::mem::take(&mut self.grouped.rtc_content),
};
Child::Walk {
depth: None,
buffer: Some(buffer),
scope: Some(Rc::clone(&self.scope)),
}
}
fn after_child(&mut self, index: usize, own: Option<String>, element: &mut HookSite<'_>) {
let text = own.unwrap_or_default();
match self.parts[index] {
RubyPart::Annotation if self.interleaved => {
flush_base(&mut self.grouped.base_text, element.output);
element.output.push_str(text.trim());
}
RubyPart::Annotation => self.grouped.annotations.push(text),
RubyPart::NextBase | RubyPart::Base => self.grouped.base_text = text,
RubyPart::Container => self.grouped.rtc_content = text,
}
}
fn close(mut self: Box<Self>, element: &mut HookSite<'_>) {
if self.interleaved {
flush_base(&mut self.grouped.base_text, element.output);
} else {
emit_grouped(&self.grouped, self.has_rtc, element.output);
}
}
}
pub fn open_part(
tag_name: &str,
node_handle: &crate::dom::NodeHandle,
parser: &crate::dom::Parser,
output: &str,
context: &Context,
children: &mut Vec<crate::dom::NodeHandle>,
) -> Option<Open> {
let Some(crate::dom::Node::Tag(tag)) = node_handle.get(parser) else {
return None;
};
children.extend(tag.children().top().iter().copied());
let (opens_with_marker, end) = match tag_name {
"rb" | "rp" => (false, CaptureEnd::RubyText),
"rt" => (true, CaptureEnd::RubyAnnotation),
_ => return Some(Open::children_only()),
};
Some(Open {
scope: Some(Rc::new(context.inline_buffer(output, opens_with_marker))),
close: Close::Capture(end),
})
}
pub fn close_text(text: &str, output: &mut String) {
output.push_str(text.trim());
}
pub fn close_annotation(text: &str, output: &mut String) {
let trimmed = text.trim();
if output.ends_with('(') {
output.push_str(trimmed);
} else {
output.push('(');
output.push_str(trimmed);
output.push(')');
}
}
fn ruby_tag_sequence(tag: &crate::dom::HTMLTag<'_>, parser: &crate::dom::Parser<'_>) -> Vec<String> {
tag.children()
.top()
.iter()
.filter_map(|child_handle| {
let crate::dom::Node::Tag(child_tag) = child_handle.get(parser)? else {
return None;
};
let tag_name = crate::converter::normalized_tag_name(child_tag.name().as_utf8_str());
matches!(tag_name.as_ref(), "rb" | "rt" | "rtc").then(|| tag_name.into_owned())
})
.collect()
}
fn flush_base(current_base: &mut String, output: &mut String) {
if !current_base.is_empty() {
output.push_str(current_base.trim());
current_base.clear();
}
}
#[derive(Default)]
struct GroupedRuby {
base_text: String,
annotations: Vec<String>,
rtc_content: String,
}
fn emit_grouped(grouped: &GroupedRuby, has_rtc: bool, output: &mut String) {
output.push_str(grouped.base_text.trim());
let annotation = grouped.annotations.iter().map(|value| value.trim()).collect::<String>();
if !annotation.is_empty() {
if has_rtc && !grouped.rtc_content.trim().is_empty() && grouped.annotations.len() > 1 {
output.push('(');
output.push_str(&annotation);
output.push(')');
} else {
output.push_str(&annotation);
}
}
if !grouped.rtc_content.trim().is_empty() {
output.push_str(grouped.rtc_content.trim());
}
}