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

src/node/serializing.rs: implement format_text #62

Merged
merged 3 commits into from
Feb 2, 2025

Conversation

niklak
Copy link
Owner

@niklak niklak commented Feb 2, 2025

  • Implemented Document::formatted_text, Selection::formatted_text, and NodeRef::formatted_text, which return formatted text of the document, selection, or node respectively.

Copy link

coderabbitai bot commented Feb 2, 2025

Warning

Rate limit exceeded

@niklak has exceeded the limit for the number of commits or files that can be reviewed per hour. Please wait 14 minutes and 36 seconds before requesting another review.

⌛ How to resolve this issue?

After the wait time has elapsed, a review can be triggered using the @coderabbitai review command as a PR comment. Alternatively, push new commits to this PR.

We recommend that you space out your commits to avoid hitting the rate limit.

🚦 How do rate limits work?

CodeRabbit enforces hourly rate limits for each developer per organization.

Our paid plans have higher rate limits than the trial, open-source and free plans. In all cases, we re-allow further reviews after a brief timeout.

Please see our FAQ for further information.

📥 Commits

Reviewing files that changed from the base of the PR and between 123f55e and 015c3c0.

📒 Files selected for processing (4)
  • src/node/serializing.rs (2 hunks)
  • tests/data.rs (1 hunks)
  • tests/node-traversal.rs (2 hunks)
  • tests/selection-traversal.rs (2 hunks)

Walkthrough

The changes add new text formatting functionality across multiple components. New formatted_text methods have been implemented for the Document, Selection, and NodeRef structs to generate normalized and formatted text outputs. A new internal function (format_text) and helper (normalize_text) have been introduced in the serialization module to support these methods. Additionally, tests and static HTML content have been added to validate the new behavior without modifying existing functionality.

Changes

File(s) Change Summary
CHANGELOG.md, src/document.rs, src/selection.rs, src/.../node_ref.rs Added formatted_text methods to the Document, Selection, and NodeRef structs, along with the introduction of NodeRef::normalized_char_count.
src/.../serializing.rs Introduced new functions: format_text (public within crate) for generating formatted text and a helper normalize_text for whitespace normalization.
src/node.rs Re-exported the format_text function with pub(crate) visibility.
tests/data.rs, tests/node-traversal.rs, tests/selection-traversal.rs Added static HTML content (DMC_CONTENTS) and new tests verifying the output of the formatted_text methods.

Possibly related PRs

Poem

Hop along the coding lane,
I’m a bunny with some new refrain.
Formatted texts now dance and play,
Whitespace tamed in a neat array.
From Document to NodeRef so bright,
Formats hop in pure delight! 🐰
Happy trails in every byte!


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 generate docstrings to generate docstrings for this PR. (Beta)
  • @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 Feb 2, 2025

Codecov Report

Attention: Patch coverage is 98.86364% with 1 line in your changes missing coverage. Please review.

Project coverage is 92.12%. Comparing base (b598faf) to head (015c3c0).
Report is 4 commits behind head on main.

Files with missing lines Patch % Lines
src/node/serializing.rs 98.66% 1 Missing ⚠️
Additional details and impacted files
@@            Coverage Diff             @@
##             main      #62      +/-   ##
==========================================
+ Coverage   91.90%   92.12%   +0.22%     
==========================================
  Files          16       16              
  Lines        2618     2706      +88     
==========================================
+ Hits         2406     2493      +87     
- Misses        212      213       +1     

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

🧹 Nitpick comments (3)
src/node/serializing.rs (1)

183-207: Consider edge cases in text normalization.

