Skip to content

Refactor walk_children() - #62

Merged
letmutex merged 6 commits into
mainfrom
refactor-walk-children
Nov 20, 2025
Merged

letmutex merged 6 commits into
mainfrom
refactor-walk-children

Conversation

@letmutex

@letmutex letmutex commented Nov 20, 2025 •

Copy link
Copy Markdown
Owner

Remove walk_children from walk_node, expose walk_children(Node) to the handler chain. Now, element handlers are responsible for calling walk_children to get the content of their children.

This improves performance by ~23% in the Wikipedia conversion benchmark (from 19.9ms to 15.4ms).

-convert()               time:   [19.961 ms 19.973 ms 19.984 ms]
+convert()               time:   [15.461 ms 15.551 ms 15.661 ms]

Summary by CodeRabbit

  • Refactor

    • Content is now derived by traversing element children and serialized via a unified path, yielding more consistent Markdown output and fewer edge cases.
    • Normalization now merges adjacent text and collapses excess newlines/spaces for cleaner results.
  • Bug Fixes

    • Improved whitespace trimming at block/inline boundaries to avoid empty or spurious inserts and preserve link/formatting fidelity.
    • Better handling of lists, tables and code/pre blocks to reduce incorrect or serialized fallbacks.
  • Documentation

    • Benchmark note updated (README).

✏️ Tip: You can customize this high-level summary in your review settings.

@coderabbitai

coderabbitai Bot commented Nov 20, 2025 •

Copy link
Copy Markdown
Contributor

Walkthrough

This PR removes Element.content, threads a Chain through handlers, adds Chain::walk_children, and implements DOM-walking buffer logic (new walk_children, normalize_content_for_buffer, trimming/combining helpers) to derive and propagate child content and markdown-translated state.

Changes

