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

tricky support for container styles #36

Closed
wants to merge 1 commit into from
Closed

tricky support for container styles #36

wants to merge 1 commit into from

Conversation

tiye
Copy link
Member

@tiye tiye commented Dec 10, 2024

mainly for media query and https://developer.mozilla.org/en-US/docs/Web/CSS/@container

Summary by CodeRabbit

  • New Features

    • Introduced a new style container for enhanced styling capabilities.
    • Added functions and macros for creating encapsulated CSS styles.
  • Bug Fixes

    • Updated several dependencies to ensure compatibility and stability.
  • Documentation

    • Updated package versions and dependency specifications across multiple components.

@tiye tiye requested a review from a team December 10, 2024 19:38
Copy link

coderabbitai bot commented Dec 10, 2024

Walkthrough

The pull request includes updates to several Cargo.toml files across multiple packages, reflecting version increments for various dependencies. Notable changes include updates to the uuid, web-sys, js-sys, serde, serde_json, and syn libraries. Additionally, the demo_respo/src/main.rs file has been modified to introduce a new style container and adjust the rendering logic in the view method. The respo/src/node/css.rs file now includes a new function for declaring contained styles and two associated macros to enhance CSS styling capabilities.

Changes

File Path Change Summary
demo_respo/Cargo.toml Updated uuid from 1.10.0 to 1.11.0 and web-sys from 0.3.70 to 0.3.76.
demo_respo/src/main.rs Added contained_styles! macro for style_container and modified view method's class assignment.
respo/Cargo.toml Updated package version from 0.1.14 to 0.1.15, js-sys from 0.3.69 to 0.3.76, serde from 1.0.210 to 1.0.215, serde_json from 1.0.128 to 1.0.133, and web-sys from 0.3.70 to 0.3.76.
respo/src/node/css.rs Added declare_contained_style function and macros contained_style_seq and contained_styles.
respo_state_derive/Cargo.toml Updated syn dependency version from 2.0.77 to 2.0.90.

Sequence Diagram(s)

sequenceDiagram
    participant User
    participant App
    participant CSS

    User->>App: Request View
    App->>CSS: Apply Styles
    CSS->>App: Return Styled View
    App->>User: Render View
Loading

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. (Experiment)
  • @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

@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: 3

📜 Review details

Configuration used: CodeRabbit UI
Review profile: ASSERTIVE

📥 Commits

Reviewing files that changed from the base of the PR and between 1df6885 and 727ecc9.

