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

Add contact component #9

Merged
merged 5 commits into from
Nov 8, 2024
Merged

Add contact component #9

merged 5 commits into from
Nov 8, 2024

Conversation

5ouma
Copy link
Owner

@5ouma 5ouma commented Nov 8, 2024

⚠️ Issue

close #


✏️ Description

Select a service from the list.
Render a clickable component with an icon and URL.


🔄 Type of the Change

  • 🎉 New Feature
  • 🧰 Bug
  • 🛡️ Security
  • 📖 Documentation
  • 🏎️ Performance
  • 🧹 Refactoring
  • 🧪 Testing
  • 🔧 Maintenance
  • 🎽 CI
  • 🧠 Meta

bun.lockb Show resolved Hide resolved
Copy link

codecov bot commented Nov 8, 2024

Codecov Report

All modified and coverable lines are covered by tests ✅

Project coverage is 100.00%. Comparing base (2aecf4d) to head (e478f13).
Report is 2 commits behind head on main.

✅ All tests successful. No failed tests found.

Additional details and impacted files
@@            Coverage Diff            @@
##              main        #9   +/-   ##
=========================================
  Coverage   100.00%   100.00%           
=========================================
  Files            5         9    +4     
  Lines           42       132   +90     
  Branches         4         8    +4     
=========================================
+ Hits            42       132   +90     

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

5ouma added 4 commits November 8, 2024 21:36
Return a URL to the profile and service icon.
This component is clickable to access there.
Preview all icons and texts.
Check whether the components are rendered as expected.
@5ouma 5ouma force-pushed the feat-component-contact branch from 8a9b660 to 3db70fd Compare November 8, 2024 12:36
Copy link

coderabbitai bot commented Nov 8, 2024

Walkthrough

The pull request introduces several enhancements to the "mobicard" project, including the addition of a new dependency @iconify-json/simple-icons in package.json. A new Contact component is created in src/components/Contact/Contact.astro, which fetches and displays contact information with icons. Corresponding story and test files are added to showcase and validate the component's functionality. Additionally, a utility function getContact is introduced in src/libs/contact.ts to manage contact data, alongside a new services constant in src/types/services.ts for service types.

Changes

File Change Summary
package.json Added dependency: "@iconify-json/simple-icons": "1.2.11" in dependencies.
src/components/Contact/Contact.astro Introduced a new component that renders a contact link with props for service and id.
src/components/Contact/Contact.stories.ts Added a new story file for the Contact component with multiple named exports for various social media links.
src/components/Contact/Contact.test.ts Introduced a test suite for the Contact component, validating rendering based on story configurations.
src/components/Contact/story.ts Added constants for social media services, each typed with Props.
src/libs/contact.ts Introduced getContact function to fetch contact data based on service and id.
src/types/services.ts Added services constant for social media platforms and service type for type-safe access.

Possibly related PRs

  • Add bio component #5: The changes in this PR introduce a new bio component that includes an icon, which may relate to the newly added dependency @iconify-json/simple-icons in the main PR, as both involve icon usage in the project.

Suggested labels

🎉 New Feature

Warning

Tool Failures:

Tool Failure Count:


📜 Recent review details

Configuration used: CodeRabbit UI
Review profile: CHILL

📥 Commits

Reviewing files that changed from the base of the PR and between 3db70fd and e478f13.

📒 Files selected for processing (1)
  • src/types/services.ts (1 hunks)
🚧 Files skipped from review as they are similar to previous changes (1)
  • src/types/services.ts

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.

@5ouma
Copy link
Owner Author

5ouma commented Nov 8, 2024

@coderabbitai review

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.

Caution

Inline review comments failed to post. This is likely due to GitHub's limits when posting large numbers of comments.

Actionable comments posted: 6

🧹 Outside diff range and nitpick comments (7)
src/libs/contact.ts (2)

1-3: Consider a more specific type name.

The type name contact could be more specific to better represent its purpose, such as ContactInfo or ContactDetails.

-type contact = { url: string; icon: string };
+type ContactInfo = { url: string; icon: string };

5-11: Consider adding unit tests for edge cases.

