Skip to content

Refactor element handlers - #60

Merged
letmutex merged 18 commits into
mainfrom
optimize-handlers
Nov 15, 2025
Merged

letmutex merged 18 commits into
mainfrom
optimize-handlers

Conversation

@letmutex

@letmutex letmutex commented Nov 15, 2025 •

Copy link
Copy Markdown
Owner

ElementHandler Refactoring Part 2

Summary by CodeRabbit

  • Documentation

    • README example updated to show custom tag handlers returning a single Option value.
  • Refactor

    • Handler API unified: element handlers now produce a single structured optional result; serialization and content-joining behavior reorganized, with public builder/handler signatures updated.
  • Tests

    • Tests updated to the new handler semantics; added ordered-list test for start values ≤ 0.
  • Chores

    • Release builds now include debug symbols; benchmark runner logs results before README updates; ignore list refreshed.

@coderabbitai

coderabbitai Bot commented Nov 15, 2025 •

Copy link
Copy Markdown
Contributor

Walkthrough

Replaces tuple-based handler returns with a unified HandlerResult { content: String, markdown_translated: bool }; updates ElementHandler/Chain/ElementHandlers to return Option<HandlerResult>; threads HandlerResult through dom walker and element handlers; extracts element serialization to element_util; adds text_util::join_contents; updates examples, tests, benches, and Cargo release profile.

Changes