The normalize_text function handles basic whitespace normalization well, but consider adding documentation about its behavior with:

  • Unicode whitespace characters
  • Zero-width spaces
  • Non-breaking spaces
 fn normalize_text(text: &str, follows_newline: bool) -> StrTendril {
+    // Handle all Unicode whitespace characters including:
+    // - Regular spaces
+    // - Non-breaking spaces
+    // - Zero-width spaces
+    // - Other Unicode whitespace
     let push_start_whitespace = !follows_newline && text.starts_with(char::is_whitespace);
tests/node-traversal.rs (1)

332-353: Consider adding more test cases.

While the current test is good, consider adding test cases for:

  • Empty documents
  • Documents with only whitespace
  • Documents with special HTML elements (pre, br, etc.)
  • Documents with nested formatting

Here's a suggested additional test case:

#[cfg_attr(not(target_arch = "wasm32"), test)]
#[cfg_attr(target_arch = "wasm32", wasm_bindgen_test)]
fn test_doc_formatted_text_edge_cases() {
    // Test empty document
    let doc = Document::from("");
    assert_eq!(doc.formatted_text().as_ref(), "");

    // Test whitespace-only document
    let doc = Document::from("  \n  \t  ");
    assert_eq!(doc.formatted_text().as_ref(), "");

    // Test pre tag formatting
    let doc = Document::from("<pre>  preserved  whitespace  </pre>");
    assert_eq!(doc.formatted_text().as_ref(), "  preserved  whitespace  \n\n");
}
src/document.rs (1)

120-129: Add examples to the documentation.

The documentation clearly explains the formatting rules but would benefit from examples showing the input and expected output.

Add examples like this:

 /// Returns the formatted text of the document and its descendants. This is the same as
 /// the `text()` method, but with a few differences:
 ///
 /// - Whitespace is normalized so that there is only one space between words.
 /// - All whitespace is removed from the beginning and end of the text.
 /// - After block elements, a double newline is added.
 /// - For elements like `br`, 'hr', 'li', 'tr' a single newline is added.
+///
+/// # Examples
+///
+/// ```
+/// use dom_query::Document;
+///
+/// let doc = Document::from(r#"<div>Hello   World</div><p>First</p><p>Second</p>"#);
+/// assert_eq!(doc.formatted_text(), "Hello World\n\nFirst\n\nSecond\n\n");
+/// ```
📜 Review details

Configuration used: CodeRabbit UI
Review profile: CHILL
Plan: Pro

📥 Commits

Reviewing files that changed from the base of the PR and between b598faf and 9e28247.

📒 Files selected for processing (9)
  • CHANGELOG.md (1 hunks)
  • src/document.rs (1 hunks)
  • src/node.rs (1 hunks)
  • src/node/node_ref.rs (2 hunks)
  • src/node/serializing.rs (2 hunks)
  • src/selection.rs (2 hunks)
  • tests/data.rs (1 hunks)
  • tests/node-traversal.rs (2 hunks)
  • tests/selection-traversal.rs (2 hunks)
🧰 Additional context used
🪛 GitHub Actions: Rust Clippy & Audit
src/node/node_ref.rs

[error] 562-562: Empty line after doc comment.

🪛 GitHub Check: codecov/patch
src/node/serializing.rs

[warning] 108-108: src/node/serializing.rs#L108
Added line #L108 was not covered by tests


[warning] 114-114: src/node/serializing.rs#L114
Added line #L114 was not covered by tests


[warning] 124-125: src/node/serializing.rs#L124-L125
Added lines #L124 - L125 were not covered by tests


[warning] 134-137: src/node/serializing.rs#L134-L137
Added lines #L134 - L137 were not covered by tests


[warning] 169-170: src/node/serializing.rs#L169-L170
Added lines #L169 - L170 were not covered by tests

⏰ Context from checks skipped due to timeout of 90000ms (1)
  • GitHub Check: test
🔇 Additional comments (6)
src/node.rs (1)

18-18: LGTM!

The visibility modifier pub(crate) is appropriate for the format_text function as it should only be accessible within the crate.

tests/data.rs (1)

108-128: LGTM!

The test data is well-structured and includes various text formatting scenarios that will help validate the text formatting functionality.

src/node/serializing.rs (1)

90-181: Add test coverage for untested code paths.

The following code paths need test coverage:

  • Empty text content handling (line 114)
  • Pre tag content handling (lines 124-125)
  • Document/Fragment node handling (lines 134-137)
  • Line break handling for br/hr/li/tr tags (lines 169-170)

Let's verify the untested code paths:

🧰 Tools
🪛 GitHub Check: codecov/patch

[warning] 108-108: src/node/serializing.rs#L108
Added line #L108 was not covered by tests


[warning] 114-114: src/node/serializing.rs#L114
Added line #L114 was not covered by tests


[warning] 124-125: src/node/serializing.rs#L124-L125
Added lines #L124 - L125 were not covered by tests


[warning] 134-137: src/node/serializing.rs#L134-L137
Added lines #L134 - L137 were not covered by tests


[warning] 169-170: src/node/serializing.rs#L169-L170
Added lines #L169 - L170 were not covered by tests

tests/selection-traversal.rs (1)

527-551: LGTM!

The test case is well-structured and thoroughly validates the text formatting rules, including whitespace normalization and newline handling.

src/selection.rs (1)

180-193: LGTM!

The implementation correctly handles multiple selected nodes by concatenating their formatted text while maintaining consistent formatting rules.

CHANGELOG.md (1)

9-10: Changelog Entry for New Formatted Text Methods

The updated changelog clearly documents the addition of the new formatted text methods:

  • Document::formatted_text
  • Selection::formatted_text
  • NodeRef::formatted_text

This entry aligns well with the PR objectives and provides a concise description of the new functionality. Consider if additional context—such as a note on underlying normalization behavior or reference to the internal helper functions—would add value for users looking for more granular details.

Comment on lines 556 to 566
/// Returns the formatted text of the node and its descendants. This is the same as
/// the `text()` method, but with a few differences:
///
/// - Whitespace is normalized so that there is only one space between words.
/// - All whitespace is removed from the beginning and end of the text.
/// - After block elements, a double newline is added.
/// - For elements like `br`, 'hr', 'li', 'tr' a single newline is added.

pub fn formatted_text(&self) -> StrTendril {
format_text(self, false)
}
Copy link

Choose a reason for hiding this comment

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

⚠️ Potential issue

Fix the empty line after doc comment.

Remove the empty line after the doc comment to fix the Clippy warning.

Apply this diff:

 /// Returns the formatted text of the node and its descendants. This is the same as
 /// the `text()` method, but with a few differences:
 ///
 /// - Whitespace is normalized so that there is only one space between words.
 /// - All whitespace is removed from the beginning and end of the text.
 /// - After block elements, a double newline is added.
 /// - For elements like `br`, 'hr', 'li', 'tr' a single newline is added.
-
 pub fn formatted_text(&self) -> StrTendril {
     format_text(self, false)
 }
📝 Committable suggestion

‼️ IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.

Suggested change
/// Returns the formatted text of the node and its descendants. This is the same as
/// the `text()` method, but with a few differences:
///
/// - Whitespace is normalized so that there is only one space between words.
/// - All whitespace is removed from the beginning and end of the text.
/// - After block elements, a double newline is added.
/// - For elements like `br`, 'hr', 'li', 'tr' a single newline is added.
pub fn formatted_text(&self) -> StrTendril {
format_text(self, false)
}
/// Returns the formatted text of the node and its descendants. This is the same as
/// the `text()` method, but with a few differences:
///
/// - Whitespace is normalized so that there is only one space between words.
/// - All whitespace is removed from the beginning and end of the text.
/// - After block elements, a double newline is added.
/// - For elements like `br`, 'hr', 'li', 'tr' a single newline is added.
pub fn formatted_text(&self) -> StrTendril {
format_text(self, false)
}
🧰 Tools
🪛 GitHub Actions: Rust Clippy & Audit

[error] 562-562: Empty line after doc comment.

@niklak niklak merged commit b2fb5c5 into main Feb 2, 2025
11 checks passed
@niklak niklak deleted the feature/formatted-text branch February 2, 2025 11:05
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