The function handles complex URL construction and should be thoroughly tested for various scenarios:

  • Invalid Mastodon/Misskey IDs
  • Special characters in IDs
  • Missing or malformed service configurations

Would you like me to help generate comprehensive unit tests for this function?

src/types/services.ts (2)

1-36: Consider standardizing icon sources.

The services object uses icons from two different sources:

  • mingcute: Most services
  • simple-icons: Posts and Misskey

Consider standardizing to one icon set for consistency, or document why different sources are needed.


1-36: Consider adding service configuration types.

Adding TypeScript interfaces for service configurations would improve type safety and documentation.

Consider adding:

interface ServiceConfig {
  url?: string;
  icon: string;
}

export const services: Record<string, ServiceConfig> = {
  // ... existing configurations
};
src/components/Contact/story.ts (1)

3-46: Consider restructuring for better maintainability.

The current structure exports individual constants. Consider grouping them in a single object for easier maintenance and access:

-export const Bluesky: Props = {
+export const CONTACT_SERVICES = {
+ Bluesky: {
   service: "Bluesky",
   id: "bsky.app",
-};
+} as Props,

-export const Facebook: Props = {
+ Facebook: {
   service: "Facebook",
   id: "facebook",
-};
+} as Props,
// ... other services
} as const;

This approach would:

  • Centralize all service definitions
  • Make it easier to add/remove services
  • Allow for easier type checking and maintenance
src/components/Contact/Contact.astro (2)

6-6: Consider using scoped CSS instead of global CSS import.

Importing global CSS in a component can lead to style leaks and make the component less isolated. Consider moving any necessary styles to the component's scoped <style> block to maintain better encapsulation.


24-45: Enhance link accessibility and user experience.

The link styling could be improved for better user experience and accessibility:

  1. Missing hover/focus states
  2. No indication of external link
  3. Font family fallback not specified

Consider adding these style improvements:

 a {
   display: inline-flex;
   align-items: center;
   gap: 0.5rem;
   text-decoration: none;
   color: var(--foreground);
+  transition: opacity 0.2s ease;
+ }
+
+ a:hover, a:focus {
+  opacity: 0.8;
+  text-decoration: underline;
 }

 span {
-  font-family: "LINE Seed JP";
+  font-family: "LINE Seed JP", system-ui, sans-serif;
   font-size: 1rem;
   font-style: normal;
   font-weight: bold;
   line-height: normal;
 }
🛑 Comments failed to post (6)
src/libs/contact.ts (3)

5-11: 🛠️ Refactor suggestion

Add type guards for the services object.

The function assumes the service will always exist in the services object. Add runtime checks to ensure type safety.

 export const getContact = (service: service, id: string): contact => {
+  if (!services[service]) {
+    throw new Error(`Unsupported service: ${service}`);
+  }
+
   const url: string = ...

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


5-11: ⚠️ Potential issue

Add input validation and error handling.

The function lacks validation for the id parameter and proper error handling. This could lead to runtime errors or security issues.

Consider implementing these safety measures:

 export const getContact = (service: service, id: string): contact => {
+  if (!id || typeof id !== 'string') {
+    throw new Error('Invalid ID provided');
+  }
+
   const url: string =
     service === "Mastodon" || service === "Misskey"
-      ? `https://${id.split("@")[2]}/${id}`
+      ? (() => {
+          const parts = id.split("@");
+          if (parts.length !== 3) {
+            throw new Error(`Invalid ${service} ID format. Expected format: @user@domain`);
+          }
+          return `https://${parts[2]}/${encodeURIComponent(id)}`;
+        })()
-      : services[service].url + id;
+      : services[service].url + encodeURIComponent(id);
   return { url, icon: services[service].icon };
 };
📝 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.

export const getContact = (service: service, id: string): contact => {
  if (!id || typeof id !== 'string') {
    throw new Error('Invalid ID provided');
  }

  const url: string =
    service === "Mastodon" || service === "Misskey"
      ? (() => {
          const parts = id.split("@");
          if (parts.length !== 3) {
            throw new Error(`Invalid ${service} ID format. Expected format: @user@domain`);
          }
          return `https://${parts[2]}/${encodeURIComponent(id)}`;
        })()
      : services[service].url + encodeURIComponent(id);
  return { url, icon: services[service].icon };
};

5-11: 💡 Codebase verification

Services configuration needs attention for Mastodon and Misskey

The verification revealed that while most services have both url and icon properties, Mastodon and Misskey services are missing the url property in the configuration. This aligns with the special URL handling in the getContact function for these services, but it should be documented or made consistent with other services.

  • src/types/services.ts: Mastodon and Misskey entries lack the url property while all other services have both url and icon
  • The special URL handling in getContact compensates for this inconsistency by constructing the URL from the ID parameter
🔗 Analysis chain

Verify the integration with services configuration.

Need to ensure that the services object contains the expected URL formats and icon definitions for all supported services.


Let me try a different approach to verify the services configuration.


Let me try one more time with corrected regex patterns.


Let me check the content of the services configuration file we found.

🏁 Scripts executed

The following scripts were executed for the analysis:

Script:

#!/bin/bash
# Description: Verify the services configuration structure

# Test 1: Check if services.ts exists and contains required properties
echo "Checking services configuration..."
rg -A 10 "export const services = {" "../types/services.ts"

# Test 2: Verify all services have required properties
ast-grep --pattern 'services = {
  $$$
  $_: { url: $_, icon: $_ }
  $$$
}'

