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

chore: use lit for shared components #11

Open
wants to merge 4 commits into
base: main
Choose a base branch
from
Open

chore: use lit for shared components #11

wants to merge 4 commits into from

Conversation

asithade
Copy link
Collaborator

@asithade asithade commented Dec 9, 2024

This pull request includes significant changes to the build process and the footer component. The most important changes include switching to LitElement for the footer component, updating the build scripts, and modifying the styles to use the css tagged template from lit.

Build Process Updates:

  • package.json: Updated the build:browser script to use a new TypeScript-based build script (src/scripts/build-components.ts). Added @types/browserify to the dependencies. [1] [2]
  • src/scripts/build-components.ts: Added a new script to bundle components using browserify and tsify.

Footer Component Refactor:

TypeScript Configuration:

  • src/scripts/tsconfig.json: Enabled experimentalDecorators and disabled emitDecoratorMetadata to support the use of decorators in the project.

Summary by CodeRabbit

  • New Features

    • Enhanced the LFXFooter component with improved rendering capabilities using LitElement.
    • Introduced a new script for automating the bundling of TypeScript component files.
  • Bug Fixes

    • Adjusted styles for better consistency and maintainability across the footer component.
  • Documentation

    • Minor formatting updates to the copyright section for improved readability.
  • Chores

    • Updated TypeScript configuration to enable experimental decorators and adjust metadata emission settings.
    • Added a new dependency for improved type definitions.

Signed-off-by: Asitha de Silva <[email protected]>
Copy link

coderabbitai bot commented Dec 9, 2024

Walkthrough

The pull request introduces several significant changes across multiple files. The package.json file updates the build script for browser components, replacing browserify with ts-node and adding a new dependency. The LFXFooter component is refactored to extend LitElement, enhancing its rendering capabilities and simplifying its structure. Styling for the footer is overhauled using the lit library, improving modularity. Minor adjustments are made to the tokens.json file, while the tsconfig.json files are updated to enable experimental decorators. A new script for bundling components is also introduced.

Changes

File Change Summary
package.json - Updated build:browser script to use ts-node with build-components.ts instead of browserify.
- Added dependency @types/browserify version ^12.0.40.
src/components/footer/footer.component.ts - Refactored LFXFooter to extend LitElement, simplifying the constructor and removing unnecessary methods.
- Added static property styles.
src/components/footer/footer.style.ts - Overhauled styles using lit library's css template literal.
- Updated color properties to use CSS variables for consistency.
src/scripts/build-components.ts - Introduced a new script for bundling TypeScript components using Browserify.
src/scripts/tsconfig.json - Added experimentalDecorators: true and emitDecoratorMetadata: false to compilerOptions.
tsconfig.json - Added experimentalDecorators: true and emitDecoratorMetadata: false to compilerOptions.
src/design/tokens/tokens.json - Added a newline character at the end of the file.

Possibly related PRs

Suggested reviewers

  • MRashad26
  • joanagmaia

🐰 In the meadow, changes bloom,
New scripts and styles make room.
Lit elements dance, colors bright,
A footer that shines with delight!
With decorators now in play,
Our code hops forward, hip-hip-hooray! 🌼


📜 Recent review details

Configuration used: CodeRabbit UI
Review profile: CHILL

📥 Commits

Reviewing files that changed from the base of the PR and between 1247aa9 and 00ba8e2.

📒 Files selected for processing (1)
  • tsconfig.json (1 hunks)
🚧 Files skipped from review as they are similar to previous changes (1)
  • tsconfig.json

🪧 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

🧹 Outside diff range and nitpick comments (3)
src/scripts/build-components.ts (2)

5-5: Consider dynamic component discovery.

Instead of hardcoding component paths, consider using the filesystem to discover components. This would make the build process more maintainable as new components are added.

-const components = ['footer/footer.component.ts'];
+const componentsDir = path.join(__dirname, '../components');
+const components = fs.readdirSync(componentsDir, { recursive: true })
+  .filter((file: string) => file.endsWith('.component.ts'))
+  .map(file => path.relative(componentsDir, file));

1-4: Consider adding configuration options.

The build script could benefit from configuration options to control:

  • Development vs production builds
  • Source map generation
  • Output directory
  • Component inclusion/exclusion patterns

