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

fix: improve handling of pseudo classes and elements #58

Merged
merged 1 commit into from
Dec 5, 2024

Conversation

alan-agius4
Copy link
Collaborator

@alan-agius4 alan-agius4 commented Dec 5, 2024

Closes #52

Description by Callstackai

This PR improves the handling of pseudo classes and elements in the Beasties library by updating the regex patterns used for normalization.

Diagrams of code changes
sequenceDiagram
    participant Test
    participant Beasties
    participant CSS Parser

    Test->>Beasties: process(HTML with stylesheet)
    Note over Beasties: New pattern added for<br/>pseudo-classes/elements

    Beasties->>CSS Parser: Parse CSS from style.css
    CSS Parser-->>Beasties: Return CSS rules

    Note over Beasties: Remove pseudo-classes/elements<br/>from selectors during normalization
    
    Beasties->>Beasties: normalizedSelector()<br/>Remove :pseudo-classes<br/>Remove ::pseudo-elements
    
    Beasties-->>Test: Return processed HTML with:<br/>- Original pseudo selectors preserved<br/>- Inlined styles in head
Loading
Files Changed
FileSummary
packages/beasties/src/index.tsUpdated regex pattern to handle pseudo classes and elements.
packages/beasties/test/__snapshots__/beasties.test.ts.snapAdded snapshot for new test case involving pseudo classes and elements.
packages/beasties/test/beasties.test.tsAdded a test case to verify the handling of pseudo classes and elements.

This PR includes files in programming languages that we currently do not support. We have not reviewed files with the extensions .ts, .snap. See list of supported languages.

Summary by CodeRabbit

  • New Features

    • Enhanced CSS selector processing to support both pseudo-classes and pseudo-elements.
    • Improved normalization of CSS selectors for better stylesheet handling.
  • Tests

    • Introduced a new test case to verify handling of CSS pseudo-classes and pseudo-elements, ensuring correct processing and logger behaviour.

Copy link

coderabbitai bot commented Dec 5, 2024

Walkthrough

The pull request modifies the Beasties class in packages/beasties/src/index.ts by updating regex patterns for CSS selector processing. The changes introduce a new pattern, removePseudoClassesAndElementsPattern, which enhances the normalization of selectors by capturing both pseudo-classes and pseudo-elements. Additionally, a new test case is added to beasties.test.ts to verify the handling of these selectors, ensuring that the logger behaves correctly during processing. The overall structure and functionality of the Beasties class and its tests remain unchanged.

Changes

File Change Summary
packages/beasties/src/index.ts Updated regex patterns for CSS selector processing; replaced removePseudoElementsPattern and cleanEmptyNotPattern with removePseudoClassesAndElementsPattern. Modified normalizeCssSelector to use the new pattern. No changes to method signatures.
packages/beasties/test/beasties.test.ts Added import for Logger type; introduced new test case "works with pseudo classes and elements" to verify handling of CSS pseudo-classes and pseudo-elements. Existing tests remain unchanged.

Assessment against linked issues

Objective Addressed Explanation
Handle empty sub-selector warnings for pseudo selectors in CSS (Issue #52)

Possibly related PRs

  • perf: cache selector normalization #47: The changes in this PR involve the normalization of CSS selectors, which directly relates to the modifications made in the main PR regarding the regex patterns for CSS selector processing in the Beasties class. Both PRs focus on enhancing the handling of CSS selectors.

Suggested reviewers

  • danielroe

🐰 In the meadow, selectors play,
With pseudo classes, they dance and sway.
Patterns refined, the logs stay clear,
In the world of styles, we have no fear!
Hopping along, our code is bright,
With changes made, all feels just right! 🌼


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

codspeed-hq bot commented Dec 5, 2024

CodSpeed Performance Report

Merging #58 will degrade performances by 46.79%

Comparing alan-agius4:pseudo-elemenets-classes (73a1603) with main (cc55b22)

Summary

⚡ 1 improvements
❌ 2 regressions
✅ 6 untouched benchmarks

⚠️ Please fix the performance issues or acknowledge them on CodSpeed.

Benchmarks breakdown

Benchmark main alan-agius4:pseudo-elemenets-classes Change
run on HTML file 4.8 ms 9 ms -46.79%
should keep existing link tag attributes 1,124.7 µs 978.3 µs +14.96%
should keep existing link tag attributes in the noscript link 1 ms 1.3 ms -20.99%

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 (2)
packages/beasties/test/beasties.test.ts (1)

254-300: Consider enhancing test coverage

The test case effectively validates the handling of pseudo-classes and elements. However, consider adding these scenarios:

  1. Pseudo-elements with parameters (e.g., ::nth-child(2n))
  2. Multiple chained pseudo-classes
  3. Edge cases with escaped colons in selectors
packages/beasties/src/index.ts (1)

29-29: Add documentation for the regex pattern

Consider adding a comment explaining the pattern components:

  • Negative lookbehind for escaped colons
  • Single/double colon matching
  • Parameter capturing
  • Case insensitivity
+// Matches both pseudo-classes (e.g., :hover) and pseudo-elements (e.g., ::before)
+// (?<!\\) - negative lookbehind for escaped colons
+// ::? - matches both single and double colons
+// (?:\(.+\))? - optionally matches parameters within parentheses
 const removePseudoClassesAndElementsPattern = /(?<!\\)::?[a-z-]+(?:\(.+\))?/gi
📜 Review details

Configuration used: CodeRabbit UI
Review profile: CHILL

📥 Commits

Reviewing files that changed from the base of the PR and between cc55b22 and 73a1603.

⛔ Files ignored due to path filters (1)
  • packages/beasties/test/__snapshots__/beasties.test.ts.snap is excluded by !**/*.snap
📒 Files selected for processing (2)
  • packages/beasties/src/index.ts (2 hunks)
  • packages/beasties/test/beasties.test.ts (2 hunks)
🔇 Additional comments (2)
packages/beasties/test/beasties.test.ts (1)

255-260: LGTM!

The logger mock implementation is concise and appropriate for the test requirements.

packages/beasties/src/index.ts (1)

680-682: LGTM!

The implementation effectively handles both pseudo selectors and trailing commas whilst maintaining the existing caching mechanism.

@alan-agius4 alan-agius4 requested a review from danielroe December 5, 2024 11:10
@@ -26,8 +26,7 @@ import { applyMarkedSelectors, markOnly, parseStylesheet, serializeStylesheet, v
import { createDocument, serializeDocument } from './dom'
import { createLogger, isSubpath } from './util'

const removePseudoElementsPattern = /(?<!\\)::?[a-z-]+(?![a-z-(])/gi
const cleanEmptyNotPattern = /::?not\(\s*\)/g
Copy link
Owner

Choose a reason for hiding this comment

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

do we not need to handle an empty ::not()?

Copy link
Collaborator Author

Choose a reason for hiding this comment

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

From my understanding that is not valid
https://developer.mozilla.org/en-US/docs/Web/CSS/:not

Copy link
Owner

Choose a reason for hiding this comment

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

no... curious we were handling it before - maybe it might end up empty based on stripping of unused selectors?

Copy link
Collaborator Author

Choose a reason for hiding this comment

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

Stripping happens at a later stage, and I do not see any failing tests 🤷‍♂️

@danielroe danielroe merged commit e247922 into danielroe:main Dec 5, 2024
8 of 9 checks passed
@codecov-commenter
Copy link

Codecov Report

All modified and coverable lines are covered by tests ✅

Project coverage is 83.95%. Comparing base (cc55b22) to head (73a1603).
Report is 2 commits behind head on main.

Additional details and impacted files
@@            Coverage Diff             @@
##             main      #58      +/-   ##
==========================================
- Coverage   84.89%   83.95%   -0.94%     
==========================================
  Files           7        7              
  Lines        1205     1203       -2     
  Branches      282      281       -1     
==========================================
- Hits         1023     1010      -13     
- Misses        182      193      +11     

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

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.

Empty-sub-selector warning while using pseudo selectors in :has/:where/:is
3 participants