Repository navigation
Refactor walk_children() - #62
Conversation
WalkthroughThis PR removes Changes
Sequence Diagram(s)sequenceDiagram
participant Handler as Element Handler
participant Chain as Chain / ElementHandlers
participant Walker as dom_walker
Note over Handler,Chain: Handler requests content resolution
Handler->>Chain: handle(..., element.node, markdown_translated?)
Chain->>Walker: walk_children(element.node)
alt iterate children
Walker->>Handler: call handler for child nodes
Handler-->>Walker: HandlerResult (content, markdown_translated)
end
Walker->>Walker: merge adjacent text blocks (can_combine)
Walker->>Walker: normalize_content_for_buffer(last, new, is_pre)
Walker-->>Chain: HandlerResult { content, markdown_translated }
Chain-->>Handler: HandlerResult returned
Estimated code review effort🎯 4 (Complex) | ⏱️ ~60 minutes
Possibly related PRs
Poem
Pre-merge checks and finishing touches❌ Failed checks (1 warning)
✅ Passed checks (2 passed)
✨ Finishing touches
🧪 Generate unit tests (beta)
📜 Recent review detailsConfiguration used: CodeRabbit UI Review profile: CHILL Plan: Pro 📒 Files selected for processing (4)
🧰 Additional context used🧬 Code graph analysis (2)src/element_handler/anchor.rs (1)
src/element_handler/list.rs (2)
🔇 Additional comments (10)
Comment |
There was a problem hiding this comment.
Actionable comments posted: 0
Caution
Some comments are outside the diff and can’t be posted inline due to platform limitations.
⚠️ Outside diff range comments (1)
src/element_handler/table.rs (1)
19-178: Faithful-mode table translation ignores caption translation statusYou correctly track
markdown_translatedfor header/body cells viaextract_row_cells, butall_children_translatedis never updated from the"caption"branch. In Faithful mode, that means a table with a caption that falls back to HTML can still be emitted as a Markdown table, which conflicts with the comment that all child table elements must be translated before emitting Markdown.You can fix this by incorporating captions into
all_children_translated:@@ pub(crate) fn table_handler(chain: &dyn Chain, element: Element) -> Option<HandlerResult> { - match tag_name { - "caption" => { - if let Some(res) = chain.handle(&child) { - captions.push(res.content.trim().to_string()); - } - } + match tag_name { + "caption" => { + if let Some(res) = chain.handle(&child) { + all_children_translated &= res.markdown_translated; + captions.push(res.content.trim().to_string()); + } + } @@ fn extract_row_cells( - let mut cells = Vec::new(); - let mut all_translated = true; + let mut cells = Vec::new(); + let mut all_translated = true; @@ - let Some(res) = chain.handle(&cell_node) else { + let Some(res) = chain.handle(&cell_node) else { continue; }; - if !res.markdown_translated { - all_translated = false; - } + if !res.markdown_translated { + all_translated = false; + }(Only the caption branch change is functionally necessary; the extract_row_cells hunk is shown here just for context.)
This keeps Faithful-mode behavior consistent: any non-translated caption will correctly force the whole table back to HTML.
Also applies to: 181-205
🧹 Nitpick comments (5)
src/dom_walker.rs (2)
105-158: Adjacent inline-element merge logic is correct but could use clearer invariants / panic messagingThe new
walk_childrenimplementation that:
- merges adjacent inline elements via
can_combine, and- trims trailing spaces before block children and leading spaces after a block
is logically sound:
indexstarts at 1 and only decrements inside the branch wherecan_combinehas already succeeded, soindex -= 1cannot underflow.- After
children.remove(index),index - 1still refers to the original first node, and thecan_combineconstraints ensure it has a single text child, so the subsequent.first().unwrap()/NodeData::Text { .. }pattern match is safe under current invariants.Two small improvements would make this more robust and maintainable:
More descriptive panic – the
panic!("")in thelet NodeData::Text { .. } = text_data elsearm gives no context if the invariant is ever broken by future refactors. Consider usingunreachable!(or at least a message) that names the expectation, e.g."can_combine invariant violated: expected first child to be Text".Document the mutation behavior – a brief comment that
walk_childrenmutatesnode.childrenby removing merged siblings and folding text into the first node would help future readers understand that the DOM is being normalized in-place before traversal.These are non-blocking polish items, but worth considering.
222-255: normalize_content_for_buffer logic is sound; watch for edge cases with<pre>and paragraph breaksThe normalization does two things:
- Collapses runs of newlines across a buffer boundary to at most two total, by trimming only from the start of
content.- When not in
precontext and with no newlines at either side, collapses double spaces across buffer entries (last item ends with' ', new content starts with' ').Both behaviors seem correct and efficient enough for typical content sizes. A few nuances to keep in mind:
- Newline collapsing is independent of
is_pre. If anypre/code-block content ever flows through this function, its leading newlines could be trimmed. From this file it looks like raw text in<pre>is handled via theis_prebranch inNodeData::Text, but it’s worth double‑checking that handler-generated content for code/pre never hitsnormalize_content_for_bufferin a way that matters.- For paragraphs, this changes how multiple blocks of content are stitched together around blank lines. Please verify behavior for cases like consecutive
<p>s and headings with trailing/leading newlines to confirm that exactly two newlines are preserved where markdown expects paragraph separation.If tests already cover these, no changes required; otherwise, adding focused tests around “more than two blank lines between blocks” would lock in this behavior.
src/element_handler/p.rs (1)
8-12: Chain-based content for paragraphs looks right; check empty<p>and<br>edge casesSwitching to:
serialize_if_faithful!(chain, element, 0);let content = chain.walk_children(element.node);let content = content.trim_matches('\n');- and wrapping with
"\n\n{content}\n\n"fits the new Chain model and keeps paragraph separation explicit.
Two behavior points worth double-checking against tests:
- Empty or whitespace-only
<p>–walk_childrenmay return an empty string, in which case this will still emit"\n\n\n\n". If the previous implementation suppressed some empty paragraphs, confirm this matches intended behavior.- Paragraphs with
<br>– since<br>currently renders as" \n"or"\\\n", trimming leading/trailing'\n'only affects newlines at the very beginning or end of the paragraph content. Please verify that sequences like<p>a<br>b</p>and<p>a<br/></p>still render as desired (line breaks inside the paragraph vs. extra blank lines after it).If existing tests cover these, no change needed; otherwise, a couple of focused cases would be helpful.
src/element_handler/code.rs (1)
45-83: Optional: avoid shadowingcontentwith a different type inhandle_code_blockThe current pattern creates a
Stringand then shadows it with a&str, which is slightly harder to follow. You could keep a singleStringbinding and strip the trailing newline in place for clarity:- let content = chain.walk_children(element.node); - let content = content.strip_suffix('\n').unwrap_or(&content); + let mut content = chain.walk_children(element.node); + if content.ends_with('\n') { + content.pop(); + } + if element.options.code_block_style == CodeBlockStyle::Fenced { let fence = if element.options.code_block_fence == CodeBlockFence::Tildes { - get_code_fence_marker("~", content) + get_code_fence_marker("~", &content) } else { - get_code_fence_marker("`", content) + get_code_fence_marker("`", &content) }; @@ - result.push_str(content); + result.push_str(&content); @@ - let code = content + let code = content .lines()Behavior stays the same while making the lifetime story more obvious.
src/element_handler/mod.rs (1)
273-289: Consider propagatingmarkdown_translatedfromwalk_children_with_statusIn both the “no handler” default branch and
block_handleryou currently ignore themarkdown_translatedstatus returned bydom_walker::walk_childrenvia the Chain, and instead construct aHandlerResultthat is always marked as translated:
- Lines 273–289:
Some(self.walk_children(node).into())- Lines 370–375:
Some(concat_strings!(...).into())If callers rely on
HandlerResult.markdown_translatedoutside of faithful mode, you may want to preserve the child status, e.g.:- } else { - // Default behavior: walk children and return their content - Some(self.walk_children(node).into()) - } + } else { + // Default behavior: walk children and return their content/status + Some(self.walk_children_with_status(node)) + }And in
block_handler:fn block_handler(chain: &dyn Chain, element: Element) -> Option<HandlerResult> { if element.options.translation_mode == TranslationMode::Pure { - let content = chain.walk_children(element.node); - let content = content.trim_matches('\n'); - Some(concat_strings!("\n\n", content, "\n\n").into()) + let mut result = chain.walk_children_with_status(element.node); + let content = result.content.trim_matches('\n'); + result.content = concat_strings!("\n\n", content, "\n\n"); + Some(result)This keeps the new Chain-based content generation while more accurately reflecting whether any descendants had to fall back to HTML.
Also applies to: 370-378
📜 Review details
Configuration used: CodeRabbit UI
Review profile: CHILL
Plan: Pro
📒 Files selected for processing (24)
src/dom_walker.rs(5 hunks)src/element_handler/anchor.rs(3 hunks)src/element_handler/blockquote.rs(1 hunks)src/element_handler/br.rs(1 hunks)src/element_handler/caption.rs(1 hunks)src/element_handler/code.rs(7 hunks)src/element_handler/element_util.rs(6 hunks)src/element_handler/emphasis.rs(1 hunks)src/element_handler/head_body.rs(1 hunks)src/element_handler/headings.rs(1 hunks)src/element_handler/hr.rs(1 hunks)src/element_handler/html.rs(2 hunks)src/element_handler/img.rs(2 hunks)src/element_handler/li.rs(2 hunks)src/element_handler/list.rs(6 hunks)src/element_handler/mod.rs(3 hunks)src/element_handler/p.rs(1 hunks)src/element_handler/pre.rs(2 hunks)src/element_handler/table.rs(8 hunks)src/element_handler/tbody.rs(1 hunks)src/element_handler/td_th.rs(1 hunks)src/element_handler/thead.rs(1 hunks)src/element_handler/tr.rs(1 hunks)src/lib.rs(0 hunks)
💤 Files with no reviewable changes (1)
- src/lib.rs
🧰 Additional context used
🧬 Code graph analysis (14)
src/element_handler/td_th.rs (1)
src/element_handler/element_util.rs (1)
handle_or_serialize_by_parent(16-42)
src/element_handler/tbody.rs (1)
src/element_handler/element_util.rs (1)
handle_or_serialize_by_parent(16-42)
src/element_handler/caption.rs (1)
src/element_handler/element_util.rs (1)
handle_or_serialize_by_parent(16-42)
src/element_handler/thead.rs (1)
src/element_handler/element_util.rs (1)
handle_or_serialize_by_parent(16-42)
src/element_handler/code.rs (1)
src/element_handler/element_util.rs (1)
serialize_element(46-177)
src/element_handler/table.rs (1)
src/element_handler/element_util.rs (1)
serialize_element(46-177)
src/element_handler/anchor.rs (1)
src/element_handler/mod.rs (5)
handle(89-89)handle(96-98)handle(250-292)handle(309-309)handle(329-337)
src/element_handler/list.rs (2)
src/element_handler/element_util.rs (1)
serialize_element(46-177)src/text_util.rs (1)
join_contents(98-131)
src/element_handler/pre.rs (2)
src/node_util.rs (1)
get_node_tag_name(5-11)src/element_handler/element_util.rs (1)
serialize_element(46-177)
src/dom_walker.rs (2)
src/element_handler/mod.rs (2)
walk_children(312-312)walk_children(339-341)src/node_util.rs (1)
get_node_tag_name(5-11)
src/element_handler/tr.rs (1)
src/element_handler/element_util.rs (1)
handle_or_serialize_by_parent(16-42)
src/element_handler/head_body.rs (1)
src/element_handler/element_util.rs (1)
handle_or_serialize_by_parent(16-42)
src/element_handler/mod.rs (3)
src/element_handler/element_util.rs (1)
serialize_element(46-177)src/dom_walker.rs (2)
walk_children(105-158)is_block_element(433-435)src/node_util.rs (2)
get_node_tag_name(5-11)get_parent_node(13-24)
src/element_handler/html.rs (1)
src/element_handler/element_util.rs (1)
serialize_element(46-177)
🔇 Additional comments (26)
src/dom_walker.rs (3)
59-61: Skip pushing empty text fragments is fine and reduces buffer noiseGuarding
buffer.push(to_add)withif !to_add.is_empty()avoids storing empty strings created by trimming and compression, without changing any observable output. Looks good.
74-88: Handler content normalization looks coherent; just be aware of cross-element newline collapsingPassing
res.contentthroughnormalize_content_for_buffer(buffer.last(), res.content, is_pre)before pushing centralizes newline/space normalization at the buffer boundary. That should replace the previousjoin_contentsbehavior cleanly, and the!content.is_empty()guard prevents spurious empty segments.Given this changes how adjacent element content is merged (especially around headings and block elements), please ensure existing tests around block/inline boundaries and markdown translation still pass and consider adding one or two regression tests that assert exact output where multiple inline elements and line breaks meet (e.g.,
<em>foo</em> <strong>bar</strong>and sequences of headings/paragraphs).
135-155: Space trimming around block children seems reasonable; verify against tricky mixed contentThe
trim_leading_spaces/is_blocklogic inwalk_children:
- trims trailing spaces before each block child via
trim_buffer_end_spaces, and- trims leading spaces at the start of block parents, and after block children, but not between purely inline siblings,
matches the intent of collapsing extraneous spaces at block boundaries while preserving inline spacing.
Because this is subtle, especially for cases like:
- text followed by a block followed by more text, and
- inline elements with leading/trailing spaces adjacent to blocks,
it would be good to have explicit tests (if not already present) covering those patterns to ensure markdown output matches expectations.
src/element_handler/img.rs (1)
8-24: img_handler Chain parameter wiring looks consistent with the broader refactorSwitching the signature to
img_handler(chain: &dyn Chain, element: Element)and updatingserialize_if_faithful!(chain, element, 0);aligns this handler with the new chain-based serialization pattern. Since the rest of the logic is unchanged, behavior should be identical aside from enabling faithful-mode serialization to use the Chain context.Just make sure the updated
serialize_if_faithful!macro signature matches this usage everywhere.src/element_handler/hr.rs (1)
8-14: hr_handler correctly threads Chain into faithful serializationThe change to
hr_handler(chain: &dyn Chain, element: Element)andserialize_if_faithful!(chain, element, 0);matches the new pattern while keeping the HrStyle-based markdown output intact. No issues spotted.src/element_handler/br.rs (1)
8-14: br_handler Chain wiring is consistent; behavior unchangedUpdating
br_handlerto acceptchain: &dyn Chainand callingserialize_if_faithful!(chain, element, 0);keeps the existing BrStyle behavior while integrating with the new Chain-based serialization. Looks good.src/element_handler/head_body.rs (1)
7-8: LGTM - Chain parameter correctly threaded through.The handler signature and call to
handle_or_serialize_by_parenthave been correctly updated to pass thechainparameter, aligning with the refactored signature shown in the relevant code snippets.src/element_handler/caption.rs (1)
8-10: LGTM - Consistent with the refactoring pattern.All updates to thread the
chainparameter through the macro and function calls are correct and consistent with the broader refactor.src/element_handler/emphasis.rs (1)
9-14: LGTM - Content generation correctly migrated to Chain.The handler now properly uses
chain.walk_children(element.node)for on-demand content generation instead of cachedelement.content. The subsequent whitespace stripping and marker logic remains unchanged.src/element_handler/html.rs (3)
11-11: LGTM - Chain parameter properly integrated.
25-27: Content generation correctly uses Chain walking.The markdown-translatable path now properly generates content via
chain.walk_children(element.node)with appropriate newline trimming and wrapping.
30-30: Serialization updated to use Chain context.The
serialize_elementcall correctly passes thechainparameter as shown in the relevant code snippets fromelement_util.rs.src/element_handler/td_th.rs (1)
8-10: LGTM - Chain parameter correctly propagated.The handler signature and downstream calls have been properly updated to thread the
chainparameter through the serialization and parent-handling logic.src/element_handler/tbody.rs (1)
8-12: LGTM - Consistent refactoring applied.All changes correctly thread the
chainparameter through the macro and function calls, maintaining consistency with the broader refactor.src/element_handler/headings.rs (1)
9-14: LGTM - Content generation migrated to Chain with appropriate trimming.The handler correctly uses
chain.walk_children(element.node)for content generation. The two-step trimming (ASCII whitespace followed by newlines) is appropriate for heading content normalization.src/element_handler/tr.rs (1)
8-17: LGTM - Chain parameter correctly integrated.The handler properly threads the
chainparameter through the serialization macro and the parent-handling function call, consistent with the broader refactor.src/element_handler/blockquote.rs (1)
8-17: Chain-based blockquote handling looks correctUsing
chain.walk_childrenplus a single leading'\n'trim and end-of-content ASCII whitespace trimming preserves the existing formatting semantics while aligning with the new chain-based pipeline. No issues spotted.src/element_handler/li.rs (1)
10-41: List item refactor is consistent with the new Chain flowThreading
chainthrough, usingwalk_childrenfor content, and distinguishingolvsulvia the parent tag look correct. The adjusted newline handling for theulcase should better align withjoin_contentswithout introducing extra spacing.src/element_handler/thead.rs (1)
8-13: thead handler correctly propagates the Chain contextPassing
chaininto bothserialize_if_faithful!andhandle_or_serialize_by_parentmatches the updated utilities and preserves the existing faithful/parent logic.src/element_handler/pre.rs (1)
10-47: pre/code handling and faithful fallback logic look soundThe new
is_simple_code_blockcheck pluswalk_children_with_statusand the Faithful-mode fallback on!result.markdown_translatedalign with the documented cases for<pre><code>vs other<pre>usages. The outertrim_matches('\n')plus\n\n…\n\nframing also looks consistent with block-level formatting.Given how subtle these translation-mode branches are, it’s worth ensuring there are regression tests for:
<pre><code>in both Pure and Faithful modes, and<pre>with more complex children correctly falling back to HTML in Faithful mode.src/element_handler/element_util.rs (1)
16-42: Core serialization utilities are correctly updated to be Chain-awareThreading
chainthroughhandle_or_serialize_by_parent,serialize_element, andserialize_if_faithful!is coherent with the broader refactor. Usingchain.walk_childrenfor non-block HTML contents preserves the “current translated children inside raw HTML inline” behavior while keeping block HTML fully DOM-serialized.Also applies to: 46-76, 182-203
src/element_handler/anchor.rs (1)
32-78: Anchor handler’s Chain integration and content sourcing look correctUsing
serialize_if_faithful!(chain, …)inside the attr loop andchain.walk_children(element.node)both for the no-hreffallback and as the anchor text source aligns the anchor behavior with the new traversal model without changing link-style semantics.src/element_handler/list.rs (1)
12-71: Ordered/unordered list handling correctly tracks child translation statusThe combination of:
- Faithful-mode guards (including the initial structural checks),
- the
(content, translated)return fromget_ol_content, and- the post-check on
result.markdown_translatedbefore potentially falling back toserialize_element(chain, &element)gives ordered and unordered lists consistent “all children must be translated” semantics. The newline trimming and early
Nonereturn for empty content are also reasonable.Also applies to: 78-132
src/element_handler/code.rs (2)
15-43: Chain-awarecode_handlerwiring looks correctUsing
chain: &dyn Chainin the handler, passing it through toserialize_element(chain, &element)for the faithful/non-text-children case, and tohandle_code_block/handle_inline_codekeeps behavior consistent while integrating the new Chain API. Theparent_node.unwrap()is safe given theis_code_blockcomputation.
112-148: Inline code handler correctly migrated toChainDeriving inline code content via
chain.walk_children(element.node)before backtick analysis, and passing&contentintohandle_preformatted_code, preserves the previous semantics while aligning with the Chain-based walking approach. No issues spotted here.src/element_handler/mod.rs (1)
311-316:Chainwalking helpers andis_inside_preare wired sensiblyThe new
Chainmethods (walk_childrenandwalk_children_with_status) correctly delegate todom_walker::walk_children, computingis_blockandis_prefromget_node_tag_nameand the newis_inside_prehelper so that pre/code contexts skip leading-space trimming. Theis_inside_pretraversal viaget_parent_nodeis safe and bounded by the DOM depth, and overall these integrations look consistent with the dom_walker expectations.Also applies to: 339-355, 357-368
There was a problem hiding this comment.
Actionable comments posted: 1
🧹 Nitpick comments (4)
src/element_handler/table.rs (1)
22-23: Consider including<caption>translation status inall_children_translated
all_children_translatedcurrently aggregates only fromextract_row_cells(i.e.,<th>/<td>content). Captions are handled viachain.handle(&child)but theirmarkdown_translatedflag is ignored, so a table with an untranslated<caption>can still be treated as “fully translated” in Faithful mode.If captions should also participate in Faithful gating, you can fold them into
all_children_translated:"caption" => { - if let Some(res) = chain.handle(&child) { - captions.push(res.content.trim().to_string()); - } + if let Some(res) = chain.handle(&child) { + if !res.markdown_translated { + all_children_translated = false; + } + captions.push(res.content.trim().to_string()); + } }This keeps your manual child-translation tracking aligned with the rest of the table’s structure-aware logic.
Also applies to: 42-47, 189-205
src/element_handler/list.rs (1)
43-70: Preserveresult.markdown_translatedwhen wrapping list content
resultcorrectly carries the aggregatedmarkdown_translatedfromget_ol_content/walk_children, and you already gate on it in Faithful mode. After that, you trim and wrap the content but drop the flag by calling.into(), which always setsmarkdown_translated = true.You can keep the flag without changing behavior:
- let trimmed = result.content.trim_matches(|ch| ch == '\n'); - if trimmed.is_empty() { - return None; - } - - if is_parent_li { - Some(concat_strings!("\n", trimmed, "\n").into()) - } else { - Some(concat_strings!("\n\n", trimmed, "\n\n").into()) - } + let trimmed = result.content.trim_matches(|ch| ch == '\n'); + if trimmed.is_empty() { + return None; + } + + let wrapped = if is_parent_li { + concat_strings!("\n", trimmed, "\n") + } else { + concat_strings!("\n\n", trimmed, "\n\n") + }; + + Some(HandlerResult { + content: wrapped, + markdown_translated: result.markdown_translated, + })That keeps translation status accurate for callers, especially in Pure mode, with minimal complexity.
src/element_handler/html.rs (1)
24-33: Reusewalk_children’smarkdown_translatedinhtml_handlerIn the markdown‑translatable branch you only use
chain.walk_children(...).contentand convert the wrapped string via.into(), forcingmarkdown_translated = trueeven if some descendants fell back to HTML.You can cheaply preserve the aggregated flag:
- if markdown_translatable { - let content = chain.walk_children(element.node).content; - let content = content.trim_matches('\n'); - Some(concat_strings!("\n\n", content, "\n\n").into()) - } else { - Some(HandlerResult { - content: serialize_element(chain, &element), - markdown_translated: false, - }) - } + if markdown_translatable { + let result = chain.walk_children(element.node); + let content = result.content.trim_matches('\n'); + Some(HandlerResult { + content: concat_strings!("\n\n", content, "\n\n"), + markdown_translated: result.markdown_translated, + }) + } else { + Some(HandlerResult { + content: serialize_element(chain, &element), + markdown_translated: false, + }) + }This keeps the top‑level HTML element’s translation status aligned with the new
walk_childrensemantics.src/element_handler/mod.rs (1)
250-289: Good abstraction aroundChain, but consider consistent use ofmarkdown_translatedThe new
Chainimplementation andwalk_childrenhelper are well-structured:
Chain::handlere-roots walking viawalk_nodewithout interfering with the main handler dispatch.Chain::walk_childrencorrectly derivesis_block/is_preusingis_block_elementandis_inside_pre, then returns both content and an aggregatedmarkdown_translatedflag.- The default “no handler” case in
ElementHandlers::handleis now cleanly expressed in terms ofserialize_element(Faithful) vs.walk_children(Pure).One consistency gap: several handlers that consume
chain.walk_children(e.g.,block_handlerhere, plus list/html/table fallbacks) currently do:
let content = chain.walk_children(...).content;- Wrap the string.
- Convert via
.into(), which forcesmarkdown_translated = true.Given that
walk_children/walk_nodewere extended specifically to trackmarkdown_translated, it’s worth standardizing on patterns like:let result = chain.walk_children(element.node); let content = result.content.trim_matches('\n'); HandlerResult { content: concat_strings!("\n\n", content, "\n\n"), markdown_translated: result.markdown_translated, }You’ve already applied this style in some places (e.g., OL handling), and adopting it broadly would make the translation status signal much more reliable for callers and for Faithful-mode decisions.
Also applies to: 301-313, 315-348, 350-374
📜 Review details
Configuration used: CodeRabbit UI
Review profile: CHILL
Plan: Pro
📒 Files selected for processing (13)
src/element_handler/anchor.rs(3 hunks)src/element_handler/blockquote.rs(1 hunks)src/element_handler/code.rs(7 hunks)src/element_handler/element_util.rs(6 hunks)src/element_handler/emphasis.rs(1 hunks)src/element_handler/headings.rs(1 hunks)src/element_handler/html.rs(2 hunks)src/element_handler/li.rs(2 hunks)src/element_handler/list.rs(6 hunks)src/element_handler/mod.rs(3 hunks)src/element_handler/p.rs(1 hunks)src/element_handler/pre.rs(2 hunks)src/element_handler/table.rs(8 hunks)
🚧 Files skipped from review as they are similar to previous changes (3)
- src/element_handler/li.rs
- src/element_handler/headings.rs
- src/element_handler/emphasis.rs
🧰 Additional context used
🧬 Code graph analysis (8)
src/element_handler/element_util.rs (2)
src/dom_walker.rs (1)
is_block_element(433-435)src/node_util.rs (1)
parent_tag_name_equals(27-36)
src/element_handler/list.rs (2)
src/element_handler/element_util.rs (1)
serialize_element(46-177)src/text_util.rs (1)
join_contents(98-131)
src/element_handler/mod.rs (3)
src/element_handler/element_util.rs (1)
serialize_element(46-177)src/dom_walker.rs (2)
walk_children(105-158)is_block_element(433-435)src/node_util.rs (2)
get_node_tag_name(5-11)get_parent_node(13-24)
src/element_handler/pre.rs (2)
src/node_util.rs (1)
get_node_tag_name(5-11)src/element_handler/element_util.rs (1)
serialize_element(46-177)
src/element_handler/table.rs (1)
src/element_handler/element_util.rs (1)
serialize_element(46-177)
src/element_handler/code.rs (1)
src/element_handler/element_util.rs (1)
serialize_element(46-177)
src/element_handler/html.rs (1)
src/element_handler/element_util.rs (1)
serialize_element(46-177)
src/element_handler/anchor.rs (1)
src/element_handler/mod.rs (5)
handle(89-89)handle(96-98)handle(250-292)handle(309-309)handle(326-334)
🪛 GitHub Actions: Cargo Build & Test
src/element_handler/anchor.rs
[error] 48-48: cargo clippy --deny warnings failed: useless conversion to the same type: element_handler::HandlerResult at src/element_handler/anchor.rs:48. Consider removing .into() (clippy::useless_conversion).
🔇 Additional comments (6)
src/element_handler/p.rs (1)
8-12: p_handler correctly switched to Chain-based content traversalUsing
chain.walk_children(element.node).contentwith the existing newline trimming and wrapping keeps behavior consistent while aligning with the new Chain-based model.src/element_handler/element_util.rs (1)
2-7: Chain-aware serialization/utilities look consistent and cohesiveThreading
&dyn Chainthroughhandle_or_serialize_by_parent,serialize_element, andserialize_if_faithful!cleanly centralizes HTML fallback and keeps the existing newline/whitespace behavior, while aligning with the new walk-children pipeline.Also applies to: 16-42, 46-72, 182-202
src/element_handler/blockquote.rs (1)
8-17: blockquote_handler refactor preserves formatting while using Chain contentThe switch to
chain.walk_childrenplus leading'\n'trim slots neatly into the existing whitespace and quoting pipeline without changing the rendered structure.src/element_handler/pre.rs (1)
10-47: pre_handler’s faithful vs pure logic and simple-code detection look soundThe new
is_simple_code_blockcheck and the conditional fallback toserialize_elementin faithful mode correctly gate when<pre>becomes a Markdown code block versus raw HTML, while usingchain.walk_childrenfor content in the translated path.src/element_handler/anchor.rs (1)
32-48: Remove redundant.into()to fix clippy failureThe code at
anchor.rs:48calls.into()onchain.walk_children(element.node), which already returns aHandlerResult. Since thewalk_childrenmethod signature returnsHandlerResultdirectly, wrapping it inSome()already produces the correct return typeOption<HandlerResult>, making the.into()call a useless conversion that triggersclippy::useless_conversion.Remove the
.into():- let Some(link) = link else { - return Some(chain.walk_children(element.node).into()); - }; + let Some(link) = link else { + return Some(chain.walk_children(element.node)); + };The rest of the Chain-based refactor in this handler (including updated
serialize_if_faithful!usage and content derivation at line 63) is consistent with patterns in other handlers.src/element_handler/code.rs (1)
15-42: Chain threading and code handler refactor look consistentThe updates to thread
chainthroughcode_handler,handle_code_block, andhandle_inline_codeare coherent:
- Faithful guard now properly serializes via
serialize_element(chain, &element).- Content for both block and inline code comes from
chain.walk_children(element.node), aligning with the new walking model.- The
parent_node.unwrap()in the code‑block path is correctly guarded byis_code_block.I don’t see functional regressions in these modified sections.
Also applies to: 45-83, 112-148
| if element.options.translation_mode == TranslationMode::Faithful && !all_children_translated { | ||
| return Some(HandlerResult { | ||
| content: serialize_element(chain, &element), | ||
| markdown_translated: false, | ||
| }); | ||
| } | ||
|
|
||
| // If we didn't find any rows or cells, just return the content as-is | ||
| if rows.is_empty() && headers.is_empty() { | ||
| let content = chain.walk_children(element.node).content; | ||
| let content = content.trim_matches('\n'); | ||
| if content.is_empty() { | ||
| return None; | ||
| } | ||
| return Some(concat_strings!("\n\n", content, "\n\n").into()); | ||
| } |
There was a problem hiding this comment.
Propagate markdown_translated and re‑guard Faithful mode in table fallbacks
In both fallback branches (rows.is_empty() && headers.is_empty() and num_columns == 0), you call chain.walk_children(element.node) but only use .content, converting the final result via .into(). That forces markdown_translated = true even if walk_children actually reported false, and Faithful mode is no longer re-checked for these “non‑tabular” cases.
For irregular tables that don’t yield headers/rows but contain partially untranslated children, this will:
- Treat the table as fully markdown‑translated, and
- Skip the Faithful fallback to serialized HTML that you apply earlier based on
all_children_translated.
To keep translation status and Faithful behavior consistent, consider:
- Using the full
HandlerResultfromwalk_children, and - Adding a Faithful guard keyed off that result, then
- Returning a
HandlerResultthat preservesresult.markdown_translated.
Example adjustment:
@@
- if rows.is_empty() && headers.is_empty() {
- let content = chain.walk_children(element.node).content;
- let content = content.trim_matches('\n');
- if content.is_empty() {
- return None;
- }
- return Some(concat_strings!("\n\n", content, "\n\n").into());
- }
+ if rows.is_empty() && headers.is_empty() {
+ let result = chain.walk_children(element.node);
+ if element.options.translation_mode == TranslationMode::Faithful
+ && !result.markdown_translated
+ {
+ return Some(HandlerResult {
+ content: serialize_element(chain, &element),
+ markdown_translated: false,
+ });
+ }
+
+ let content = result.content.trim_matches('\n');
+ if content.is_empty() {
+ return None;
+ }
+ return Some(HandlerResult {
+ content: concat_strings!("\n\n", content, "\n\n"),
+ markdown_translated: result.markdown_translated,
+ });
+ }
@@
- if num_columns == 0 {
- let content = chain.walk_children(element.node).content;
- let content = content.trim_matches('\n');
- if content.is_empty() {
- return None;
- }
- return Some(concat_strings!("\n\n", content, "\n\n").into());
- }
+ if num_columns == 0 {
+ let result = chain.walk_children(element.node);
+ if element.options.translation_mode == TranslationMode::Faithful
+ && !result.markdown_translated
+ {
+ return Some(HandlerResult {
+ content: serialize_element(chain, &element),
+ markdown_translated: false,
+ });
+ }
+
+ let content = result.content.trim_matches('\n');
+ if content.is_empty() {
+ return None;
+ }
+ return Some(HandlerResult {
+ content: concat_strings!("\n\n", content, "\n\n"),
+ markdown_translated: result.markdown_translated,
+ });
+ }This keeps the Faithful semantics coherent for tables that can’t be rendered as Markdown.
Also applies to: 150-157
🤖 Prompt for AI Agents
In src/element_handler/table.rs around lines 126-141 (and similarly 150-157),
the code calls chain.walk_children(element.node) but only uses .content and
converts to .into(), which loses the returned HandlerResult.markdown_translated
and skips re-checking Faithful translation_mode; fix by capturing the full
HandlerResult (let result = chain.walk_children(element.node)), check
result.markdown_translated and if element.options.translation_mode ==
TranslationMode::Faithful && !result.markdown_translated return the serialized
HTML fallback (as done earlier), otherwise build and return a HandlerResult that
uses result.content for the string concatenation and preserves
result.markdown_translated in the returned markdown_translated field so
translation status and Faithful behavior remain consistent.
There was a problem hiding this comment.
Actionable comments posted: 0
Caution
Some comments are outside the diff and can’t be posted inline due to platform limitations.
⚠️ Outside diff range comments (2)
src/text_util.rs (1)
255-265: concat_strings! macro has a type error in length accumulation
len += &$x.len();adds a&usizeinto ausize, which will not compile. This looks like a stray&and will break any use of the macro.Suggested fix:
- $( - len += &$x.len(); - )* + $( + len += $x.len(); + )*This keeps the capacity estimate correct without changing any call sites.
src/element_handler/table.rs (1)
43-47: Missing faithful-mode fallback when caption translation fails
chain.handlefor<caption>can returnmarkdown_translated == falsewhen the caption contains HTML we can’t render as Markdown. Becauseall_children_translatedisn’t updated in this branch, we incorrectly report success and still emit the Markdown table in faithful mode, letting raw HTML sneak into a supposedly translated block. Please fold the caption’s translation status intoall_children_translatedso we fall back to serialized HTML when needed."caption" => { - if let Some(res) = chain.handle(&child) { - captions.push(res.content.trim().to_string()); - } + if let Some(res) = chain.handle(&child) { + all_children_translated &= res.markdown_translated; + captions.push(res.content.trim().to_string()); + } }
🧹 Nitpick comments (1)
src/element_handler/headings.rs (1)
9-15: Heading handler correctly switched to chain-derived contentUsing
chain.walk_children(element.node).contentand then trimming viatrim_ascii_whitespacefollowed bytrim_matches('\n')keeps the old normalization behavior while aligning with the new Chain API. The extratrim_matches('\n')aftertrim_ascii_whitespaceis slightly redundant but not harmful.This still assumes
element.tagis always anhN-style tag (due tonth(1).unwrap()); if that invariant ever relaxes, you may want a safe parse path instead ofunwrap.
📜 Review details
Configuration used: CodeRabbit UI
Review profile: CHILL
Plan: Pro
📒 Files selected for processing (14)
src/element_handler/anchor.rs(3 hunks)src/element_handler/blockquote.rs(1 hunks)src/element_handler/code.rs(7 hunks)src/element_handler/element_util.rs(6 hunks)src/element_handler/emphasis.rs(1 hunks)src/element_handler/headings.rs(1 hunks)src/element_handler/html.rs(2 hunks)src/element_handler/li.rs(2 hunks)src/element_handler/list.rs(7 hunks)src/element_handler/mod.rs(3 hunks)src/element_handler/p.rs(1 hunks)src/element_handler/pre.rs(2 hunks)src/element_handler/table.rs(8 hunks)src/text_util.rs(1 hunks)
🚧 Files skipped from review as they are similar to previous changes (2)
- src/element_handler/anchor.rs
- src/element_handler/emphasis.rs
🧰 Additional context used
🧬 Code graph analysis (7)
src/element_handler/element_util.rs (2)
src/dom_walker.rs (1)
is_block_element(433-435)src/node_util.rs (1)
parent_tag_name_equals(27-36)
src/element_handler/code.rs (1)
src/element_handler/element_util.rs (1)
serialize_element(46-177)
src/element_handler/pre.rs (2)
src/node_util.rs (1)
get_node_tag_name(5-11)src/element_handler/element_util.rs (1)
serialize_element(46-177)
src/element_handler/table.rs (1)
src/element_handler/element_util.rs (1)
serialize_element(46-177)
src/element_handler/list.rs (2)
src/text_util.rs (1)
join_blocks(98-131)src/element_handler/element_util.rs (1)
serialize_element(46-177)
src/element_handler/html.rs (1)
src/element_handler/element_util.rs (1)
serialize_element(46-177)
src/element_handler/mod.rs (3)
src/element_handler/element_util.rs (1)
serialize_element(46-177)src/dom_walker.rs (2)
walk_children(105-158)is_block_element(433-435)src/node_util.rs (2)
get_node_tag_name(5-11)get_parent_node(13-24)
🔇 Additional comments (6)
src/text_util.rs (1)
96-131: join_blocks rename keeps behavior; API impact is confined to crate
join_blockspreserves the previousjoin_contentslogic and is stillpub(crate), so the rename is purely internal and safe as long as all in-crate call sites are updated (as inlist.rs). No issues with the allocation or newline handling here.src/element_handler/blockquote.rs (1)
8-17: Chain-based content for blockquotes looks consistent with existing behaviorSwitching to
chain.walk_children(element.node).contentand threadingchainintoserialize_if_faithful!aligns this handler with the new pipeline. The leading\ntrim plus trailing ASCII-whitespace trim before prefixing each line with"> "preserves the earlier blockquote formatting assumptions.The only thing to watch is that
Chain::walk_childrennormalizes child content identically to the oldElement.content; any change there will surface as different leading/trailing newlines here. Please rely on existing blockquote tests to confirm no regressions.src/element_handler/p.rs (1)
8-12: Paragraph handler correctly migrated to chain.walk_childrenThreading
chainintoserialize_if_faithful!and deriving content viachain.walk_children(element.node).contentwith surrounding\n\n … \n\npreserves the paragraph block behavior while fitting the new architecture.trim_matches('\n')maintains the previous stripping of leading/trailing blank lines.No issues spotted here; just ensure paragraph-focused tests still pass with the new Chain-based content source.
src/element_handler/html.rs (1)
11-31: HTML handler’s faithful-mode semantics changed; confirm this is intentionalThe refactor to:
- pass
chainthrough, and- derive markdown content via
chain.walk_children(element.node).contentis consistent with the rest of the PR.
The key behavioral change is the
markdown_translatableguard: inFaithfulmode you now require the parent to be aDocumentnode, whereas inPuremode it’s always markdown-translatable. This tightens when<html>(or similar) gets turned into Markdown vs serialized as raw HTML.If the intention is “only top-level HTML gets markdown-ized in faithful mode,” this is correct, but it’s worth re-running any tests involving embedded HTML fragments to confirm there are no surprises.
src/element_handler/element_util.rs (1)
16-42: Chain-aware serialization wiring looks correct; validate inline-HTML and parent-guarded casesThese changes align element serialization with the new Chain-based traversal:
handle_or_serialize_by_parentnow takeschainand:
- falls back to
serialize_element(chain, element)when the parent tag check fails inFaithfulmode,- otherwise uses
chain.walk_children(element.node).contenttrimmed of\nand wrapped with\n\n…\n\n.serialize_elementnow acceptschainand, for non-block elements, writes outchain.walk_children(element.node).contentdirectly into the HTML serializer, matching the “raw HTML inline with Markdown children” comment.serialize_if_faithful!is correctly updated to accept$chainand forward it toserialize_element, so all callers consistently use the same fallback path.Assuming
Chain::walk_childrenonly walks children (not the element itself) and preserves the same normalization that the oldElement.contenthad, this should behave identically for both inline HTML and the parent-guarded faithful-mode handlers. Please lean on tests that cover:
- inline HTML with mixed Markdown children, and
<tbody>,<td>, etc. when placed under unexpected parents,to confirm no regressions.
Also applies to: 46-76, 182-203
src/element_handler/li.rs (1)
10-17: The asymmetry exists but has no functional impact on output formatting.The code does show the UL/OL newline asymmetry you identified:
ul_li(line 27):concat_strings!("\n", marker, spacing, content)— no trailing newlineol_li(line 32):concat_strings!("\n", content, "\n")— has trailing newlineHowever, this asymmetry is functionally inconsequential. The
join_blocks()function (lines 98–131 intext_util.rs) normalizes item joining by:
- Stripping trailing newlines from the accumulated result
- Stripping leading newlines from each new item
- Inserting a controlled separator (1 or 2 newlines based on context)
This means whether UL items have a trailing newline is irrelevant—
join_blocks()removes it anyway. The tests confirm the output is correct: both UL and OL produce items separated by single newlines (Item 1\n* Item 2\n* Item 3for UL,1. Item 1\n2. Item 2for OL).The asymmetry is a minor code consistency issue but does not alter spacing or cause the problems the review suggests.
Likely an incorrect or invalid review comment.
Remove
walk_childrenfromwalk_node, exposewalk_children(Node)to the handler chain. Now, element handlers are responsible for callingwalk_childrento get the content of their children.This improves performance by ~23% in the Wikipedia conversion benchmark (from 19.9ms to 15.4ms).
Summary by CodeRabbit
Refactor
Bug Fixes
Documentation
✏️ Tip: You can customize this high-level summary in your review settings.