Length of output: 330


Script:

#!/bin/bash
# Search for services configuration in the entire codebase
echo "Searching for services configuration..."
rg "services\s*=\s*{" -A 10

# Also check for any type definitions related to services
echo -e "\nChecking service-related type definitions..."
rg "type.*Service" -A 5

Length of output: 345


Script:

#!/bin/bash
# Search for services configuration
echo "Searching for services configuration..."
rg "services = {" -A 10

# Search for service type definitions and imports
echo -e "\nChecking for service types and imports..."
rg "type.*service" -i

# Search for files that might contain services configuration
echo -e "\nListing potential service configuration files..."
fd -t f -e ts -e js services

Length of output: 822


Script:

#!/bin/bash
# Display the content of services.ts
echo "Content of services configuration file:"
cat src/types/services.ts

Length of output: 897

src/components/Contact/Contact.test.ts (1)

7-16: 🛠️ Refactor suggestion

Enhance test coverage for the Contact component.

The current test suite only verifies the presence of the ID in the output. Consider adding tests for:

  1. Link generation and href validation
  2. Icon rendering
  3. Error cases (invalid service, missing ID)
  4. Accessibility attributes
  5. Different service types from the stories

Here's a suggested enhancement:

 describe("Contact", () => {
   for (const [name, props] of Object.entries(stories)) {
     test(name, async () => {
       const container: AstroContainer = await AstroContainer.create();
       const result: string = await container.renderToString(Contact, { props });
 
       expect(result).toContain(`>${props.id}</span>`);
+      // Verify link generation
+      expect(result).toMatch(new RegExp(`href=["']${props.service}.*${props.id}["']`));
+      
+      // Verify icon presence
+      expect(result).toContain('class="iconify"');
+      
+      // Verify accessibility
+      expect(result).toContain('aria-label');
     });
   }
+  
+  test("handles invalid service", async () => {
+    const container: AstroContainer = await AstroContainer.create();
+    const invalidProps = { service: "invalid", id: "test" };
+    
+    await expect(
+      container.renderToString(Contact, { props: invalidProps })
+    ).rejects.toThrow();
+  });
 });

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

src/types/services.ts (1)

18-23: ⚠️ Potential issue

Add URL configurations for Mastodon and Misskey services.

Mastodon and Misskey are federated platforms where users can be on different instances. Consider:

  1. Adding a URL pattern that accepts instance URL
  2. Documenting the expected format for these services

Here's a suggested implementation:

  Mastodon: {
+   url: "https://",  // Instance URL will be prepended
    icon: "mingcute:mastodon-line",
  },
  Misskey: {
+   url: "https://",  // Instance URL will be prepended
    icon: "simple-icons:misskey",
  },

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

src/components/Contact/story.ts (1)

43-46: ⚠️ Potential issue

Replace example.com email with actual contact email.