Cohort / File(s) Summary
Public API
src/lib.rs
Removed pub content: &'a str from Element<'a>.
Chain & Handlers Core
src/element_handler/mod.rs, src/element_handler/element_util.rs
Added Chain::walk_children(&self, node: &Rc<Node>) -> HandlerResult and impl for ElementHandlers; removed standalone content param from handler entry; updated serialize_element and handle_or_serialize_by_parent to accept chain; updated serialize_if_faithful! macro to take chain.
DOM walker & normalization
src/dom_walker.rs
Added pub(crate) fn walk_children(...) -> bool and pub(crate) fn normalize_content_for_buffer(...) -> String; walk_node now delegates combination/whitespace-normalization to new logic, merges adjacent text blocks, collapses excessive newlines (max 2), and trims around block boundaries using trim_buffer_end* helpers. Removed use of prior join_contents path.
Handler signature threading (bulk)
src/element_handler/*.rs
Many handlers now accept chain: &dyn Chain (replacing _chain) and obtain content via chain.walk_children(element.node).content instead of element.content. Files: anchor.rs, blockquote.rs, br.rs, caption.rs, code.rs, emphasis.rs, head_body.rs, headings.rs, hr.rs, html.rs, img.rs, li.rs, list.rs, p.rs, pre.rs, table.rs, tbody.rs, td_th.rs, thead.rs, tr.rs.
Content & translation-flow changes
src/element_handler/{list.rs,table.rs,pre.rs,code.rs}
Lists/tables now aggregate per-child markdown_translated status (returning tuples or HandlerResult with flag) and gate faithful-mode fallback to serialize_element(chain, &element) when children aren’t fully translated; pre/code detect simple code-blocks and propagate translation state via chain.walk_children.
Text utilities rename
src/text_util.rs
Renamed join_contents → join_blocks.
Bench & docs
benches/README.md, README.md
Updated benchmark timings, statistics and README benchmark claim.

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
Loading

Estimated code review effort

🎯 4 (Complex) | ⏱️ ~60 minutes

  • Extra attention:
    • src/dom_walker.rs — new normalization, newline/space collapsing, combining logic, and pre-context handling.
    • src/element_handler/mod.rs & element_util.rs — Chain trait change, macro update, and serialize_element(chain, &element) call sites.
    • src/element_handler/table.rs & src/element_handler/list.rs — per-child translation tracking and changed return shapes.
    • Verify all handlers no longer rely on element.content and that chain is consistently threaded.

Possibly related PRs

Poem

🐰 I hop through nodes with tidy paws,
I stitch the spaces, trim the flaws.
Chain in my grip, I walk and bind,
Two newlines max — I’m precise and kind.
A rabbit refactor, neat in twine! 🥕

Pre-merge checks and finishing touches

❌ Failed checks (1 warning)
Check name Status Explanation Resolution
Docstring Coverage ⚠️ Warning Docstring coverage is 35.00% which is insufficient. The required threshold is 80.00%. You can run @coderabbitai generate docstrings to improve docstring coverage.
✅ Passed checks (2 passed)
Check name Status Explanation
Description Check ✅ Passed Check skipped - CodeRabbit’s high-level summary is enabled.
Title check ✅ Passed The title 'Refactor walk_children()' accurately describes the primary changes in this pull request, which center on introducing a new walk_children function and updating content derivation across the codebase to use chain-based walking instead of direct element.content access.
✨ Finishing touches
  • 📝 Generate docstrings
🧪 Generate unit tests (beta)
  • Create PR with unit tests
  • Post copyable unit tests in a comment
  • Commit unit tests in branch refactor-walk-children

📜 Recent review details

Configuration used: CodeRabbit UI

Review profile: CHILL

Plan: Pro

📥 Commits

Reviewing files that changed from the base of the PR and between 7738526 and 01ed854.

📒 Files selected for processing (4)
  • README.md (1 hunks)
  • src/element_handler/anchor.rs (3 hunks)
  • src/element_handler/list.rs (7 hunks)
  • src/text_util.rs (1 hunks)
🧰 Additional context used
🧬 Code graph analysis (2)
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)
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)
🔇 Additional comments (10)
README.md (2)

13-13: Verify benchmark claim and reconcile with benches/README.md.

The benchmark claim changes from ~70ms (i5 7th gen) to ~16ms (Apple M4), reflecting a ~4.4× speedup. However, the AI summary mentions benches/README.md reports a more modest improvement (~19.96–19.984 ms → ~15.46–15.66 ms, ~1.3× faster).

The discrepancy could stem from different hardware, benchmarking methodology, or test datasets. Ensure the main README claim is accurate and reconcilable with the bench suite results.

Please verify:

  1. The benchmark methodology and dataset are consistent between README.md and benches/README.md
  2. The ~16ms claim is reproducible on the target hardware (Apple M4)
  3. If a significant portion of improvement comes from the walk_children() refactor, document this in the commit message or PR description

1-149: Confirm documentation updates for public API changes.

Per the PR summary, Element.content is removed (breaking change to public API), and handlers are refactored to use Chain::walk_children(). The README examples (particularly the custom tag handler example at lines 62–68) should be verified to ensure they reflect the updated API and still compile/work as expected.

Please confirm:

  1. All code examples in the README are valid for the refactored API
  2. Custom handler examples correctly use the Chain parameter to access element content
  3. If the custom handler example needs clarification on how to derive content from the chain
src/text_util.rs (1)

98-131: LGTM: Clear rename improves semantics.

The rename from join_contents to join_blocks better reflects the function's purpose of joining markdown block-level elements. The implementation logic remains correct.

src/element_handler/anchor.rs (2)

32-49: LGTM: Chain threading is consistent.

The signature change to actively use chain and the updated serialize_if_faithful! macro call align with the broader refactoring pattern. The fallback path correctly uses chain.walk_children(element.node) when no link is found.


63-75: LGTM: Content derivation follows the new pattern.

The content is now correctly derived from chain.walk_children(element.node).content and consistently used across all link styles. This aligns with the removal of Element.content mentioned in the PR summary.

src/element_handler/list.rs (5)

9-37: LGTM: Imports and faithful mode checks updated correctly.

The import change to join_blocks and the updated serialize_if_faithful! and serialize_element calls with chain as the first parameter are consistent with the refactoring pattern across the codebase.


43-51: LGTM: Result handling tracks translation state.

The updated code correctly constructs HandlerResult from the tuple returned by get_ol_content for ordered lists, while using chain.walk_children directly for unordered lists. This allows proper tracking of the markdown_translated flag.


53-59: LGTM: Defensive re-serialization ensures faithful translation.

This additional check ensures that even after initial validation, if the result isn't fully translated to markdown in faithful mode, the element is re-serialized as HTML. This provides a safety net for edge cases.


61-70: LGTM: Empty content filtering improves output quality.

The new check for empty content (after trimming newlines) prevents emitting meaningless list structures. This enhances output quality by avoiding markdown like \n\n\n\n for lists with no actual content.


78-132: LGTM: Translation tracking aggregates child state correctly.

The updated get_ol_content function now returns a tuple (String, bool) to track both content and translation status. The all_translated flag correctly aggregates the translation state of all children, starting at true and setting to false if any child is not fully translated.


Comment @coderabbitai help to get the list of available commands and usage tips.

@coderabbitai coderabbitai Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

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 status

You correctly track markdown_translated for header/body cells via extract_row_cells, but all_children_translated is 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 messaging

The new walk_children implementation that:

  • merges adjacent inline elements via can_combine, and
  • trims trailing spaces before block children and leading spaces after a block

is logically sound:

  • index starts at 1 and only decrements inside the branch where can_combine has already succeeded, so index -= 1 cannot underflow.
  • After children.remove(index), index - 1 still refers to the original first node, and the can_combine constraints 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:

  1. More descriptive panic – the panic!("") in the let NodeData::Text { .. } = text_data else arm gives no context if the invariant is ever broken by future refactors. Consider using unreachable! (or at least a message) that names the expectation, e.g. "can_combine invariant violated: expected first child to be Text".

  2. Document the mutation behavior – a brief comment that walk_children mutates node.children by 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 breaks

The normalization does two things:

  1. Collapses runs of newlines across a buffer boundary to at most two total, by trimming only from the start of content.
  2. When not in pre context 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 any pre/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 the is_pre branch in NodeData::Text, but it’s worth double‑checking that handler-generated content for code/pre never hits normalize_content_for_buffer in 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 cases

Switching 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:

  1. Empty or whitespace-only <p> – walk_children may 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.
  2. 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 shadowing content with a different type in handle_code_block

The current pattern creates a String and then shadows it with a &str, which is slightly harder to follow. You could keep a single String binding 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 propagating markdown_translated from walk_children_with_status

In both the “no handler” default branch and block_handler you currently ignore the markdown_translated status returned by dom_walker::walk_children via the Chain, and instead construct a HandlerResult that 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_translated outside 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

📥 Commits

Reviewing files that changed from the base of the PR and between f78f065 and 4da8f55.

📒 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 noise

Guarding buffer.push(to_add) with if !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 collapsing

Passing res.content through normalize_content_for_buffer(buffer.last(), res.content, is_pre) before pushing centralizes newline/space normalization at the buffer boundary. That should replace the previous join_contents behavior 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 content

The trim_leading_spaces / is_block logic in walk_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 refactor

Switching the signature to img_handler(chain: &dyn Chain, element: Element) and updating serialize_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 serialization

The change to hr_handler(chain: &dyn Chain, element: Element) and serialize_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 unchanged

Updating br_handler to accept chain: &dyn Chain and calling serialize_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_parent have been correctly updated to pass the chain parameter, 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 chain parameter 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 cached element.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_element call correctly passes the chain parameter as shown in the relevant code snippets from element_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 chain parameter through the serialization and parent-handling logic.

src/element_handler/tbody.rs (1)

8-12: LGTM - Consistent refactoring applied.

All changes correctly thread the chain parameter 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 chain parameter 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 correct

Using chain.walk_children plus 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 flow

Threading chain through, using walk_children for content, and distinguishing ol vs ul via the parent tag look correct. The adjusted newline handling for the ul case should better align with join_contents without introducing extra spacing.

src/element_handler/thead.rs (1)

8-13: thead handler correctly propagates the Chain context

Passing chain into both serialize_if_faithful! and handle_or_serialize_by_parent matches 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 sound

The new is_simple_code_block check plus walk_children_with_status and the Faithful-mode fallback on !result.markdown_translated align with the documented cases for <pre><code> vs other <pre> usages. The outer trim_matches('\n') plus \n\n…\n\n framing 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-aware

Threading chain through handle_or_serialize_by_parent, serialize_element, and serialize_if_faithful! is coherent with the broader refactor. Using chain.walk_children for 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 correct

Using serialize_if_faithful!(chain, …) inside the attr loop and chain.walk_children(element.node) both for the no-href fallback 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 status

The combination of:

  • Faithful-mode guards (including the initial structural checks),
  • the (content, translated) return from get_ol_content, and
  • the post-check on result.markdown_translated before potentially falling back to serialize_element(chain, &element)

gives ordered and unordered lists consistent “all children must be translated” semantics. The newline trimming and early None return for empty content are also reasonable.

Also applies to: 78-132

src/element_handler/code.rs (2)

15-43: Chain-aware code_handler wiring looks correct

Using chain: &dyn Chain in the handler, passing it through to serialize_element(chain, &element) for the faithful/non-text-children case, and to handle_code_block / handle_inline_code keeps behavior consistent while integrating the new Chain API. The parent_node.unwrap() is safe given the is_code_block computation.


112-148: Inline code handler correctly migrated to Chain

Deriving inline code content via chain.walk_children(element.node) before backtick analysis, and passing &content into handle_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: Chain walking helpers and is_inside_pre are wired sensibly

The new Chain methods (walk_children and walk_children_with_status) correctly delegate to dom_walker::walk_children, computing is_block and is_pre from get_node_tag_name and the new is_inside_pre helper so that pre/code contexts skip leading-space trimming. The is_inside_pre traversal via get_parent_node is 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

@coderabbitai coderabbitai Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Actionable comments posted: 1

🧹 Nitpick comments (4)
src/element_handler/table.rs (1)

22-23: Consider including <caption> translation status in all_children_translated

all_children_translated currently aggregates only from extract_row_cells (i.e., <th>/<td> content). Captions are handled via chain.handle(&child) but their markdown_translated flag 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: Preserve result.markdown_translated when wrapping list content

result correctly carries the aggregated markdown_translated from get_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 sets markdown_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: Reuse walk_children’s markdown_translated in html_handler

In the markdown‑translatable branch you only use chain.walk_children(...).content and convert the wrapped string via .into(), forcing markdown_translated = true even 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_children semantics.

src/element_handler/mod.rs (1)

250-289: Good abstraction around Chain, but consider consistent use of markdown_translated

The new Chain implementation and walk_children helper are well-structured:

  • Chain::handle re-roots walking via walk_node without interfering with the main handler dispatch.
  • Chain::walk_children correctly derives is_block / is_pre using is_block_element and is_inside_pre, then returns both content and an aggregated markdown_translated flag.
  • The default “no handler” case in ElementHandlers::handle is now cleanly expressed in terms of serialize_element (Faithful) vs. walk_children (Pure).

One consistency gap: several handlers that consume chain.walk_children (e.g., block_handler here, plus list/html/table fallbacks) currently do:

  • let content = chain.walk_children(...).content;
  • Wrap the string.
  • Convert via .into(), which forces markdown_translated = true.

Given that walk_children/walk_node were extended specifically to track markdown_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

📥 Commits

Reviewing files that changed from the base of the PR and between 15a1e2f and 7738526.

📒 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 traversal

Using chain.walk_children(element.node).content with 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 cohesive

Threading &dyn Chain through handle_or_serialize_by_parent, serialize_element, and serialize_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 content

The switch to chain.walk_children plus 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 sound

The new is_simple_code_block check and the conditional fallback to serialize_element in faithful mode correctly gate when <pre> becomes a Markdown code block versus raw HTML, while using chain.walk_children for content in the translated path.

src/element_handler/anchor.rs (1)

32-48: Remove redundant .into() to fix clippy failure

The code at anchor.rs:48 calls .into() on chain.walk_children(element.node), which already returns a HandlerResult. Since the walk_children method signature returns HandlerResult directly, wrapping it in Some() already produces the correct return type Option<HandlerResult>, making the .into() call a useless conversion that triggers clippy::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 consistent

The updates to thread chain through code_handler, handle_code_block, and handle_inline_code are 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 by is_code_block.

I don’t see functional regressions in these modified sections.

Also applies to: 45-83, 112-148

Comment on lines +126 to 141
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());
}

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

⚠️ Potential issue | 🟠 Major

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 HandlerResult from walk_children, and
  • Adding a Faithful guard keyed off that result, then
  • Returning a HandlerResult that preserves result.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.

@coderabbitai coderabbitai Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

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 &usize into a usize, 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.handle for <caption> can return markdown_translated == false when the caption contains HTML we can’t render as Markdown. Because all_children_translated isn’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 into all_children_translated so 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 content

Using chain.walk_children(element.node).content and then trimming via trim_ascii_whitespace followed by trim_matches('\n') keeps the old normalization behavior while aligning with the new Chain API. The extra trim_matches('\n') after trim_ascii_whitespace is slightly redundant but not harmful.

This still assumes element.tag is always an hN-style tag (due to nth(1).unwrap()); if that invariant ever relaxes, you may want a safe parse path instead of unwrap.

📜 Review details

Configuration used: CodeRabbit UI

Review profile: CHILL

Plan: Pro

📥 Commits

Reviewing files that changed from the base of the PR and between 15a1e2f and aee34da.

📒 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_blocks preserves the previous join_contents logic and is still pub(crate), so the rename is purely internal and safe as long as all in-crate call sites are updated (as in list.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 behavior

Switching to chain.walk_children(element.node).content and threading chain into serialize_if_faithful! aligns this handler with the new pipeline. The leading \n trim 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_children normalizes child content identically to the old Element.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_children

Threading chain into serialize_if_faithful! and deriving content via chain.walk_children(element.node).content with surrounding \n\n … \n\n preserves 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 intentional

The refactor to:

  • pass chain through, and
  • derive markdown content via chain.walk_children(element.node).content

is consistent with the rest of the PR.

The key behavioral change is the markdown_translatable guard: in Faithful mode you now require the parent to be a Document node, whereas in Pure mode 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 cases

These changes align element serialization with the new Chain-based traversal:

  • handle_or_serialize_by_parent now takes chain and:
    • falls back to serialize_element(chain, element) when the parent tag check fails in Faithful mode,
    • otherwise uses chain.walk_children(element.node).content trimmed of \n and wrapped with \n\n…\n\n.
  • serialize_element now accepts chain and, for non-block elements, writes out chain.walk_children(element.node).content directly into the HTML serializer, matching the “raw HTML inline with Markdown children” comment.
  • serialize_if_faithful! is correctly updated to accept $chain and forward it to serialize_element, so all callers consistently use the same fallback path.

Assuming Chain::walk_children only walks children (not the element itself) and preserves the same normalization that the old Element.content had, 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 newline
  • ol_li (line 32): concat_strings!("\n", content, "\n") — has trailing newline

However, this asymmetry is functionally inconsequential. The join_blocks() function (lines 98–131 in text_util.rs) normalizes item joining by:

  1. Stripping trailing newlines from the accumulated result
  2. Stripping leading newlines from each new item
  3. 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 3 for UL, 1. Item 1\n2. Item 2 for 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.

@letmutex
letmutex merged commit ee96b37 into main Nov 20, 2025
@letmutex
letmutex deleted the refactor-walk-children branch November 20, 2025 12:12
@letmutex letmutex mentioned this pull request Nov 20, 2025
2 tasks done
This was referenced Dec 9, 2025
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant