Skip to content

Enhanced ElementHandler API - #59

Merged
letmutex merged 4 commits into
mainfrom
chain-of-responsibility
Nov 14, 2025
Merged

letmutex merged 4 commits into
mainfrom
chain-of-responsibility

Conversation

@letmutex

@letmutex letmutex commented Nov 14, 2025 •

Copy link
Copy Markdown
Owner

The original idea is from OkHttp. This PR adds a Chain param for the ElementHandler, which can be used to:

  • Skip the current handler and delegate to the previous handler using proceed(Element)
  • Process child nodes using handle(Rc<Node>)

This will resolve #23 and introduce an enhanced ElementHandler API proposed in #57.

Status: Unstable, the added APIs are likely to change.

Summary by CodeRabbit

  • Refactor

    • Core handling now uses a chain-based model: handlers receive a processing context, can delegate or short‑circuit, and configuration is centralized for consistent behavior.
  • Documentation

    • Examples and builder docs updated to show the new handler callback signature including the processing context.
  • Tests

    • Tests updated and expanded to cover chain-based custom rules, proceed()/fallback behavior and the revised handler signatures.

@coderabbitai

coderabbitai Bot commented Nov 14, 2025 •

Copy link
Copy Markdown
Contributor

Walkthrough

Adds a public Chain trait and refactors handlers to receive (&dyn Chain, Element). Centralizes Options in ElementHandlers (Arc), moves options/skipped_handlers into Element, updates DOM traversal to use ElementHandlers/Chain, and adjusts many handler signatures, examples, and tests accordingly.

Changes