⛔ Files ignored due to path filters (1)
  • Cargo.lock is excluded by !**/*.lock
📒 Files selected for processing (5)
  • demo_respo/Cargo.toml (1 hunks)
  • demo_respo/src/main.rs (3 hunks)
  • respo/Cargo.toml (3 hunks)
  • respo/src/node/css.rs (2 hunks)
  • respo_state_derive/Cargo.toml (1 hunks)
🔇 Additional comments (6)
respo/src/node/css.rs (1)

867-888: LGTM! Macro implementation is clean and well-documented.

The macro follows established patterns and includes clear documentation with examples.

respo_state_derive/Cargo.toml (1)

Line range hint 14-19: LGTM: Safe dependency update

The update to syn 2.0.90 is a minor version bump that maintains the same feature set. This change is safe and appropriate for macro processing.

demo_respo/Cargo.toml (1)

20-21: 🧹 Nitpick (assertive)

Verify web-sys features for container query support

The web-sys update to 0.3.76 is appropriate, but we should verify that all necessary features for container query support are enabled.

Consider adding ResizeObserver to web-sys features if container size monitoring is needed for the container queries implementation.

Also applies to: 26-46

respo/Cargo.toml (3)

3-3: Version bump aligns with feature addition

The increment to version 0.1.15 is appropriate for adding container styles support.


Line range hint 31-53: Consistent web-sys feature set

The web-sys features list appears comprehensive for DOM manipulation needs. The version update matches demo_respo, maintaining consistency across the workspace.


15-23: Verify dependency version compatibility

The updates to js-sys, serde, and serde_json are minor version changes. However, let's verify there are no breaking changes or security issues.

✅ Verification successful

Let me check for security advisories for serde and serde_json as well, and verify their version consistency across the workspace.


Dependencies are safe and consistently used

The updated dependencies (js-sys 0.3.76, serde 1.0.215, and serde_json 1.0.133) have:

  • No security vulnerabilities reported
  • Consistent usage across the workspace where they appear
  • Minor version updates that maintain backward compatibility
🏁 Scripts executed

The following scripts were executed for the analysis:

Script:

#!/bin/bash
# Check for any security advisories for the updated dependencies
gh api graphql -f query='
{
  securityVulnerabilities(first: 10, ecosystem: RUST, package: "js-sys") {
    nodes {
      advisory {
        summary
        severity
      }
      vulnerableVersionRange
    }
  }
}
'

# Check if versions are consistent across workspace
rg "version = \"0\.3\.76\"" $(fd Cargo.toml)

Length of output: 468


Script:

#!/bin/bash
# Check for security advisories for serde and serde_json
gh api graphql -f query='
{
  serde: securityVulnerabilities(first: 10, ecosystem: RUST, package: "serde") {
    nodes {
      advisory {
        summary
        severity
      }
      vulnerableVersionRange
    }
  }
  serde_json: securityVulnerabilities(first: 10, ecosystem: RUST, package: "serde_json") {
    nodes {
      advisory {
        summary
        severity
      }
      vulnerableVersionRange
    }
  }
}
'

# Check version consistency for serde and serde_json
rg "serde = \{ version = \"1\.0\.215\"" $(fd Cargo.toml)
rg "serde_json = \"1\.0\.133\"" $(fd Cargo.toml)

Length of output: 864

Comment on lines +890 to +931
/// macro to create a public function of CSS rules(up to 5 tuples) at current file scope,
/// ```rust
/// respo::static_styles!(the_name,
/// ("&", respo::css::respo_style())
/// );
/// ```
/// gets a function like:
/// ```ignore
/// pub fn the_name() -> String
/// ```
/// if you have more styles to specify, use `static_style_seq!` instead.
#[macro_export]
macro_rules! contained_styles {
($a:ident, $b:expr) => {
$crate::contained_style_seq!($a, &[$b]);
};
// to allow optional trailing comma
($a:ident, $b:expr,) => {
$crate::contained_style_seq!($a, &[$b]);
};
($a:ident, $b:expr, $c:expr) => {
$crate::contained_style_seq!($a, &[$b, $c]);
};
($a:ident, $b:expr, $c:expr,) => {
$crate::contained_style_seq!($a, &[$b, $c]);
};
($a:ident, $b:expr, $c:expr, $d:expr) => {
$crate::contained_style_seq!($a, &[$b, $c, $d]);
};
($a:ident, $b:expr, $c:expr, $d:expr,) => {
$crate::contained_style_seq!($a, &[$b, $c, $d]);
};
($a:ident, $b:expr, $c:expr, $d:expr, $e:expr) => {
$crate::contained_style_seq!($a, &[$b, $c, $d, $e]);
};
($a:ident, $b:expr, $c:expr, $d:expr, $e:expr,) => {
$crate::contained_style_seq!($a, &[$b, $c, $d, $e]);
};
($a:ident, $b:expr, $c:expr, $d:expr, $e:expr, $f:expr) => {
$crate::contained_style_seq!($a, &[$b, $c, $d, $e, $f]);
};
}
Copy link

Choose a reason for hiding this comment

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

🧹 Nitpick (assertive)

Fix macro name in documentation example.

The documentation example incorrectly references static_styles! instead of contained_styles!.

Apply this fix to the documentation:

 /// ```rust
-/// respo::static_styles!(the_name,
+/// respo::contained_styles!(the_name,
 ///   ("&", respo::css::respo_style())
 /// );
 /// ```

Comment on lines +739 to +787
/// does internal work inside the macro `contained_style!(name, &styles)`.
/// inserts CSS as `<style .. />` under `<head ... />` element
/// notice that the code only generats once and being cached as DOM states, with extra `<contained> { ... }` wrapper
///
/// NOT working for dynamic styles that changes over time, use inline styles instead.
pub fn declare_contained_style<T, U>(name: T, rules: &[(Option<String>, U, RespoStyle)]) -> String
where
T: Into<String> + Clone,
U: Into<String> + Clone + Display,
{
let mut defined_styles = CLASS_NAME_IN_TAGS.write().expect("access styles");
if defined_styles.contains(&name.to_owned().into()) {
name.into()
} else {
let window = web_sys::window().expect("window");
let document = window.document().expect("load document");
let head = document.head().expect("head");
let style_tag = document.create_element("style").expect("create style tag");
style_tag
.set_attribute("id", &format!("def__{}", name.to_owned().into()))
.expect("name tag");

let mut styles = String::from("");
for (contained, query, properties) in rules {
styles.push_str(
&query
.to_string()
.replace("$0", &format!(".{}", &name.to_owned().into()))
.replace('&', &format!(".{}", &name.to_owned().into())),
);
styles.push_str(" {\n");
styles.push_str(&properties.to_string());
styles.push_str("}\n");

if let Some(contained) = contained {
styles = format!("{} {{\n{}\n}}", contained, styles);
}
}

style_tag.dyn_ref::<Element>().expect("into element").set_inner_html(&styles);
head
.append_child(style_tag.dyn_ref::<Element>().expect("get element"))
.expect("add style");

defined_styles.insert(name.to_owned().into());

name.into()
}
}
Copy link

Choose a reason for hiding this comment

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

🧹 Nitpick (assertive)

LGTM! Consider enhancing error handling.

The implementation is clean and follows existing patterns well. The container query support is implemented correctly.

Consider using custom error types instead of expect() calls for better error handling. For example:

-  let mut defined_styles = CLASS_NAME_IN_TAGS.write().expect("access styles");
+  let mut defined_styles = CLASS_NAME_IN_TAGS.write().map_err(|e| 
+    format!("Failed to access styles: {}", e))?;

Committable suggestion skipped: line range outside the PR's diff.

Comment on lines +101 to +108
contained_styles!(
style_container,
(
Some("@media only screen and (max-width: 600px)".to_owned()),
"&",
respo_style().background_color(respo::css::CssColor::Hsl(0, 0, 95))
)
);
Copy link

Choose a reason for hiding this comment

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

🧹 Nitpick (assertive)

LGTM! Consider mobile-first approach.

The container styles implementation is correct, but consider using a mobile-first approach with min-width instead of max-width for better responsive design practices.

Consider this alternative approach:

 contained_styles!(
   style_container,
   (
-    Some("@media only screen and (max-width: 600px)".to_owned()),
+    Some("@media only screen and (min-width: 600px)".to_owned()),
     "&",
-    respo_style().background_color(respo::css::CssColor::Hsl(0, 0, 95))
+    respo_style().background_color(respo::css::CssColor::Hsl(0, 0, 100))
   )
 );
📝 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
contained_styles!(
style_container,
(
Some("@media only screen and (max-width: 600px)".to_owned()),
"&",
respo_style().background_color(respo::css::CssColor::Hsl(0, 0, 95))
)
);
contained_styles!(
style_container,
(
Some("@media only screen and (min-width: 600px)".to_owned()),
"&",
respo_style().background_color(respo::css::CssColor::Hsl(0, 0, 100))
)
);

@tiye tiye closed this Dec 10, 2024
@tiye tiye deleted the contained branch December 10, 2024 19:45
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