The current email address uses a placeholder domain. Please update it with the actual contact email address for the application.

It's hard to treat the different type of objects.
@5ouma 5ouma merged commit 7b7edac into main Nov 8, 2024
11 checks passed
@5ouma 5ouma deleted the feat-component-contact branch November 8, 2024 13:52
@github-actions github-actions bot mentioned this pull request Nov 8, 2024
@5ouma 5ouma added the 🎉 New Feature Introduce a new feature label Nov 8, 2024
@github-actions github-actions bot mentioned this pull request Nov 9, 2024
5ouma pushed a commit that referenced this pull request Nov 9, 2024
<!-- Release notes generated using configuration in .github/release.yml at main -->

* Add bio component by @5ouma in #5
* Add homepage component by @5ouma in #7
* Add contact component by @5ouma in #9
* Add index page and default layout template by @5ouma in #13
* Astro requires in-file CSS for scoping by @5ouma in #6
* Add README and license by @5ouma in #11
* Exclude Astro and Astrobook related by @5ouma in #8
* Add more test cases for anomalous conditions by @5ouma in #10
* Allow commenting on commits by @5ouma in #3
* Deploy and analyze performance by @5ouma in #12
* Quote meta file variable by @5ouma in #14
* Change the environment variable for repository name by @5ouma in #15
* Don't treat the input as JSON by @5ouma in #16
* chore(deps): pin koki-develop/bun-diff-action action to 22bcd25 by @renovate in #4

* @5ouma made their first contribution in #1
* @renovate made their first contribution in #4
* @github-actions made their first contribution in #2

**Full Changelog**: https://github.com/5ouma/mobicard/commits/v0.1.0
github-actions bot added a commit that referenced this pull request Nov 9, 2024
<!-- Release notes generated using configuration in .github/release.yml at main -->

* Add bio component by @5ouma in #5
* Add homepage component by @5ouma in #7
* Add contact component by @5ouma in #9
* Add index page and default layout template by @5ouma in #13
* Astro requires in-file CSS for scoping by @5ouma in #6
* Add README and license by @5ouma in #11
* Exclude Astro and Astrobook related by @5ouma in #8
* Add more test cases for anomalous conditions by @5ouma in #10
* Allow commenting on commits by @5ouma in #3
* Deploy and analyze performance by @5ouma in #12
* Quote meta file variable by @5ouma in #14
* Change the environment variable for repository name by @5ouma in #15
* Don't treat the input as JSON by @5ouma in #16
* chore(deps): pin koki-develop/bun-diff-action action to 22bcd25 by @renovate in #4

* @5ouma made their first contribution in #1
* @renovate made their first contribution in #4
* @github-actions made their first contribution in #2

**Full Changelog**: https://github.com/5ouma/mobicard/commits/v0.1.0
github-actions bot added a commit that referenced this pull request Nov 9, 2024
<!-- Release notes generated using configuration in .github/release.yml at main -->

* Add bio component by @5ouma in #5
* Add homepage component by @5ouma in #7
* Add contact component by @5ouma in #9
* Add index page and default layout template by @5ouma in #13
* Astro requires in-file CSS for scoping by @5ouma in #6
* Add README and license by @5ouma in #11
* Exclude Astro and Astrobook related by @5ouma in #8
* Add more test cases for anomalous conditions by @5ouma in #10
* Allow commenting on commits by @5ouma in #3
* Deploy and analyze performance by @5ouma in #12
* Quote meta file variable by @5ouma in #14
* Change the environment variable for repository name by @5ouma in #15
* Don't treat the input as JSON by @5ouma in #16
* chore(deps): pin koki-develop/bun-diff-action action to 22bcd25 by @renovate in #4

* @5ouma made their first contribution in #1
* @renovate made their first contribution in #4
* @github-actions made their first contribution in #2

**Full Changelog**: https://github.com/5ouma/mobicard/commits/v0.1.0
@coderabbitai coderabbitai bot mentioned this pull request Nov 22, 2024
11 tasks
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
🎉 New Feature Introduce a new feature
Projects
None yet
Development

Successfully merging this pull request may close these issues.

1 participant