Cohort / File(s) Summary
Build & Config
Cargo.toml
Adds [profile.release] with debug = true.
Docs & Examples
README.md, examples/simple/main.rs
README and example updated to show handlers returning Option/Option<HandlerResult> (e.g., Some("...".into())) instead of (Option<String>, bool).
Benchmarks
benches/bench.ts, benches/README.md
Logs benchmark result before persisting, passes trimmed result to README writer, and updates README metadata/preface.
Core handler API
src/element_handler/mod.rs, src/lib.rs
Introduces HandlerResult with From impls; changes ElementHandler trait to handle(...) -> Option<HandlerResult>; Chain/ElementHandlers now propagate HandlerResult; removes Arc<Options> usage; narrows Element.skipped_handlers visibility.
Element serialization & utilities
src/element_handler/element_util.rs, src/text_util.rs, src/node_util.rs
Adds serialize_element, handle_or_serialize_by_parent, and serialize_if_faithful!; adds pub(crate) fn join_contents(contents: &[String]) -> String; removes is_parent_handler and related faithful-mode parent checks.
Element handlers (bulk)
src/element_handler/{anchor,blockquote,br,caption,code,emphasis,head_body,headings,hr,html,img,li,list,p,pre,table,tbody,td_th,thead,tr}.rs
All handlers now return Option<HandlerResult>; tuple returns removed; handlers construct/return HandlerResult (via .into() or struct); many delegate to element_util helpers; imports adjusted.
List & table logic
src/element_handler/list.rs, src/element_handler/table.rs
Adds OL helpers (ListChildContent, get_ol_content, add_ol_li_marker, digits) and OL formatting; table extraction updated to consume HandlerResult and use res.content; faithful-mode table paths return HandlerResult.
DOM walker integration
src/dom_walker.rs
Replaces tuple handling with Option<HandlerResult> flow; uses join_contents and conditionally pushes res.content while honoring res.markdown_translated.
Tests
tests/basic_tests.rs, tests/list_tests.rs
Tests adapted to handlers returning Option (use None instead of (None, true)); adds ordered_lists_start_with_zero_or_negative test; builder.add_handler signatures updated.
Misc & Repo files
.gitignore, benches/*
Minor .gitignore edits; bench artifacts and README updated.

Sequence Diagram(s)

sequenceDiagram
    participant DW as DomWalker
    participant CH as Chain / ElementHandlers
    participant H as ElementHandler
    participant R as HandlerResult

    rect rgb(250,250,255)
    Note over DW,CH: Old flow (tuple-based)
    DW->>CH: proceed(node)
    CH->>H: on_visit(chain, element)
    H-->>CH: (Some(content), bool)
    CH-->>DW: (content, bool)
    end

    rect rgb(245,255,245)
    Note over DW,CH: New flow (HandlerResult)
    DW->>CH: proceed(node)
    CH->>H: handle(chain, element)
    H-->>CH: Some(HandlerResult{content, markdown_translated})
    CH-->>DW: Option<HandlerResult>
    DW->>DW: if res.markdown_translated then push(res.content) else emit serialized HTML
    end

    rect rgb(255,250,240)
    Note right of R: Unified return: content + markdown_translated\nreduces boolean plumbing across callers
    end
Loading

Estimated code review effort

🎯 4 (Complex) | ⏱️ ~60 minutes

  • Areas needing extra attention:
    • src/element_handler/mod.rs — HandlerResult definition, trait/signature changes, dispatch plumbing.
    • src/element_handler/element_util.rs — serialize_element, newline normalization, serialize_if_faithful! macro semantics.
    • src/element_handler/list.rs & src/element_handler/table.rs — OL helpers, marker logic, and table cell extraction using res.content.
    • src/dom_walker.rs & src/text_util.rs — join_contents correctness and buffer edge cases.
    • Verify all handlers and call sites no longer use tuple returns and consistently inspect HandlerResult.markdown_translated.

Possibly related PRs

  • Enhanced ElementHandler API #59 — Prior refactor introducing Chain-based API and handler signature changes; strongly related to this PR’s continuation of handler-signature and traversal changes.

Poem

🐰
I nibbled tuples, stitched a tidy part,
HandlerResult now holds content and heart.
I join the strings and hush the noisy flags,
Hoplight trims newlines, fixes ragged tags.
Hop — the Markdown meadow blooms smart!

Pre-merge checks and finishing touches

❌ Failed checks (1 warning)
Check name Status Explanation Resolution
Docstring Coverage ⚠️ Warning Docstring coverage is 15.79% 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
Title check ✅ Passed The pull request title 'Refactor element handlers' accurately describes the main change—a comprehensive refactoring of element handler implementations throughout the codebase, including API changes from tuple-based returns to structured HandlerResult types.
Description Check ✅ Passed Check skipped - CodeRabbit’s high-level summary is enabled.
✨ 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 optimize-handlers

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

@letmutex

Copy link
Copy Markdown
Owner Author

@coderabbitai summary

@coderabbitai

coderabbitai Bot commented Nov 15, 2025

Copy link
Copy Markdown
Contributor
✅ Actions performed

Summary regeneration triggered.

@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: 2

🧹 Nitpick comments (8)
src/text_util.rs (1)

106-134: Consider optimizing memory allocations in join_contents.

The function creates a new String with recalculated capacity on each iteration (line 131: result = next_result), leading to O(n) allocations for n non-empty strings. While functional, this could impact performance when joining many content pieces.

Consider either:

  1. Pre-calculating total capacity before the loop
  2. Reusing the existing result String by calculating only the additional capacity needed

Example optimization:

 pub(crate) fn join_contents(contents: &[String]) -> String {
-    let mut result = String::new();
+    // Pre-calculate approximate capacity
+    let total_capacity: usize = contents.iter().map(|s| s.len()).sum();
+    let mut result = String::with_capacity(total_capacity);
+    
     for content in contents {
         let content_len = content.len();
         if content_len == 0 {
             continue;
         }
 
-        let result_len = result.len();
-
-        let left = result.trim_end_matches('\n');
-        let right = content.trim_start_matches('\n');
-
-        let max_trimmed_new_lines =
-            std::cmp::max(result_len - left.len(), content_len - right.len());
-        let separator_new_lines = std::cmp::min(max_trimmed_new_lines, 2);
-        let separator = "\n".repeat(separator_new_lines);
-
-        let mut next_result = String::with_capacity(left.len() + separator.len() + right.len());
-        next_result.push_str(left);
-        next_result.push_str(&separator);
-        next_result.push_str(right);
-
-        result = next_result;
+        if !result.is_empty() {
+            let result_len = result.len();
+            let left_trim = result.trim_end_matches('\n');
+            let right_trim = content.trim_start_matches('\n');
+            
+            // Truncate result to remove trailing newlines
+            result.truncate(left_trim.len());
+            
+            let max_trimmed_new_lines =
+                std::cmp::max(result_len - left_trim.len(), content_len - right_trim.len());
+            let separator_new_lines = std::cmp::min(max_trimmed_new_lines, 2);
+            
+            for _ in 0..separator_new_lines {
+                result.push('\n');
+            }
+            result.push_str(right_trim);
+        } else {
+            result.push_str(content);
+        }
     }
     result
 }
src/element_handler/thead.rs (1)

1-6: thead_handler refactor looks correct; Vec allocation could be optimized later

The move to Option<HandlerResult> plus delegating to handle_or_serialize_by_parent matches the new handler pattern and should preserve behavior, given you pass through element.markdown_translated and still gate with serialize_if_faithful!. The only minor concern is the per‑call vec!["table"] allocation; if handle_or_serialize_by_parent is used heavily, consider changing its parameter to &[&str] so callers can pass &["table"] without allocating.

Also applies to: 8-13

src/dom_walker.rs (1)

6-7: HandlerResult integration in walk_node looks sound; join_contents use is appropriate

Switching to text_util::join_contents and feeding its result into handlers.handle before truncating the buffer keeps the previous “collect children → compute Element.content → replace with handler output” pattern, and updating markdown_translated from res.markdown_translated aligns with the new HandlerResult‑centric flow. If you want a tiny readability tweak, you could bind join_contents(&buffer[prev_buffer_len..]) to a local content variable before the handle call, but functionally this looks correct.

Also applies to: 75-82, 85-89

src/element_handler/head_body.rs (1)

1-5: head_body_handler correctly uses handle_or_serialize_by_parent; small Vec nit

The new Option<HandlerResult> signature and delegation to handle_or_serialize_by_parent with "html" as the allowed parent look consistent with the overall refactor. Similar to other handlers, this currently allocates a Vec via vec!["html"] on every call; if handle_or_serialize_by_parent is ever updated to take &[&str], you can then pass &["html"] and avoid that allocation.

Also applies to: 7-8

src/element_handler/tr.rs (1)

1-6: tr_handler refactor matches the new pattern; consider tfoot and Vec allocation

The tr_handler change to Option<HandlerResult> plus serialize_if_faithful! → handle_or_serialize_by_parent mirrors the other table handlers and should preserve behavior. Two small follow‑ups you might consider:

  • If you want <tr> under <tfoot> to be markdown‑translated in faithful mode as well, add "tfoot" to the allowed parent list.
  • As with other handlers, switching handle_or_serialize_by_parent to accept &[&str] would let you replace &vec!["tbody", "thead"] with &["tbody", "thead"] and avoid per‑call allocations.

Also applies to: 8-16

src/element_handler/td_th.rs (1)

1-11: HandlerResult migration looks correct; consider avoiding per-call Vec allocation

The td/th handler correctly uses serialize_if_faithful! and delegates to handle_or_serialize_by_parent, and the new Option<HandlerResult> signature aligns with the rest of the handler API.

Given the PR’s performance goal, you might later consider changing handle_or_serialize_by_parent to accept &[&str] so callers can pass a static slice (e.g. &["tr"]) instead of allocating vec!["tr"] on every call. This is non-blocking but would remove a tiny allocation on hot paths.

src/element_handler/mod.rs (2)

55-77: Consider deriving common traits on HandlerResult

HandlerResult is central to the new API. Deriving a few standard traits would make debugging and testing easier without changing semantics.

Example:

-/// The processing result of a [ElementHandler]
-pub struct HandlerResult {
+/// The processing result of an [ElementHandler].
+#[derive(Debug, Clone, PartialEq, Eq)]
+pub struct HandlerResult {
     pub content: String,
     pub markdown_translated: bool,
 }

The From<String> / From<&str> impls look correct and ergonomically encode markdown_translated = true for Markdown-producing paths.


79-86: ElementHandler API update looks good; consider aligning append with HandlerResult

The switch to fn handle(&self, chain: &dyn Chain, element: Element) -> Option<HandlerResult> together with the blanket impl<F> ElementHandler for F keeps handler ergonomics intact and object safety preserved; no functional issues here.

One design nit: append still returns Option<String> while handle now returns Option<HandlerResult>. If append content is conceptually “more of the same output”, you may want to either:

  • Clarify in docs that append is always Markdown and intentionally bypasses HandlerResult, or
  • Change it to Option<HandlerResult> for a fully consistent handler contract.

This is purely an API consistency concern; behavior today is fine.

Also applies to: 93-100

📜 Review details

Configuration used: CodeRabbit UI

Review profile: CHILL

Plan: Pro

📥 Commits

Reviewing files that changed from the base of the PR and between 17f4f85 and fd6f22d.

📒 Files selected for processing (31)
  • Cargo.toml (1 hunks)
  • README.md (1 hunks)
  • benches/bench.ts (2 hunks)
  • examples/simple/main.rs (1 hunks)
  • src/dom_walker.rs (3 hunks)
  • src/element_handler/anchor.rs (4 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 (6 hunks)
  • src/element_handler/element_util.rs (1 hunks)
  • src/element_handler/emphasis.rs (2 hunks)
  • src/element_handler/head_body.rs (1 hunks)
  • src/element_handler/headings.rs (2 hunks)
  • src/element_handler/hr.rs (1 hunks)
  • src/element_handler/html.rs (2 hunks)
  • src/element_handler/img.rs (3 hunks)
  • src/element_handler/li.rs (2 hunks)
  • src/element_handler/list.rs (2 hunks)
  • src/element_handler/mod.rs (8 hunks)
  • src/element_handler/p.rs (1 hunks)
  • src/element_handler/pre.rs (2 hunks)
  • src/element_handler/table.rs (7 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 (5 hunks)
  • src/node_util.rs (0 hunks)
  • src/text_util.rs (1 hunks)
  • tests/basic_tests.rs (2 hunks)
💤 Files with no reviewable changes (1)
  • src/node_util.rs
🧰 Additional context used
🧬 Code graph analysis (17)
src/element_handler/caption.rs (1)
src/element_handler/element_util.rs (1)
  • handle_or_serialize_by_parent (12-35)
src/element_handler/tr.rs (1)
src/element_handler/element_util.rs (1)
  • handle_or_serialize_by_parent (12-35)
src/element_handler/li.rs (1)
src/node_util.rs (2)
  • get_node_tag_name (5-11)
  • get_parent_node (13-24)
src/element_handler/td_th.rs (1)
src/element_handler/element_util.rs (1)
  • handle_or_serialize_by_parent (12-35)
src/element_handler/code.rs (2)
src/element_handler/element_util.rs (1)
  • serialize_element (39-169)
src/node_util.rs (2)
  • get_node_tag_name (5-11)
  • get_parent_node (13-24)
src/element_handler/anchor.rs (1)
src/element_handler/mod.rs (5)
  • handle (85-85)
  • handle (97-99)
  • handle (244-291)
  • handle (302-302)
  • handle (317-325)
src/lib.rs (1)
src/element_handler/mod.rs (1)
  • new (109-230)
src/element_handler/tbody.rs (1)
src/element_handler/element_util.rs (1)
  • handle_or_serialize_by_parent (12-35)
src/element_handler/element_util.rs (2)
src/dom_walker.rs (1)
  • is_block_element (400-402)
src/node_util.rs (1)
  • parent_tag_name_equals (27-36)
src/element_handler/html.rs (1)
src/element_handler/element_util.rs (1)
  • serialize_element (39-169)
src/element_handler/list.rs (4)
src/element_handler/element_util.rs (1)
  • serialize_element (39-169)
src/node_util.rs (2)
  • get_node_tag_name (5-11)
  • get_parent_node (13-24)
src/text_util.rs (2)
  • indent_text_except_first_line (178-197)
  • join_contents (108-134)
src/element_handler/mod.rs (1)
  • new (109-230)
src/element_handler/pre.rs (2)
src/element_handler/element_util.rs (1)
  • serialize_element (39-169)
src/node_util.rs (1)
  • get_node_tag_name (5-11)
src/element_handler/table.rs (1)
src/element_handler/element_util.rs (1)
  • serialize_element (39-169)
src/element_handler/thead.rs (1)
src/element_handler/element_util.rs (1)
  • handle_or_serialize_by_parent (12-35)
src/dom_walker.rs (1)
src/text_util.rs (1)
  • join_contents (108-134)
src/element_handler/head_body.rs (1)
src/element_handler/element_util.rs (1)
  • handle_or_serialize_by_parent (12-35)
src/element_handler/mod.rs (6)
src/dom_walker.rs (1)
  • walk_node (17-103)
src/element_handler/element_util.rs (1)
  • serialize_element (39-169)
src/element_handler/p.rs (1)
  • p_handler (8-11)
src/element_handler/pre.rs (1)
  • pre_handler (10-34)
src/element_handler/table.rs (1)
  • table_handler (18-153)
src/lib.rs (3)
  • new (87-94)
  • new (164-171)
  • options (174-177)
🔇 Additional comments (26)
benches/bench.ts (2)

20-23: Good refactor for observability, but inconsistent with PR objectives.

The extraction of the result into an intermediate variable and the addition of logging improve code clarity and debugging. However, these changes don't appear to relate to the stated PR objectives ("Better element handler APIs" and "Fix performance"), which describe Rust handler API refactoring. This file only contains TypeScript benchmark script improvements.


50-50: LGTM: Markdown formatting fix.

Removing the leading hyphen corrects the markdown formatting, as the line should not render as a list item.

Cargo.toml (1)

29-30: Verify that debug symbols in release builds are intentional.

Enabling debug symbols in release builds significantly increases binary size. While this can be useful for profiling and debugging performance issues, it's unusual for production releases.

Is this temporary for performance investigation, or intended to be permanent? If temporary, consider documenting this or adding a TODO comment.

examples/simple/main.rs (1)

30-32: LGTM!

The custom handler correctly uses the new API, returning Option<HandlerResult> via the .into() conversion. This is more ergonomic than the previous tuple-based return.

README.md (1)

65-65: LGTM!

Documentation accurately reflects the simplified custom handler API, showing the new Option<HandlerResult> return type via .into().

src/element_handler/p.rs (1)

1-11: LGTM!

The refactoring correctly updates the paragraph handler to return Option<HandlerResult> instead of a tuple. The use of .into() for the conversion is idiomatic and leverages the From<String> implementation.

src/element_handler/blockquote.rs (1)

1-17: LGTM!

The blockquote handler correctly implements the new HandlerResult-based API. The refactoring maintains the existing logic while improving the API surface.

src/element_handler/pre.rs (1)

1-34: LGTM!

The pre handler correctly handles both code paths:

  • Line 27: Uses .into() for markdown-translated content
  • Lines 29-32: Explicitly constructs HandlerResult with markdown_translated: false for serialized HTML content

The refactoring maintains the existing logic while using the new HandlerResult type.

src/element_handler/caption.rs (1)

1-11: LGTM!

The caption handler correctly migrates to the new API using handle_or_serialize_by_parent helper. This encapsulates the parent-checking logic and returns the appropriate HandlerResult.

src/element_handler/br.rs (1)

1-6: br_handler correctly adopts HandlerResult, relying on Into semantics

The handler now cleanly returns Option<HandlerResult> and keeps the existing BrStyle‑based newline behavior, with serialize_if_faithful! still guarding faithful mode. As long as the Into<HandlerResult> impl for string types sets markdown_translated as expected (likely true here), this change is consistent with the new API.

Also applies to: 8-14

tests/basic_tests.rs (1)

533-571: Tests correctly reflect new Option<HandlerResult> handler semantics

The updated custom-handler tests for <img> look good:

  • with_custom_rules uses |_, _| None to fully skip images, and the empty Markdown expectation matches the new contract.
  • with_custom_rules_and_fallback cleanly demonstrates conditional None vs chain.proceed(element) and verifies that the built‑in image handler is still used when the condition matches.

Nice coverage of both the “skip” and “fallback” paths under the new API.

src/element_handler/anchor.rs (1)

5-77: Anchor handler’s move to Option<HandlerResult> is consistent and preserves behavior

The updated AnchorElementHandler cleanly switches to handle(&self, _chain, element) -> Option<HandlerResult>:

  • The no‑href case now returns Some(element.content.into()), which matches the previous “pass content through” behavior.
  • All link cases return Some(md.into()), aligning with the HandlerResult conversions used elsewhere.
  • Faithful-mode fallback via serialize_if_faithful! remains intact.

I don’t see any behavioral regressions here.

src/lib.rs (2)

35-54: Visibility change for Element::skipped_handlers may be a breaking API change

Changing skipped_handlers from pub to pub(crate) tightens the public API. This is an improvement for encapsulation but will break any downstream code that accessed this field directly.

If you consider Element part of the public surface, please double‑check that you’re comfortable with this as a breaking change (and bump versioning accordingly) or, alternatively, expose any needed functionality via methods instead of the field.


85-219: Owned Options and new skip_tags handler semantics look good

The changes to HtmlToMarkdown::new / HtmlToMarkdownBuilder::new and options():

  • Construct ElementHandlers with owned Options and store them directly, which matches the refactored ElementHandlers::new(options: Options) and removes unnecessary Arc indirection.
  • Updating self.handlers.options in options() keeps all element handlers reading the latest configuration via element.options.

For skipping tags:

  • skip_tags now uses .add_handler(tags, |_: &dyn Chain, _: Element| None), and the doc example mirrors this. Under the new API, None correctly represents “produce no output for this element,” which aligns with how tests exercise custom handlers.

This all looks consistent with the new Option<HandlerResult> contract.

src/element_handler/img.rs (1)

3-59: Verify compilation status and apply idiom improvement

The borrow-checker concern cannot be definitively verified without running rustc in this environment. However:

  1. If the code compiles as-is: the suggested fix using as_deref().unwrap_or("") is still strongly recommended—it's more idiomatic, avoids creating temporary String objects, and relies on the static lifetime of the empty string literal.

  2. If the code fails to compile: the fix is necessary. Apply the suggested change to use as_deref().unwrap_or("") instead of as_ref().unwrap_or(&String::new()) for both alt and link at lines ~48 and ~50.

Please verify locally with cargo check whether compilation succeeds with the current code, and apply the fix if needed (or if you want to adopt the more idiomatic pattern regardless).

src/element_handler/tbody.rs (1)

1-6: tbody handler correctly delegates to shared parent-aware utility

The refactor to Option<HandlerResult> and delegation to handle_or_serialize_by_parent cleanly centralizes the faithful vs markdown behavior for <tbody> and keeps the handler itself minimal. Looks good.

Also applies to: 8-12

src/element_handler/html.rs (1)

5-6: Root detection and HandlerResult shaping in html_handler look sound

The faithful-mode root check via get_parent_node/NodeData::Document matches the “only root html is markdown-translatable” intent, and the two return paths (.into() for markdown vs explicit serialize_element with markdown_translated: false) are consistent with the new handler API.

Also applies to: 11-31

src/element_handler/element_util.rs (1)

39-168: Shared serialize_element and serialize_if_faithful! look consistent with existing semantics

The split between inline vs block serialization, plus the newline-normalization for blocks, matches the provided earlier implementation, and the macro-based early return in faithful mode integrates cleanly with HandlerResult. Centralizing these pieces here should simplify the other handlers without changing behavior.

src/element_handler/li.rs (1)

3-5: list_item_handler correctly separates <ol> and <ul> behavior under the new API

The refactor preserves the existing list formatting logic while cleanly routing ordered items via the parent tag check and returning HandlerResult via .into(). The early serialize_if_faithful! guard also keeps faithful-mode HTML fallback centralized.

Also applies to: 10-38

src/element_handler/headings.rs (1)

2-7: Headings handler migration to HandlerResult preserves formatting behavior

The handler still computes heading level and chooses Setext vs ATX styles as before, and wrapping the final string in HandlerResult via .into() integrates smoothly with the new handler API and the faithful-mode macro.

Also applies to: 9-29

src/element_handler/mod.rs (6)

6-6: Module wiring and imports match the new design

The new element_util module and added imports (walk_node, serialize_element, Node, Rc) line up with how this file now uses them; I don’t see any correctness or style issues here.

Also applies to: 24-28, 45-48


102-113: Owning Options directly in ElementHandlers is reasonable

Storing Options by value and taking it by value in ElementHandlers::new simplifies ownership and removes Arc overhead. Given the usage in src/lib.rs (construct once and mutate via handlers.options = options), this looks correct and should be a minor perf win.

Just confirm that ElementHandlers isn’t intended to be cheaply cloned/shared across threads anymore; if it is, you may want an explicit Clone on Options or a builder that clones as needed.


244-291: Handler dispatch and faithful fallback logic look correct

Routing through ElementHandlers::handle now returning Option<HandlerResult> is consistent with the rest of the refactor:

  • The rules lookup with .filter(...).rev().nth(skipped_handlers) preserves the “last registered wins, with proceed walking backwards” semantics.
  • In the Some(rule) case, the constructed Element passes all the expected fields, including skipped_handlers, into the handler.
  • In the None case:
    • For TranslationMode::Faithful, you serialize the element to HTML and correctly set markdown_translated: false.
    • For other modes, Some(content.into()) uses the From<&str> impl and marks the already-produced content as Markdown, which matches expectations.

I don’t see functional issues in this method; the behavior matches how walk_node and the downstream handlers consume HandlerResult.


295-326: Chain trait and its ElementHandlers impl integrate cleanly with walk_node

The updated Chain methods:

  • proceed correctly increments skipped_handlers and delegates back into ElementHandlers::handle, preserving the handler-chaining behavior.
  • handle wraps dom_walker::walk_node and returns a single HandlerResult with the joined buffer and the subtree’s markdown_translated flag, which matches how callers like table_handler now consume it.

There’s no recursion bug here (the walk_node calls the multi-arg ElementHandlers::handle, not Chain::handle), and the Option is consistently Some for this implementation, which is fine.


328-337: block_handler correctly distinguishes pure vs faithful modes

The new block_handler implementation maps cleanly onto HandlerResult:

  • In TranslationMode::Pure, it emits Markdown-wrapped content via concat_strings! and Into<HandlerResult>, marking it as translated.
  • Otherwise, it serializes to HTML via serialize_element and explicitly sets markdown_translated: false, which is what faithful/raw HTML handling expects.

No issues here; behavior is clear and aligned with the surrounding design.


339-345: bold_handler and italic_handler correctly forward to emphasis_handler

Both handlers now return Option<HandlerResult> and simply delegate to emphasis_handler with the appropriate markers ("**" and "*"), keeping the behavior centralized. Types and delegation look consistent with the new API.

Comment thread src/element_handler/element_util.rs Resolved
Comment thread src/element_handler/list.rs Resolved
letmutex and others added 2 commits November 15, 2025 18:50
Co-authored-by: coderabbitai[bot] <136622811+coderabbitai[bot]@users.noreply.github.com>

@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: 3

📜 Review details

Configuration used: CodeRabbit UI

Review profile: CHILL

Plan: Pro

📥 Commits

Reviewing files that changed from the base of the PR and between 6d00c60 and 67d9f3c.

📒 Files selected for processing (1)
  • src/element_handler/list.rs (2 hunks)
🧰 Additional context used
🧬 Code graph analysis (1)
src/element_handler/list.rs (3)
src/element_handler/element_util.rs (1)
  • serialize_element (39-169)
src/node_util.rs (2)
  • get_node_tag_name (5-11)
  • get_parent_node (13-24)
src/text_util.rs (2)
  • indent_text_except_first_line (178-197)
  • join_contents (108-134)
🔇 Additional comments (1)
src/element_handler/list.rs (1)

43-53: Previous borrow issue has been resolved.

The temporary borrow issue flagged in the previous review has been correctly fixed by using owned strings. The logic now properly handles both ol and other list elements with appropriate trimming and newline spacing.

Comment thread src/element_handler/list.rs Resolved
Comment thread src/element_handler/list.rs Resolved
Comment thread src/element_handler/list.rs Resolved

@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

♻️ Duplicate comments (2)
src/element_handler/list.rs (2)

113-117: Fix digits(0) returning 0.

The past review correctly identified that digits(0) returns 0 instead of 1. This bug persists in the current code:

  • log10(1) = 0.0, ceil(0.0) = 0, cast to usize gives 0
  • The string "0" has 1 digit, not 0
  • This causes incorrect spacing calculation at line 127 and potential underflow

While this may not be reachable for non-empty lists, it's a latent bug for edge cases (e.g., if li_count = 0 leads to highest_index = 0).

Apply one of these fixes from the previous review:

Option 1 (explicit check):

 fn digits(num: usize) -> usize {
-    ((num + 1) as f32).log10().ceil() as usize
+    if num == 0 {
+        1
+    } else {
+        ((num + 1) as f32).log10().ceil() as usize
+    }
 }

Option 2 (use max):

 fn digits(num: usize) -> usize {
-    ((num + 1) as f32).log10().ceil() as usize
+    ((num + 1) as f32).log10().ceil().max(1.0) as usize
 }

119-131: Prevent potential underflow in spacing calculation.

Line 127's spacing calculation can underflow if:

  1. digits(highest_index) returns 0 (the bug flagged in the previous comment)
  2. ol_number_spacing is set to a small value (default is 2, but users can configure it)
  3. index_str.len() exceeds ol_number_spacing + digits(highest_index)

The subtraction would panic in debug mode or wrap in release mode.

Apply this diff to use saturating arithmetic:

 fn add_ol_li_marker(
     options: &Options,
     content: &str,
     index: usize,
     highest_index: usize,
 ) -> String {
     let index_str = index.to_string();
-    let spacing =
-        " ".repeat(options.ol_number_spacing as usize + digits(highest_index) - index_str.len());
+    let spacing_width = (options.ol_number_spacing as usize + digits(highest_index))
+        .saturating_sub(index_str.len());
+    let spacing = " ".repeat(spacing_width);
     let content = content.trim_start_matches('\n');
     let content = indent_text_except_first_line(content, index_str.len() + 1 + spacing.len(), true);
     concat_strings!("\n", index_str, ".", spacing, content)
 }
🧹 Nitpick comments (1)
src/element_handler/list.rs (1)

61-111: Consider following the suggested pattern from the previous review.

While line 69's .max(1) clamp correctly prevents underflow, line 96's pattern (curr_li_idx = start_idx - 1 followed by increment before use) is less clear than the pattern suggested in the previous review. The past review recommended starting with curr_li_idx = start_idx and incrementing at the beginning of the usage block for better readability.

Apply this diff to follow the cleaner pattern:

-    let mut curr_li_idx = start_idx - 1;
+    let mut curr_li_idx = start_idx;
 
     let contents = buffer
         .into_iter()
         .map(|content| {
             if content.is_li {
-                curr_li_idx += 1;
-                add_ol_li_marker(element.options, &content.text, curr_li_idx, highest_index)
+                let marker = add_ol_li_marker(element.options, &content.text, curr_li_idx, highest_index);
+                curr_li_idx += 1;
+                marker
             } else {
                 content.text
             }
📜 Review details

Configuration used: CodeRabbit UI

Review profile: CHILL

Plan: Pro

📥 Commits

Reviewing files that changed from the base of the PR and between 67d9f3c and 406b961.

📒 Files selected for processing (4)
  • .gitignore (1 hunks)
  • benches/README.md (1 hunks)
  • src/element_handler/list.rs (2 hunks)
  • tests/list_tests.rs (1 hunks)
🧰 Additional context used
🧬 Code graph analysis (2)
tests/list_tests.rs (2)
src/lib.rs (3)
  • builder (104-106)
  • default (80-82)
  • default (157-159)
src/options.rs (1)
  • default (22-37)
src/element_handler/list.rs (4)
src/element_handler/element_util.rs (1)
  • serialize_element (39-169)
src/node_util.rs (2)
  • get_node_tag_name (5-11)
  • get_parent_node (13-24)
src/text_util.rs (2)
  • indent_text_except_first_line (178-197)
  • join_contents (108-134)
src/element_handler/mod.rs (1)
  • new (109-230)
🪛 markdownlint-cli2 (0.18.1)
benches/README.md

17-17: Fenced code blocks should have a language specified

(MD040, fenced-code-language)

🔇 Additional comments (3)
.gitignore (1)

2-3: Good additions for generated artifacts.

Both additions are appropriate for the .gitignore file and align with the PR objectives:

  • output_*.md: Generated markdown files from the handler result serialization refactoring
  • flamegraph.svg: Performance profiling visualization output
tests/list_tests.rs (1)

76-104: LGTM! Good coverage of edge cases.

The test properly verifies that invalid start attribute values (zero and negative) are normalized to 1, which aligns with the implementation fix in src/element_handler/list.rs at line 69.

src/element_handler/list.rs (1)

12-54: LGTM! Handler refactor is clean.

The migration to HandlerResult is well-executed, and the delegation to get_ol_content for ordered lists properly separates concerns. The use of .to_owned() at line 46 correctly avoids the temporary borrow issue flagged in previous reviews.

Comment thread benches/README.md Resolved

@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

🧹 Nitpick comments (2)
src/element_handler/list.rs (2)

65-111: LGTM! Integer underflow properly prevented.

The start attribute parsing correctly uses .max(1) to ensure start_idx >= 1, preventing the underflow issue flagged in previous reviews. The subsequent curr_li_idx = start_idx - 1 is now safe.

Minor: Consider handling empty list edge case explicitly.

When li_count == 0, line 94 computes highest_index = start_idx - 1, which could be 0. While this doesn't cause runtime issues (because add_ol_li_marker is never called when there are no <li> elements), it's semantically inconsistent for highest_index < start_idx. Consider initializing highest_index = start_idx when li_count == 0 for clarity:

-    let highest_index = start_idx + li_count - 1;
+    let highest_index = if li_count == 0 {
+        start_idx
+    } else {
+        start_idx + li_count - 1
+    };

122-134: Consider saturating_sub for extra safety.

The spacing calculation at line 130 is currently safe because index <= highest_index ensures index_str.len() <= digits(highest_index). However, for defensive programming, consider using saturating_sub:

-    let spacing =
-        " ".repeat(options.ol_number_spacing as usize + digits(highest_index) - index_str.len());
+    let spacing_width = (options.ol_number_spacing as usize + digits(highest_index))
+        .saturating_sub(index_str.len());
+    let spacing = " ".repeat(spacing_width);

This guards against potential underflow if the function is called with unexpected parameters in the future.

📜 Review details

Configuration used: CodeRabbit UI

Review profile: CHILL

Plan: Pro

📥 Commits

Reviewing files that changed from the base of the PR and between 406b961 and 990a4bc.

📒 Files selected for processing (1)
  • src/element_handler/list.rs (2 hunks)
🧰 Additional context used
🧬 Code graph analysis (1)
src/element_handler/list.rs (3)
src/element_handler/element_util.rs (1)
  • serialize_element (39-169)
src/node_util.rs (2)
  • get_node_tag_name (5-11)
  • get_parent_node (13-24)
src/text_util.rs (2)
  • indent_text_except_first_line (178-197)
  • join_contents (108-134)
🔇 Additional comments (6)
src/element_handler/list.rs (6)

1-10: LGTM! Clean import organization.

The new imports support the HandlerResult refactoring and OL rendering logic introduced in this file.


12-37: LGTM! HandlerResult migration completed correctly.

The function signature and return statements have been properly updated to use the unified HandlerResult type, maintaining all the original faithful mode validation logic.


43-54: LGTM! Borrow of temporary fixed correctly.

The previous borrow-of-temporary issue has been properly resolved by materializing owned String values before trimming. The logic correctly handles both OL and non-OL cases.


56-59: LGTM! Clear and simple data structure.

The ListChildContent struct provides a clean abstraction for tracking list children during processing.


113-120: LGTM! Zero-case bug fixed correctly.

The digits function now correctly handles digits(0) == 1, preventing the incorrect spacing calculations and potential underflow that were flagged in previous reviews.


136-147: LGTM! Good test coverage for digits function.

The tests cover important edge cases including the zero case that was previously problematic.

@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

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/mod.rs (1)

233-248: Fix the redundant_closure warning causing CI failure in add_handler.

The or_insert_with(|| Vec::new()) pattern on line 245 triggers clippy's redundant_closure lint, which fails CI since clippy runs with --deny warnings.

The tag index maintenance logic is correct: the handler index is assigned once and appended to all tag entries, enabling proper override and Chain::proceed behavior.

Apply this fix:

-            let indices = self
-                .tag_to_handler_indices
-                .entry(tag.to_owned())
-                .or_insert_with(|| Vec::new());
+            let indices = self
+                .tag_to_handler_indices
+                .entry(tag.to_owned())
+                .or_insert_with(Vec::new);

Vec::new is a valid function reference matching the FnOnce() -> V requirement, replacing the unnecessary closure without behavior change. After applying, run cargo clippy -- --deny warnings locally to confirm the warning is resolved.

♻️ Duplicate comments (1)
benches/README.md (1)

15-24: Add language identifier to fenced benchmark output block.

The fenced block under “# Result” still has no language, which keeps triggering MD040 from markdownlint. Suggest using text (or none) to keep rendering neutral:

-```
+```text
 convert()               time:   [24.810 ms 24.847 ms 24.891 ms]
 ...




Please re-run your markdownlint job after this change to confirm the warning is gone.

</blockquote></details>

</blockquote></details>

<details>
<summary>🧹 Nitpick comments (2)</summary><blockquote>

<details>
<summary>src/lib.rs (1)</summary><blockquote>

`124-147`: **append() aggregation over handlers is correct but could be encapsulated.**

Iterating `for handler in &self.handlers.handlers` and aggregating `append()` output works and preserves the intended “post-processing” behavior (e.g., link footnotes), but it couples `HtmlToMarkdown` to the internal `handlers` vec layout. A small helper on `ElementHandlers` like `fn collect_append(&self) -> String` would hide this detail and keep `HtmlToMarkdown` oblivious to the storage shape.



If you plan more internal changes to `ElementHandlers` (e.g., different storage), consider adding such a helper now to avoid touching the public converter again later.

</blockquote></details>
<details>
<summary>src/element_handler/mod.rs (1)</summary><blockquote>

`55-79`: **HandlerResult design is coherent with the new handler flow.**

The `HandlerResult { content, markdown_translated }` struct plus `From<String>` / `From<&str>` (defaulting `markdown_translated: true`) line up well with how `dom_walker` propagates translation state and how most handlers return fully‑markdown content. This should make handler implementations simpler and less error‑prone than the previous tuple type.



If you anticipate debugging handlers often, consider deriving `Debug` (and maybe `Clone`) on `HandlerResult` to ease inspection, then re-run your tests to ensure no trait bounds are accidentally tightened.

</blockquote></details>

</blockquote></details>

<details>
<summary>📜 Review details</summary>

**Configuration used**: CodeRabbit UI

**Review profile**: CHILL

**Plan**: Pro

<details>
<summary>📥 Commits</summary>

Reviewing files that changed from the base of the PR and between 990a4bc9fc421b025abe616a9523eff725700087 and 639d9a7ade6fbea4eae5af5d0b5170da32aa7f46.

</details>

<details>
<summary>📒 Files selected for processing (3)</summary>

* `benches/README.md` (1 hunks)
* `src/element_handler/mod.rs` (7 hunks)
* `src/lib.rs` (6 hunks)

</details>

<details>
<summary>🧰 Additional context used</summary>

<details>
<summary>🧬 Code graph analysis (2)</summary>

<details>
<summary>src/lib.rs (1)</summary><blockquote>

<details>
<summary>src/element_handler/mod.rs (1)</summary>

* `new` (109-231)

</details>

</blockquote></details>
<details>
<summary>src/element_handler/mod.rs (11)</summary><blockquote>

<details>
<summary>src/dom_walker.rs (1)</summary>

* `walk_node` (17-103)

</details>
<details>
<summary>src/element_handler/element_util.rs (1)</summary>

* `serialize_element` (39-169)

</details>
<details>
<summary>src/element_handler/p.rs (1)</summary>

* `p_handler` (8-11)

</details>
<details>
<summary>src/element_handler/pre.rs (1)</summary>

* `pre_handler` (10-34)

</details>
<details>
<summary>src/element_handler/table.rs (1)</summary>

* `table_handler` (18-153)

</details>
<details>
<summary>src/element_handler/tbody.rs (1)</summary>

* `tbody_handler` (8-13)

</details>
<details>
<summary>src/element_handler/td_th.rs (1)</summary>

* `td_th_handler` (8-11)

</details>
<details>
<summary>src/element_handler/thead.rs (1)</summary>

* `thead_handler` (8-13)

</details>
<details>
<summary>src/element_handler/tr.rs (1)</summary>

* `tr_handler` (8-17)

</details>
<details>
<summary>src/element_handler/anchor.rs (3)</summary>

* `append` (20-30)
* `handle` (32-77)
* `new` (81-83)

</details>
<details>
<summary>src/lib.rs (3)</summary>

* `new` (88-95)
* `new` (165-172)
* `options` (175-178)

</details>

</blockquote></details>

</details><details>
<summary>🪛 GitHub Actions: Cargo Build & Test</summary>

<details>
<summary>src/element_handler/mod.rs</summary>

[error] 245-245: redundant closure: replace the closure with the associated function itself (Vec::new) as clippy warns about redundant_closure when using or_insert_with(|| Vec::new())

---

[error] 293-293: you seem to be trying to use `&Box<T>`. Consider using just `&T` (suggested: `&dyn ElementHandler`)

</details>

</details>
<details>
<summary>🪛 markdownlint-cli2 (0.18.1)</summary>

<details>
<summary>benches/README.md</summary>

17-17: Fenced code blocks should have a language specified

(MD040, fenced-code-language)

</details>

</details>

</details>

<details>
<summary>🔇 Additional comments (6)</summary><blockquote>

<details>
<summary>src/lib.rs (2)</summary><blockquote>

`34-55`: **Element.skipped_handlers field wiring looks consistent with Chain::proceed.**

The new `pub(crate) skipped_handlers: usize` on `Element` matches how `ElementHandlers::handle` and `Chain::proceed` pass and increment the skip count, enabling multi‑handler chaining per tag without exposing it publicly. No issues spotted with lifetimes or visibility here.



If you have custom handlers that call `Chain::proceed`, it’s worth re-running those tests to confirm they still see the expected “next handler” behavior under the new `skipped_handlers` model.

---

`163-183`: **Builder `options` and `skip_tags` behavior aligns with the new handler API.**

- `HtmlToMarkdownBuilder::new` and `.options()` correctly pass/assign `Options` by value to `ElementHandlers`.
- `.skip_tags()` now installs a handler `|_, _| None`, which cleanly drops those tags using the new `Option<HandlerResult>` signature and still leaves `markdown_translated` driven by the children (for tags that have any).

This keeps the public builder ergonomics intact with the refactored internals.



After upgrading, it’s worth re-running any code that relies on `skip_tags` in faithful vs pure translation modes to confirm the new `None`-based semantics match your expectations.

</blockquote></details>
<details>
<summary>src/element_handler/mod.rs (4)</summary><blockquote>

`81-99`: **Updated ElementHandler trait and closure impl match the HandlerResult API.**

Switching `ElementHandler::handle` to `Option<HandlerResult>` and keeping `append()` as a default no‑op is consistent with the new design, and the blanket impl for `Fn(&dyn Chain, Element) -> Option<HandlerResult>` keeps builder‑style closures ergonomic.



For any existing custom handlers, double-check their signatures now return `Option<HandlerResult>` and that they set `markdown_translated` correctly when emitting HTML instead of Markdown.

---

`101-115`: **ElementHandlers struct and constructor correctly encapsulate handler state.**

Using `handlers: Vec<Box<dyn ElementHandler>>`, `tag_to_handler_indices: HashMap<String, Vec<usize>>`, and an owned `Options` value in `ElementHandlers::new(options)` cleanly centralizes handler wiring. The `Options` ownership change aligns with the rest of the refactor (no more `Arc` here) and keeps the public API unchanged.



If any code relied on sharing `Options` by `Arc`, please confirm that the new by‑value ownership still satisfies your concurrency or sharing requirements.

---

`250-291`: **Handler dispatch and faithful/pure fallback logic look correct.**

- `ElementHandlers::handle` correctly uses `find_handler(tag, skipped_handlers)` to pick the most recently registered handler and passes through `Element { .., skipped_handlers }`, enabling `Chain::proceed` to walk earlier handlers.
- When no handler exists:
  - In `TranslationMode::Faithful`, you serialize via `serialize_element` and mark `markdown_translated: false`, which is appropriate.
  - Otherwise, you return `content.into()` and keep `markdown_translated: true`, letting pure translation drop unknown tags while preserving their converted children.

The explicit `skipped_handlers: 0` in the faithful fallback is fine since `serialize_element` ignores it.



Please ensure your faithful-vs-pure mode regression tests still pass, especially around previously unhandled tags, since this path now always goes through `serialize_element` in faithful mode.

---

`300-351`: **Chain implementation and block/emphasis helpers align with the new pipeline.**

- `Chain::proceed` reuses `ElementHandlers::handle` with `skipped_handlers + 1`, which correctly moves to the previous handler for that tag.
- `Chain::handle` walks a subtree via `walk_node` and wraps the result into a `HandlerResult`, making nested processing (e.g., in table/row handlers) straightforward.
- `block_handler`, `bold_handler`, and `italic_handler` now return `Option<HandlerResult>` and use `concat_strings!` or delegate to `emphasis_handler` appropriately, preserving prior behavior with the new API.



Given the centrality of `Chain` to custom handlers, it’s worth re-running any handler-heavy tests (tables, lists, nested quotes) to validate there are no unexpected recursion or markdown_translated propagation issues.

</blockquote></details>

</blockquote></details>

</details>

<!-- This is an auto-generated comment by CodeRabbit for review status -->

Comment thread src/element_handler/mod.rs Resolved
@letmutex
letmutex merged commit 41b7d82 into main Nov 15, 2025
@letmutex
letmutex deleted the optimize-handlers branch November 15, 2025 14:12
@letmutex letmutex mentioned this pull request Nov 15, 2025
@coderabbitai coderabbitai Bot mentioned this pull request Nov 20, 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