Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

added Selection::ancestors #28

Merged
merged 1 commit into from
Nov 6, 2024
Merged

added Selection::ancestors #28

merged 1 commit into from
Nov 6, 2024

Conversation

niklak
Copy link
Owner

@niklak niklak commented Nov 6, 2024

Summary by CodeRabbit

  • New Features
    • Introduced a new method for retrieving ancestor elements in the selection, enhancing navigation capabilities.
    • Added a new test for ancestor selection with limits, improving test coverage.

Copy link

coderabbitai bot commented Nov 6, 2024

Walkthrough

The changes introduced in this pull request enhance the documentation and functionality of the dom_query library in Rust. Key updates include the addition of comprehensive examples in Examples.md and README.md, demonstrating various capabilities such as document parsing, element selection, and DOM manipulation. A new method for retrieving ancestor nodes was added to the Selection struct in src/selection.rs, while test cases were updated in several files to reflect these changes and improve readability. Overall, these modifications aim to improve both the library's usability and its testing framework.

Changes

File Change Summary
Examples.md Added examples for document parsing, element selection, ancestor/descendant selection, attribute manipulation, DOM manipulation, node creation/renaming, and serialization.
README.md Expanded content with new examples on parsing, selecting, manipulating attributes, and DOM operations, structured within collapsible <details> tags.
src/selection.rs Introduced pub fn ancestors(&self, max_depth: Option<usize>) -> Selection<'a>; deprecated pub fn next(&self) -> Selection<'a>.
tests/data.rs Updated ANCESTORS_CONTENTS to replace <div id="child">Child</div> with <div id="first-child">Child</div> and <div id="second-child">Child</div>.
tests/node-manipulation.rs Reformatted assertions in test_append_existing_children and test_prepend_existing_children for readability; removed an unnecessary blank line.
tests/selection-traversal.rs Renamed selection target from #child to #first-child in multiple tests; added test_ancestors_selection_with_limit to validate ancestor selection.

Sequence Diagram(s)

sequenceDiagram
    participant User
    participant DOM
    participant Selection

    User->>DOM: Parse Document
    DOM->>Selection: Create Selection
    User->>Selection: Select Elements
    User->>Selection: Get Ancestors
    Selection->>DOM: Retrieve Ancestors
    User->>Selection: Manipulate Attributes
    Selection->>DOM: Update Attributes
    User->>DOM: Serialize to HTML
Loading

🐰 "In the garden of code, we hop and play,
With examples and tests, we brighten the day.
Ancestors found, and elements too,
Our dom_query library, now shines anew!
So let’s celebrate with a joyful cheer,
For the magic of coding, brings us all near!" 🥕


Thank you for using CodeRabbit. We offer it for free to the OSS community and would appreciate your support in helping us grow. If you find it useful, would you consider giving us a shout-out on your favorite social media?

❤️ Share
🪧 Tips

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.
    • Generate unit testing code for this file.
    • 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. Examples:
    • @coderabbitai generate unit testing code for this file.
    • @coderabbitai modularize this function.
  • 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 src/utils.ts and generate unit testing code.
    • @coderabbitai read the files in the src/scheduler package and generate a class diagram using mermaid and a README in the markdown format.
    • @coderabbitai help me debug CodeRabbit configuration file.

Note: Be mindful of the bot's finite context window. It's strongly recommended to break down tasks such as reading entire modules into smaller chunks. For a focused discussion, use review comments to chat about specific files and their changes, instead of using the PR comments.