Consider extracting configuration to a separate file:

// build-config.ts
export interface BuildConfig {
  production: boolean;
  sourceMap: boolean;
  outDir: string;
  componentPatterns: string[];
}

export const defaultConfig: BuildConfig = {
  production: process.env.NODE_ENV === 'production',
  sourceMap: true,
  outDir: 'dist/browser',
  componentPatterns: ['**/*.component.ts']
};
src/components/footer/footer.component.ts (1)

21-23: Consider declaring CSS custom properties

For better TypeScript support and documentation, consider declaring the CSS custom properties as static properties.

@customElement('lfx-footer')
export class LFXFooter extends LitElement {
  static styles = style;
+
+  static properties = {
+    '--lfx-footer-bg': { type: String },
+    '--lfx-footer-text': { type: String }
+  };
📜 Review details

Configuration used: CodeRabbit UI
Review profile: CHILL

📥 Commits

Reviewing files that changed from the base of the PR and between 40a1566 and 41b6e65.

⛔ Files ignored due to path filters (1)
  • package-lock.json is excluded by !**/package-lock.json
📒 Files selected for processing (7)
  • package.json (2 hunks)
  • src/components/footer/footer.component.ts (2 hunks)
  • src/components/footer/footer.style.ts (1 hunks)
  • src/design/tokens/tokens.json (1 hunks)
  • src/scripts/build-components.ts (1 hunks)
  • src/scripts/tsconfig.json (1 hunks)
  • tsconfig.json (1 hunks)
✅ Files skipped from review due to trivial changes (1)
  • src/design/tokens/tokens.json
🔇 Additional comments (6)
tsconfig.json (1)

11-13: LGTM! Configuration is appropriate for Lit.

The TypeScript configuration changes are correct for using Lit decorators. Setting experimentalDecorators: true enables the @customElement decorator support while keeping emitDecoratorMetadata: false is appropriate as Lit doesn't require runtime type information.

Let's verify that all component files using decorators are under the configured rootDir:

✅ Verification successful

Configuration is correctly aligned with decorator usage

All TypeScript files, including the Lit component using @customElement decorator, are properly located under the configured src/ directory. The decorator is used only in footer.component.ts with appropriate Lit imports, which aligns perfectly with the TypeScript configuration settings.

🏁 Scripts executed

The following scripts were executed for the analysis:

Script:

#!/bin/bash
# Find all TypeScript files using the @customElement decorator
rg "@customElement" --type ts

# Verify they are all under src/
fd ".ts$" | grep -v "^src/"

Length of output: 130


Script:

#!/bin/bash
# Let's verify the decorator usage and imports more thoroughly
rg "customElement" --type ts -A 2

# Also check for any Lit-related imports
rg "from ['|\"]lit" --type ts

# Double check all TypeScript files location
fd -e ts

Length of output: 1122

src/scripts/tsconfig.json (1)

12-14: LGTM! Configuration maintains consistency.

The TypeScript configuration appropriately mirrors the decorator settings from the root config while maintaining script-specific settings like resolveJsonModule.

package.json (1)

11-11: LGTM: Improved build script organization

Moving the build logic to a dedicated TypeScript file improves maintainability and allows for better error handling and configuration.

src/components/footer/footer.style.ts (1)

14-64: LGTM: Well-structured CSS with proper theming support

The CSS implementation follows best practices:

  • Proper use of CSS variables with fallbacks for theming
  • Well-scoped selectors using :host
  • Consistent styling patterns
src/components/footer/footer.component.ts (2)

Line range hint 9-20: LGTM: Well-documented component API

The JSDoc documentation clearly describes the component's purpose, parts, and CSS properties.


25-42: LGTM: Clean and secure implementation

The render method follows best practices:

  • Proper use of lit's html template literal
  • External links include security attributes (target, rel)
  • Dynamic year calculation

Comment on lines +11 to +18
browserify(`src/components/${component}`)
.plugin('tsify')
.bundle()
.pipe(fs.createWriteStream(bundlePath))
.on('finish', () => {
console.log(`Built ${bundlePath}`);
});
});
Copy link

Choose a reason for hiding this comment

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

🛠️ Refactor suggestion

