Repository navigation
Enhanced ElementHandler API - #59
Conversation
WalkthroughAdds 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
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)
Estimated code review effort🎯 4 (Complex) | ⏱️ ~60 minutes
Poem
Pre-merge checks and finishing touches❌ Failed checks (1 warning)
✅ Passed checks (4 passed)
✨ Finishing touches
🧪 Generate unit tests (beta)
📜 Recent review detailsConfiguration used: CodeRabbit UI Review profile: CHILL Plan: Pro 📒 Files selected for processing (1)
🧰 Additional context used🧬 Code graph analysis (1)src/element_handler/mod.rs (4)
🔇 Additional comments (5)
Comment |
There was a problem hiding this comment.
Actionable comments posted: 1
🧹 Nitpick comments (4)
README.md (1)
62-66: Consider documenting Chain‑based fallback behavior in the README exampleThe 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 likechain.proceed(element)so users see how to delegate back to the default behavior.src/node_util.rs (1)
5-8: Options access viaelement.options.translation_modelooks correct; comment can be generalizedSwitching
is_parent_handlerto readelement.options.translation_modekeeps 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 listThe new
_chain: &dyn Chainparameter keepstbody_handleraligned with the common handler interface without altering behavior. As a tiny micro‑optimization, you could avoid allocating aVecon each call by changingis_parent_handlerto 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 nitThe new
_chain: &dyn Chainparameter bringshead_body_handlerin line with the shared handler interface while leaving behavior unchanged. As withtbody_handler, you could later switchis_parent_handlerto 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
📒 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 APIThe added
Chainimport and_chain: &dyn Chainparameter 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 signatureThe added
Chainimport and_chain: &dyn Chainparameter keepimg_handlerconsistent 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 goodThe 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 changeUpdating the signature to take
_chain: &dyn Chainand readingelement.options.translation_modeinstead 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
_chainparameter and migration fromelement.html_to_markdown.optionstoelement.optionsis 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_styleand unused_chainparameter 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_handlerwithout 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_modeare 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_handlerto validate table row context.src/element_handler/li.rs (2)
12-12: LGTM! Handler signature updated for Chain-based API.The addition of the
_chainparameter 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.optionstoelement.optionsare consistent with the new centralized options management throughElementHandlers.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 Chainas 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
_chainparameter 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.optionstoelement.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 pathThis 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 forSome(md)and using the result is appropriate.Also applies to: 45-47
152-172: LGTM! Cell extraction correctly uses Chain delegation.The
extract_row_cellsfunction properly useschain.handle()to process cell content. The earlycontinuewhenchain.handle()returnsNoneis 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
Elementparameter instead of separate fields. The early return when nohrefis found correctly returnselement.content.
63-74: LGTM! Options and content access migrated correctly.All references to options now use
element.options, and content is accessed viaelement.content. The link style handling logic remains unchanged.
|
@coderabbitai help |
ChatThere are 3 ways to chat with CodeRabbit:
CodeRabbit commands
Other keywords and placeholders
CodeRabbit configuration file (
|
Co-authored-by: coderabbitai[bot] <136622811+coderabbitai[bot]@users.noreply.github.com>
There was a problem hiding this comment.
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 inmarkdown_translated(line 300) but then discards it by returning hardcodedtrue(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, enablingproceed()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
📒 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_nodeandis_block_elementenable the Chain implementation, whileArcwraps the shared Options.Also applies to: 47-52
59-66: Breaking API change enables handler delegation.The new
chainparameter allows handlers to delegate to previous handlers viaproceed()or recursively process nodes viahandle(), 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>inElementHandlerseliminates the need to thread options through every handler call. The Arc enables cheap sharing across handlers.
275-284: LGTM!The
Chaintrait provides the two key capabilities requested in issue #23:
proceed(): delegate to the previous handler for fallback behaviorhandle(): recursively process child nodesThe design is clean and well-documented.
306-320: LGTM!Handler signatures correctly adopt the new
chainparameter. The underscore prefix on unused_chainparameters is appropriate for handlers that don't delegate.
458-476: LGTM!The macro correctly accesses
element.options.translation_modeto match the new Element structure. The faithful-mode logic is preserved.
There was a problem hiding this comment.
Actionable comments posted: 1
📜 Review details
Configuration used: CodeRabbit UI
Review profile: CHILL
Plan: Pro
📒 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 (
proceedfor delegation andhandlefor 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_translatedflag fromwalk_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
proceedcorrectly incrementsskipped_handlersto skip to the next handler in the chain.
224-272: LGTM! Handler lookup and delegation logic is sound.The refactored
handlemethod 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
optionsandskipped_handlersto the Element (lines 243-251)- Falls back to serialization when no handler matches (lines 253-270)
The centralization of
optionsinElementHandlers(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 Chainparameter. The naming convention (underscore prefix for unused parameters) is good practice, and delegation between handlers (e.g.,bold_handlertoemphasis_handler) correctly forwards the chain.
459-476: LGTM! Macro updated to match new Element structure.The
serialize_if_faithfulmacro correctly accesses$element.options.translation_mode(line 466), consistent with the refactored Element structure where options are now stored in theElementHandlers.
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 Chainparameter. This is a breaking change as noted in the PR description, but aligns with the enhanced API design.
The original idea is from OkHttp. This PR adds a
Chainparam for theElementHandler, which can be used to:proceed(Element)handle(Rc<Node>)This will resolve #23 and introduce an enhanced
ElementHandlerAPI proposed in #57.Status: Unstable, the added APIs are likely to change.
Summary by CodeRabbit
Refactor
Documentation
Tests