CodeRabbit Commands (Invoked using PR 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 resolve 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 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.
  • 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

Documentation and Community

  • Visit our Documentation for detailed information on how to use CodeRabbit.
  • Join our Discord Community to get help, request features, and share feedback.
  • Follow us on X/Twitter for updates and announcements.

Copy link

codecov bot commented Nov 6, 2024

Codecov Report

All modified and coverable lines are covered by tests ✅

Project coverage is 83.30%. Comparing base (c507dd8) to head (5dadeee).
Report is 2 commits behind head on main.

Additional details and impacted files
@@            Coverage Diff             @@
##             main      #28      +/-   ##
==========================================
+ Coverage   83.20%   83.30%   +0.09%     
==========================================
  Files          13       13              
  Lines        1989     2000      +11     
==========================================
+ Hits         1655     1666      +11     
  Misses        334      334              

☔ View full report in Codecov by Sentry.
📢 Have feedback on the report? Share it here.

Copy link

@coderabbitai coderabbitai bot left a comment

Choose a reason for hiding this comment

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

Actionable comments posted: 0

🧹 Outside diff range and nitpick comments (6)
tests/selection-traversal.rs (2)

Line range hint 312-331: LGTM! Consider enhancing the test documentation.

The test effectively verifies the full ancestor chain traversal functionality. The assertions appropriately check both presence and absence of nodes in the ancestor chain.

Consider adding a comment explaining why we test !ancestor_sel.is("#first-child") to make it clearer that we're verifying the ancestor chain excludes the starting node.


Line range hint 362-370: Consider enhancing iterator test coverage.

While the test verifies the count of ancestors, consider adding assertions to verify the actual content/order of the iterator results.

 let child_node = child_sel.nodes().first().unwrap();
-let ancestors = child_node.ancestors_it(Some(2));
-// utilizing ancestors iterator (without intermediate collection)
-// got 2 ancestors
-assert!(ancestors.count() == 2);
+let mut ancestors = child_node.ancestors_it(Some(2));
+// Verify both count and content of ancestors
+let first = ancestors.next().unwrap();
+let second = ancestors.next().unwrap();
+assert!(ancestors.next().is_none());  // Verify we got exactly 2
+assert_eq!(first.id(), Some("parent"));
+assert_eq!(second.id(), Some("grand-parent"));
Examples.md (2)

231-233: Consider improving the comment's clarity

The comment provides a useful shorthand alternative, but could be more explicit about what it's simplifying. Consider revising to better explain the relationship with the previous code.

-
-// or just: let ancestor_sel = child_sel.ancestors(None);
-
+// Shorthand alternative to the above two lines:
+// Instead of creating Selection from ancestors, you can directly call:
+// let ancestor_sel = child_sel.ancestors(None);

231-233: Consider enhancing the ancestors example section

The example thoroughly demonstrates the API, but could be more helpful with:

  1. A brief introduction explaining when and why you'd use ancestor selection
  2. Common use cases (e.g., finding closest parent with specific class, traversing up to specific ancestor)
  3. Performance considerations when using max_limit vs no limit

Consider adding this introductory text at the start of the section:

// Ancestor selection allows you to traverse up the DOM tree from a selected element.
// This is useful for:
// - Finding the closest parent matching a condition
// - Checking if an element is contained within a specific ancestor
// - Building breadcrumb navigation
// 
// The `ancestors()` method supports both unlimited traversal (None) and 
// limited traversal (Some(n)) for performance optimization.
README.md (1)

264-265: LGTM! Consider highlighting the alternative approach more prominently.

The added comment effectively documents the alternative, more concise approach using child_sel.ancestors(None). This is valuable information for users.

Consider restructuring to make the alternative approach more prominent, as it's likely the preferred method:

-// or just: let ancestor_sel = child_sel.ancestors(None);
+// Alternative, more concise approach:
+// let ancestor_sel = child_sel.ancestors(None);
src/selection.rs (1)

531-554: LGTM! Consider enhancing documentation with usage examples.

The implementation looks solid and follows the established patterns in the codebase. The method correctly handles duplicate prevention and properly filters for element nodes.

Consider adding usage examples to the documentation, similar to other methods in the codebase. For example:

/// # Examples
/// 
/// ```
/// # use dom_query::Document;
/// let doc = Document::from("<div><p><span>Hello</span></p></div>");
/// let span = doc.select("span").first();
/// 
/// // Get all ancestors
/// let all_ancestors = span.ancestors(None);
/// assert_eq!(all_ancestors.length(), 2); // matches p and div
/// 
/// // Get ancestors with depth limit
/// let limited_ancestors = span.ancestors(Some(1));
/// assert_eq!(limited_ancestors.length(), 1); // matches only p
/// ```
📜 Review details

Configuration used: CodeRabbit UI
Review profile: CHILL

📥 Commits

Reviewing files that changed from the base of the PR and between c507dd8 and 5dadeee.

📒 Files selected for processing (6)
  • Examples.md (1 hunks)
  • README.md (1 hunks)
  • src/selection.rs (1 hunks)
  • tests/data.rs (1 hunks)
  • tests/node-manipulation.rs (2 hunks)
  • tests/selection-traversal.rs (4 hunks)
✅ Files skipped from review due to trivial changes (1)
  • tests/node-manipulation.rs
🔇 Additional comments (4)
tests/data.rs (1)

23-24: LGTM! Well-structured test data changes.

The modification to split the single child into two siblings with semantic IDs (first-child and second-child) is clean and properly formatted. This change effectively supports testing ancestor selection functionality for multiple elements.

Let's verify the HTML validity:

tests/selection-traversal.rs (2)

Line range hint 339-353: LGTM! Well-structured test for limited ancestor traversal.

The test effectively verifies the limited ancestor traversal functionality, with good coverage of both included and excluded ancestors.


372-388: LGTM! Excellent test coverage for multi-node ancestor selection.

The test effectively verifies that the Selection::ancestors method works correctly when finding common ancestors of multiple nodes, with appropriate limit handling.

src/selection.rs (1)

555-555: LGTM! Deprecation follows best practices.

The deprecation of next in favor of next_sibling is well-handled with a clear migration path for users.

@niklak niklak merged commit bbb1b44 into main Nov 6, 2024
10 checks passed
@niklak niklak deleted the feature/selection-ancestors branch November 6, 2024 17:02
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