Add error handling and build optimizations.

The current implementation lacks error handling and build optimizations. Consider these improvements:

  1. Error handling for file operations and bundling
  2. Source maps for debugging
  3. Minification for production builds
  4. Cleanup of existing bundles

Here's a suggested implementation:

+  // Ensure output directory exists
+  fs.mkdirSync(path.dirname(bundlePath), { recursive: true });
+
   browserify(`src/components/${component}`)
     .plugin('tsify')
+    .plugin('errorify') // Add error reporting
+    .transform('uglifyify', { sourceMap: true }) // Add minification
     .bundle()
+    .on('error', (err) => {
+      console.error(`Error building ${componentName}:`, err);
+      process.exit(1);
+    })
     .pipe(fs.createWriteStream(bundlePath))
     .on('finish', () => {
       console.log(`Built ${bundlePath}`);
-    });
+    })
+    .on('error', (err) => {
+      console.error(`Error writing ${bundlePath}:`, err);
+      process.exit(1);
+    });

Don't forget to add these dependencies to package.json:

{
  "devDependencies": {
    "errorify": "^1.0.0",
    "uglifyify": "^5.0.2"
  }
}

@@ -25,6 +25,7 @@
"@storybook/blocks": "^8.4.5",
"@storybook/web-components": "^8.4.5",
"@storybook/web-components-vite": "^8.4.5",
"@types/browserify": "^12.0.40",
Copy link

Choose a reason for hiding this comment

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

💡 Codebase verification

⚠️ Potential version mismatch - browserify dependency missing

The @types/browserify@^12.0.40 types package is added as a dev dependency, but there's no corresponding browserify package in the dependencies. This could lead to runtime issues as the types may not match the actual implementation.

  • Add browserify as a direct dependency in package.json
  • Ensure the browserify version is compatible with the types package (v12.x.x)
🔗 Analysis chain

Verify browserify version compatibility

The added @types/browserify@^12.0.40 types package should be compatible with the installed browserify@^17.0.0. Let's verify this compatibility.

Also applies to: 31-31

🏁 Scripts executed

The following scripts were executed for the analysis:

Script:

#!/bin/bash
# Description: Check browserify types compatibility with installed version
# Get the installed browserify version and types version requirements

echo "Checking browserify package.json..."
cat node_modules/browserify/package.json | jq '.version'

echo "Checking @types/browserify version compatibility..."
cat node_modules/@types/browserify/package.json | jq '.version, ."typescript-version"'

Length of output: 484


Script:

#!/bin/bash
# Let's check the actual versions in package.json first
echo "Checking package.json dependencies..."
cat package.json | jq '.dependencies.browserify, .devDependencies["@types/browserify"]'

# Let's also check if there are any browserify-related files
echo -e "\nChecking for browserify-related files..."
fd browserify

Length of output: 303

Comment on lines +7 to +12
@font-face {
font-family: 'Open Sans', sans-serif;
src: url(https://fonts.googleapis.com/css2?family=Open+Sans:wght@400;600&display=swap) format('truetype');
font-weight: normal;
font-style: normal;
}
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 @font-face declaration for Google Fonts

The current @font-face declaration won't work as intended. Google Fonts should be loaded via a link tag in the HTML or using the CSS @import rule. The current URL points to a CSS file, not a font file.

Consider one of these approaches:

  1. Using CSS @import (preferred for web components):
-  @font-face {
-    font-family: 'Open Sans', sans-serif;
-    src: url(https://fonts.googleapis.com/css2?family=Open+Sans:wght@400;600&display=swap) format('truetype');
-    font-weight: normal;
-    font-style: normal;
-  }
+  @import url('https://fonts.googleapis.com/css2?family=Open+Sans:wght@400;600&display=swap');
  1. Or remove the @font-face and document that the font needs to be loaded by the consuming application.
📝 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
@font-face {
font-family: 'Open Sans', sans-serif;
src: url(https://fonts.googleapis.com/css2?family=Open+Sans:wght@400;600&display=swap) format('truetype');
font-weight: normal;
font-style: normal;
}
@import url('https://fonts.googleapis.com/css2?family=Open+Sans:wght@400;600&display=swap');

Signed-off-by: Asitha de Silva <[email protected]>
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