Cohort / File(s) Summary
Core architecture
src/element_handler/mod.rs, src/lib.rs, src/dom_walker.rs
Add public Chain trait and implement it for ElementHandlers; centralize Options in ElementHandlers (Arc). Refactor traversal and HtmlToMarkdown construction to use ElementHandlers / Chain. Update Element to carry options and skipped_handlers.
Element handlers (bulk)
src/element_handler/...
(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, etc.)
All handlers change signature to accept a &dyn Chain as first parameter and Element second. Many handlers read options via element.options.* instead of element.html_to_markdown.options.*. Some handlers (table, anchor, others) use chain to obtain nested content or call proceed.
DOM traversal & utilities
src/dom_walker.rs, src/node_util.rs
walk_node / walk_children signatures updated to accept &ElementHandlers / &dyn Chain usage; get_node_content removed. Node-walking now routes through ElementHandlers/Chain and reads translation_mode from element.options.
Builder, public API & structs
src/lib.rs
HtmlToMarkdownBuilder/HtmlToMarkdown signatures updated: builder no longer stores options locally, constructs ElementHandlers with Arc. HtmlToMarkdown::from_params signature changed to accept handlers only. add_handler closure type updated to `
Examples & docs
README.md, examples/simple/main.rs
Update example handler closures and documentation to new signature `
Tests
tests/basic_tests.rs
Update tests to use the new handler closure signature (`

Sequence Diagram(s)

sequenceDiagram
    participant Walker as DOM Walker
    participant Handlers as ElementHandlers\n(implements Chain)
    participant Custom as Custom Handler
    participant Default as Default Handler

    Walker->>Handlers: handle(node, tag, attrs, content, translated, skipped)
    Handlers->>Custom: on_visit(&self as Chain, element)
    alt Custom requests fallback
        Custom->>Handlers: chain.proceed(element)
        Handlers->>Default: dispatch default handler for element
        Default-->>Handlers: (Some(markdown), true)
        Handlers-->>Custom: (Some(markdown), true)
    else Custom returns or short-circuits
        Custom-->>Handlers: (Option<String>, bool)
    end
    Handlers-->>Walker: (Option<String>, bool)
Loading

Estimated code review effort

🎯 4 (Complex) | ⏱️ ~60 minutes

  • Areas needing extra attention:
    • src/element_handler/mod.rs — Chain trait, proceed() semantics, ElementHandlers implementation and thread-safety with Arc.
    • src/lib.rs — builder/HtmlToMarkdown construction, Arc wiring, and public API changes (builder examples).
    • src/element_handler/table.rs and src/element_handler/anchor.rs — nested content extraction now uses chain.
    • Tests — verify chain.proceed() fallback behavior and ensure updated handler signatures compile.

Poem

🐇 I hop through lines and link each chain,
Passing elements like carrots in my train.
Proceed if asked, or quietly yield,
Handlers dance across the field.
A rabbit cheers: modular code, well sealed.

Pre-merge checks and finishing touches

❌ Failed checks (1 warning)
Check name Status Explanation Resolution
Docstring Coverage ⚠️ Warning Docstring coverage is 36.00% which is insufficient. The required threshold is 80.00%. You can run @coderabbitai generate docstrings to improve docstring coverage.
✅ Passed checks (4 passed)
Check name Status Explanation
Description Check ✅ Passed Check skipped - CodeRabbit’s high-level summary is enabled.
Title check ✅ Passed The title 'Enhanced ElementHandler API' is directly related to the main changes in this PR, which introduce a new Chain parameter to ElementHandler methods and establish a chain-of-responsibility pattern for element handling.
Linked Issues check ✅ Passed The PR successfully implements the fallback mechanism requested in issue #23 by adding a Chain parameter with proceed() method, allowing custom handlers to delegate to previous handlers. The implementation aligns with the objectives to enable fallback behavior.
Out of Scope Changes check ✅ Passed All code changes are directly related to implementing the chain-of-responsibility pattern for ElementHandler. Changes include updating handler signatures across all element handler modules, refactoring dom_walker, and restructuring HtmlToMarkdown to support the new Chain parameter—all within scope.
✨ 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 chain-of-responsibility

📜 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 b3e89ba and bef858c.

📒 Files selected for processing (1)
  • src/element_handler/mod.rs (7 hunks)
🧰 Additional context used
🧬 Code graph analysis (1)
src/element_handler/mod.rs (4)
src/dom_walker.rs (2)
  • is_block_element (430-432)
  • walk_node (17-103)
src/lib.rs (3)
  • options (175-178)
  • new (88-95)
  • new (165-172)
src/element_handler/anchor.rs (2)
  • on_visit (32-77)
  • new (81-83)
src/element_handler/emphasis.rs (1)
  • emphasis_handler (8-33)
🔇 Additional comments (5)
src/element_handler/mod.rs (5)

233-238: LGTM: Past Clippy issue resolved.

The iterator now correctly uses .nth(skipped_handlers) instead of .skip(skipped_handlers).next(), addressing the previous pipeline failure.


297-302: LGTM: Markdown translation status now properly propagated.

The walk_node return value is now captured and returned, fixing the previous issue where the translation status was hardcoded to true. Callers will now receive accurate information about whether the subtree was successfully rendered as Markdown.


274-303: LGTM: Well-designed Chain abstraction.

The Chain trait provides a clean API for handler delegation and recursive processing. The implementation correctly:

  • Increments skipped_handlers in proceed() to delegate to earlier-registered handlers
  • Captures and returns the actual markdown_translated status from walk_node
  • Enables the chain-of-responsibility pattern described in the PR objectives

This addresses issue #23 by allowing handlers to fall back to default behavior via proceed().


65-79: LGTM: Handler signatures consistently updated.

All handler signatures have been properly updated to accept the &dyn Chain parameter. The underscore prefix on _chain in block_handler (line 305) correctly indicates intentional non-use, as this is a terminal handler that doesn't delegate.

Also applies to: 305-319


85-93: LGTM: Appropriate use of Arc for shared configuration.

Storing Arc<Options> in ElementHandlers and passing references to handlers is an efficient design that avoids cloning while ensuring consistent configuration across the handler chain.


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

🧹 Nitpick comments (4)
README.md (1)

62-66: Consider documenting Chain‑based fallback behavior in the README example

The updated example correctly reflects the new handler signature (&dyn Chain, Element -> (Option<String>, bool)). To better showcase the main benefit of this PR (falling back to the original handler), consider adding a second example where the custom handler conditionally calls something like chain.proceed(element) so users see how to delegate back to the default behavior.

src/node_util.rs (1)

5-8: Options access via element.options.translation_mode looks correct; comment can be generalized

Switching is_parent_handler to read element.options.translation_mode keeps the faithful/markdown branching consistent with the new Options/ElementHandlers setup and removes the old HtmlToMarkdown dependency, which is what we want. One small nit: the comment mentioning only the <tr> tag is a bit misleading now that this helper is reused for different parent tags (e.g., "html", "table"). You may want to rephrase it to describe the generic “allowed parent tags” behavior instead of a specific tag.

Also applies to: 60-69

src/element_handler/tbody.rs (1)

1-7: tbody_handler correctly adapted; optional micro‑opt on parent tag list

The new _chain: &dyn Chain parameter keeps tbody_handler aligned with the common handler interface without altering behavior. As a tiny micro‑optimization, you could avoid allocating a Vec on each call by changing is_parent_handler to accept a slice and passing a literal slice instead (e.g., &["table"]). Not urgent, just a possible cleanup for later.

src/element_handler/head_body.rs (1)

1-4: head_body_handler correctly wired into Chain; minor Vec allocation nit

The new _chain: &dyn Chain parameter brings head_body_handler in line with the shared handler interface while leaving behavior unchanged. As with tbody_handler, you could later switch is_parent_handler to take a slice and pass &["html"] instead of &vec!["html"] to avoid per‑call Vec allocation, but this is purely an optional cleanup.

📜 Review details

Configuration used: CodeRabbit UI

Review profile: CHILL

Plan: Pro

📥 Commits

Reviewing files that changed from the base of the PR and between 9d45e4f and 917f028.

📒 Files selected for processing (27)
  • README.md (1 hunks)
  • examples/simple/main.rs (2 hunks)
  • src/dom_walker.rs (6 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 (3 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 (1 hunks)
  • src/element_handler/img.rs (1 hunks)
  • src/element_handler/li.rs (3 hunks)
  • src/element_handler/list.rs (1 hunks)
  • src/element_handler/mod.rs (7 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 (7 hunks)
  • src/node_util.rs (2 hunks)
  • tests/basic_tests.rs (2 hunks)
🧰 Additional context used
🧬 Code graph analysis (17)
src/element_handler/pre.rs (2)
src/element_handler/mod.rs (1)
  • serialize_element (324-454)
src/node_util.rs (1)
  • get_node_tag_name (10-16)
src/element_handler/tr.rs (1)
src/node_util.rs (1)
  • is_parent_handler (50-70)
src/element_handler/tbody.rs (1)
src/node_util.rs (1)
  • is_parent_handler (50-70)
src/element_handler/list.rs (2)
src/element_handler/mod.rs (1)
  • serialize_element (324-454)
src/node_util.rs (2)
  • get_node_tag_name (10-16)
  • get_parent_node (18-29)
src/node_util.rs (2)
src/element_handler/mod.rs (1)
  • serialize_element (324-454)
src/lib.rs (1)
  • options (175-178)
src/element_handler/head_body.rs (1)
src/node_util.rs (1)
  • is_parent_handler (50-70)
src/element_handler/caption.rs (1)
src/node_util.rs (1)
  • is_parent_handler (50-70)
tests/basic_tests.rs (2)
src/lib.rs (5)
  • builder (105-107)
  • default (81-83)
  • default (158-160)
  • convert (31-33)
  • convert (110-148)
tests/common/mod.rs (1)
  • convert (8-16)
src/element_handler/td_th.rs (1)
src/node_util.rs (1)
  • is_parent_handler (50-70)
src/element_handler/anchor.rs (1)
src/element_handler/mod.rs (2)
  • on_visit (65-65)
  • on_visit (77-79)
src/element_handler/br.rs (1)
src/lib.rs (1)
  • options (175-178)
src/element_handler/thead.rs (1)
src/node_util.rs (1)
  • is_parent_handler (50-70)
src/element_handler/code.rs (2)
src/element_handler/mod.rs (1)
  • serialize_element (324-454)
src/node_util.rs (2)
  • get_node_tag_name (10-16)
  • get_parent_node (18-29)
src/element_handler/mod.rs (4)
src/dom_walker.rs (2)
  • is_block_element (430-432)
  • walk_node (17-103)
src/lib.rs (3)
  • options (175-178)
  • new (88-95)
  • new (165-172)
src/element_handler/anchor.rs (2)
  • on_visit (32-77)
  • new (81-83)
src/element_handler/emphasis.rs (1)
  • emphasis_handler (8-33)
src/element_handler/html.rs (2)
src/element_handler/mod.rs (1)
  • serialize_element (324-454)
src/node_util.rs (1)
  • get_parent_node (18-29)
src/element_handler/table.rs (2)
src/element_handler/mod.rs (2)
  • serialize_element (324-454)
  • new (89-210)
src/node_util.rs (2)
  • get_node_children (43-46)
  • get_node_tag_name (10-16)
src/lib.rs (3)
src/options.rs (1)
  • default (22-37)
src/element_handler/mod.rs (1)
  • new (89-210)
src/dom_walker.rs (1)
  • walk_node (17-103)
🔇 Additional comments (24)
src/element_handler/p.rs (1)

1-5: p_handler signature correctly aligned with the new Chain API

The added Chain import and _chain: &dyn Chain parameter keep this handler consistent with the new handler interface without changing behavior. No issues here.

src/element_handler/img.rs (1)

2-9: img_handler correctly updated to the Chain‑based handler signature

The added Chain import and _chain: &dyn Chain parameter keep img_handler consistent with the new framework, while the existing logic and output remain unchanged. No further adjustments needed here.

src/element_handler/blockquote.rs (1)

2-16: blockquote_handler Chain integration looks good

The handler’s signature now matches the new Chain‑based interface, and the existing blockquote formatting logic remains intact. No issues spotted.

src/element_handler/list.rs (1)

3-55: list_handler correctly migrated to Options/Chain without behavior change

Updating the signature to take _chain: &dyn Chain and reading element.options.translation_mode instead of going through HtmlToMarkdown keeps this handler consistent with the new architecture while preserving its faithful‑mode and nested‑list behavior. Looks solid.

src/element_handler/html.rs (1)

11-29: Preparatory refactoring for Chain API looks good.

The mechanical addition of the _chain parameter and migration from element.html_to_markdown.options to element.options is correct. The underscore prefix appropriately signals that the chain parameter is not yet used—this is expected for preparatory work enabling the chain-of-responsibility pattern described in the PR objectives.

src/element_handler/hr.rs (1)

3-13: LGTM!

Consistent with the Chain API refactoring pattern. The migration to element.options.hr_style and unused _chain parameter align with the preparatory changes across all handlers.

src/element_handler/caption.rs (1)

3-6: LGTM!

The signature update is consistent with the broader Chain API refactoring. The handler body correctly delegates to is_parent_handler without requiring chain functionality at this stage.

src/element_handler/td_th.rs (1)

3-6: LGTM!

The signature change aligns with the Chain API refactoring. The handler correctly maintains its table cell validation logic via is_parent_handler.

src/element_handler/br.rs (1)

3-12: LGTM!

The refactoring correctly adds the Chain parameter and migrates to element.options.br_style. The BrStyle matching logic remains intact and correct.

src/element_handler/pre.rs (1)

10-31: LGTM!

The Chain parameter addition and migration to element.options.translation_mode are correct. The pre-handler's logic for faithful vs. pure translation mode and code block detection remains sound.

src/element_handler/emphasis.rs (1)

8-33: LGTM!

The Chain parameter is correctly positioned as the first parameter in the multiline signature. The emphasis handling logic (whitespace stripping, marker wrapping) remains unchanged and correct.

src/element_handler/tr.rs (1)

3-12: LGTM!

The signature update is consistent with the Chain API refactoring. The handler correctly delegates to is_parent_handler to validate table row context.

src/element_handler/li.rs (2)

12-12: LGTM! Handler signature updated for Chain-based API.

The addition of the _chain parameter aligns with the broader refactor introducing the Chain trait. The unused prefix correctly indicates this handler doesn't currently need delegation capabilities.


17-22: LGTM! Options access correctly migrated.

The changes from element.html_to_markdown.options to element.options are consistent with the new centralized options management through ElementHandlers.

Also applies to: 37-37

examples/simple/main.rs (1)

1-1: LGTM! Example updated to reflect the new Chain-based handler API.

The handler closure signature now correctly accepts &dyn Chain as the first parameter. This demonstrates the breaking API change users will need to adopt.

Also applies to: 30-30

src/element_handler/thead.rs (1)

3-3: LGTM! Handler signature updated consistently.

The addition of the _chain parameter maintains API consistency across all element handlers.

src/element_handler/headings.rs (1)

6-6: LGTM! Handler updated for Chain API with correct options access.

The signature and options access are consistently updated. The heading style logic remains unchanged.

Also applies to: 12-12

src/element_handler/code.rs (1)

15-15: LGTM! Code handler migrated to Chain API with updated options access.

All option references correctly updated from element.html_to_markdown.options to element.options. The handler logic remains unchanged.

Also applies to: 18-18, 45-46, 127-127

tests/basic_tests.rs (2)

537-542: LGTM! Test updated for Chain-based handler API.

The test correctly demonstrates removing elements with the new handler signature.


544-571: LGTM! Excellent test coverage for the new Chain delegation feature.

This test demonstrates the key functionality of the PR:

  • Custom handlers can conditionally delegate to default handlers using chain.proceed(element)
  • The test validates both the short-circuit path (returning (None, true)) and the delegation path

This directly addresses issue #23 by showing how custom handlers can fall back to default behavior.

src/element_handler/table.rs (2)

17-17: LGTM! Table handler actively uses Chain for child node processing.

The handler correctly uses chain.handle() to process caption child nodes. The pattern of checking for Some(md) and using the result is appropriate.

Also applies to: 45-47


152-172: LGTM! Cell extraction correctly uses Chain delegation.

The extract_row_cells function properly uses chain.handle() to process cell content. The early continue when chain.handle() returns None is the correct approach for handling non-element nodes or nodes that don't produce markdown output.

src/element_handler/anchor.rs (2)

32-49: LGTM! Anchor handler signature updated with direct element access.

The handler now receives a unified Element parameter instead of separate fields. The early return when no href is found correctly returns element.content.


63-74: LGTM! Options and content access migrated correctly.

All references to options now use element.options, and content is accessed via element.content. The link style handling logic remains unchanged.

Comment thread src/element_handler/mod.rs Resolved
@letmutex

Copy link
Copy Markdown
Owner Author

@coderabbitai help

@coderabbitai

coderabbitai Bot commented Nov 14, 2025

Copy link
Copy Markdown
Contributor

Chat

There are 3 ways to chat with CodeRabbit:

  • Review comments: Directly reply to a review comment made by CodeRabbit. Example:
    • I pushed a fix in commit <commit_id>, please review it.
    • Open a follow-up GitHub issue for this discussion.
  • Files and specific lines of code (under the "Files changed" tab): Tag @coderabbitai in a new review comment at the desired location with your query.
  • PR comments: Tag @coderabbitai in a new PR comment to ask questions about the PR branch. For the best results, please provide a very specific query, as very limited context is provided in this mode. Examples:
    • @coderabbitai gather interesting stats about this repository and render them as a table. Additionally, render a pie chart showing the language distribution in the codebase.
    • @coderabbitai read the files in the src/scheduler package and generate a class diagram using mermaid and a README in the markdown format.

CodeRabbit commands

These commands are invoked using PR/Issue comments.

  • @coderabbitai pause to pause the reviews on a PR.
  • @coderabbitai resume to resume the paused reviews.
  • @coderabbitai review to trigger an incremental review. This is useful when automatic reviews are disabled for the repository.
  • @coderabbitai full review to do a full review from scratch and review all the files again.
  • @coderabbitai summary to regenerate the summary of the PR.
  • @coderabbitai evaluate custom pre-merge check --instructions <custom-checks-instructions> --name <custom-checks-title> [--mode <error|warning>] to validate the custom pre-merge checks instructions. Defaults to error when --mode is omitted.
    • @coderabbitai ignore pre-merge checks to override pre-merge checks and get an approval on PR.
    • @coderabbitai run pre-merge checks to run pre-merge checks on the pull request.
  • @coderabbitai generate docstrings to generate docstrings for this PR.
  • @coderabbitai generate sequence diagram to generate a sequence diagram of the changes in this PR.
  • @coderabbitai generate unit tests to generate unit tests for this PR.
  • @coderabbitai resolve to resolve all the CodeRabbit review comments.
  • @coderabbitai configuration to show the current CodeRabbit configuration for the repository.
  • @coderabbitai help to get help.

Other keywords and placeholders

  • Add @coderabbitai ignore or @coderabbit ignore anywhere in the PR description to prevent this PR from being reviewed.
  • Add @coderabbitai summary to generate the high-level summary at a specific location in the PR description.
  • Add @coderabbitai anywhere in the PR title to generate the title automatically.

CodeRabbit configuration file (.coderabbit.yaml)

  • You can programmatically configure CodeRabbit by adding a .coderabbit.yaml file to the root of your repository.
  • Please see the configuration documentation for more information.
  • You can also validate your configuration using the online YAML validator.
  • If your editor has YAML language server enabled, you can add the path at the top of this file to enable auto-completion and validation: # yaml-language-server: $schema=https://coderabbit.ai/integrations/schema.v2.json

Status, support, documentation and community

  • Visit our status page to check the current availability of CodeRabbit.
  • Create a ticket on our support page for assistance with any issues or questions.
  • Visit our documentation site for detailed information on how to use CodeRabbit.
  • Join our Discord community to connect with other users and get help from the community.
  • Follow us on X/Twitter for updates and announcements.

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

♻️ Duplicate comments (1)
src/element_handler/mod.rs (1)

298-303: Critical: Return the actual translation status.

The implementation correctly captures walk_node's return value in markdown_translated (line 300) but then discards it by returning hardcoded true (line 302). This breaks faithful-mode logic that relies on the translation status flag.

This issue was already identified in a previous review.

Apply this diff:

     fn handle(&self, node: &Rc<Node>) -> (Option<String>, bool) {
         let mut buffer = Vec::new();
         let markdown_translated = walk_node(node, &mut buffer, self, None, true, false);
         let md = buffer.join("");
-        (Some(md), true)
+        (Some(md), markdown_translated)
     }
🧹 Nitpick comments (1)
src/element_handler/mod.rs (1)

224-272: Handler chain traversal logic is correct.

The reverse iteration with skip(skipped_handlers).nth(0) correctly walks backward through handlers registered for the tag, enabling proceed() to delegate to the next handler in the chain.

Consider this optional refactor for clarity:

-        .nth(0);
+        .next();

Using .next() instead of .nth(0) is more idiomatic when taking the first element.

📜 Review details

Configuration used: CodeRabbit UI

Review profile: CHILL

Plan: Pro

📥 Commits

Reviewing files that changed from the base of the PR and between 917f028 and 87953fe.

📒 Files selected for processing (1)
  • src/element_handler/mod.rs (7 hunks)
🧰 Additional context used
🧬 Code graph analysis (1)
src/element_handler/mod.rs (4)
src/dom_walker.rs (2)
  • is_block_element (430-432)
  • walk_node (17-103)
src/lib.rs (3)
  • options (175-178)
  • new (88-95)
  • new (165-172)
src/element_handler/anchor.rs (2)
  • on_visit (32-77)
  • new (81-83)
src/element_handler/emphasis.rs (1)
  • emphasis_handler (8-33)
🔇 Additional comments (7)
src/element_handler/mod.rs (7)

22-26: LGTM!

The new imports support the Chain-based architecture: walk_node and is_block_element enable the Chain implementation, while Arc wraps the shared Options.

Also applies to: 47-52


59-66: Breaking API change enables handler delegation.

The new chain parameter allows handlers to delegate to previous handlers via proceed() or recursively process nodes via handle(), addressing the fallback mechanism requested in issue #23.

Note: This is an intentional breaking change to the public API, consistent with the PR's "Unstable" status.


73-80: LGTM!

The closure-to-ElementHandler adapter correctly reflects the new signature, enabling users to pass closures with the chain parameter to add_handler.


83-93: LGTM!

Centralizing Arc<Options> in ElementHandlers eliminates the need to thread options through every handler call. The Arc enables cheap sharing across handlers.


275-284: LGTM!

The Chain trait provides the two key capabilities requested in issue #23:

  • proceed(): delegate to the previous handler for fallback behavior
  • handle(): recursively process child nodes

The design is clean and well-documented.


306-320: LGTM!

Handler signatures correctly adopt the new chain parameter. The underscore prefix on unused _chain parameters is appropriate for handlers that don't delegate.


458-476: LGTM!

The macro correctly accesses element.options.translation_mode to match the new Element structure. The faithful-mode logic is preserved.

@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

📜 Review details

Configuration used: CodeRabbit UI

Review profile: CHILL

Plan: Pro

📥 Commits

Reviewing files that changed from the base of the PR and between 87953fe and b3e89ba.

📒 Files selected for processing (1)
  • src/element_handler/mod.rs (7 hunks)
🧰 Additional context used
🧬 Code graph analysis (1)
src/element_handler/mod.rs (4)
src/dom_walker.rs (2)
  • is_block_element (430-432)
  • walk_node (17-103)
src/lib.rs (3)
  • options (175-178)
  • new (88-95)
  • new (165-172)
src/element_handler/anchor.rs (2)
  • on_visit (32-77)
  • new (81-83)
src/element_handler/emphasis.rs (1)
  • emphasis_handler (8-33)
🪛 GitHub Actions: Cargo Build & Test
src/element_handler/mod.rs

[error] 237-239: Clippy: called skip(..).next() on an iterator. Use .nth(...) instead. Hint: consider replacing with .nth(skipped_handlers); possible lint: clippy::iter_skip_next. Command 'cargo clippy -- --deny warnings' failed with exit code 101.

🔇 Additional comments (6)
src/element_handler/mod.rs (6)

275-284: LGTM! Well-designed Chain trait.

The Chain trait cleanly implements the chain-of-responsibility pattern inspired by OkHttp's interceptor design. The two methods (proceed for delegation and handle for recursive processing) address the requirements from issue #23 for handler fallback functionality.


286-304: LGTM! Chain implementation is correct.

The implementation properly captures and propagates the markdown_translated flag from walk_node (line 300) and returns it (line 302). This addresses the concern raised in the previous review about hardcoding the success flag.

The delegation logic in proceed correctly increments skipped_handlers to skip to the next handler in the chain.


224-272: LGTM! Handler lookup and delegation logic is sound.

The refactored handle method correctly implements the chain-of-responsibility pattern:

  • Reverses handler rules to prioritize custom handlers (line 237)
  • Skips already-tried handlers using the counter (line 238)
  • Passes all necessary context including options and skipped_handlers to the Element (lines 243-251)
  • Falls back to serialization when no handler matches (lines 253-270)

The centralization of options in ElementHandlers (line 85, 89) is a clean architectural improvement.


306-320: LGTM! Handler signatures correctly updated.

The built-in handlers properly implement the new signature with chain: &dyn Chain parameter. The naming convention (underscore prefix for unused parameters) is good practice, and delegation between handlers (e.g., bold_handler to emphasis_handler) correctly forwards the chain.


459-476: LGTM! Macro updated to match new Element structure.

The serialize_if_faithful macro correctly accesses $element.options.translation_mode (line 466), consistent with the refactored Element structure where options are now stored in the ElementHandlers.


59-80: LGTM! ElementHandler trait properly refactored.

The trait and its blanket implementation for closures have been correctly updated to accept the new chain: &dyn Chain parameter. This is a breaking change as noted in the PR description, but aligns with the enhanced API design.

Comment thread src/element_handler/mod.rs Resolved
@letmutex
letmutex merged commit 17f4f85 into main Nov 14, 2025
@letmutex
letmutex deleted the chain-of-responsibility branch November 14, 2025 15:05
This was referenced Nov 15, 2025
@coderabbitai coderabbitai Bot mentioned this pull request Jul 16, 2026
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.

Is there a way to fallback the original handler after add_handler?

1 participant