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

Enhance the TypeScript types #27

Merged
merged 2 commits into from
Nov 10, 2024
Merged

Enhance the TypeScript types #27

merged 2 commits into from
Nov 10, 2024

Conversation

5ouma
Copy link
Owner

@5ouma 5ouma commented Nov 10, 2024

⚠️ Issue

close #


✏️ Description

Avoid slow types and make objects read-only.


🔄 Type of the Change

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

@prlabeler prlabeler bot added the 🧹 Refactoring A code change that neither fixes a bug nor adds a feature label Nov 10, 2024
Copy link

codecov bot commented Nov 10, 2024

Codecov Report

All modified and coverable lines are covered by tests ✅

Project coverage is 100.00%. Comparing base (bf87e2b) to head (b82befe).
Report is 1 commits behind head on main.

✅ All tests successful. No failed tests found.

Additional details and impacted files
@@            Coverage Diff            @@
##              main       #27   +/-   ##
=========================================
  Coverage   100.00%   100.00%           
=========================================
  Files           11        11           
  Lines          153       153           
  Branches        16        16           
=========================================
  Hits           153       153           

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

Copy link
Contributor

github-actions bot commented Nov 10, 2024

🔦 Lighthouse Result

performance accessibility best-practices seo
🟢 92 🟢 100 🟢 100 🟧 63
📊 Score Scale
Fail Average Pass
🔺 0-49 🟧 50-89 🟢 90-100

Copy link

coderabbitai bot commented Nov 10, 2024

Walkthrough

This pull request modifies several files to enhance type safety and immutability across the application. In src/libs/contact.ts, the service type is renamed to serviceName, and the contact type is exported as a read-only type. A new info type is introduced in src/types/services.ts, defining the structure of service objects. Additionally, components like Contact.astro and Homepage.astro are updated to reflect these type changes, streamlining property access and enforcing the new type structures.

Changes

File Change Summary
src/libs/contact.ts - Renamed service type to serviceName.
- Exported contact type as Readonly<{ url: string; icon: string; color: string }>.
- Updated getContact and isFediverse function signatures to use serviceName.
src/types/services.ts - Introduced new type info for service objects with properties url, icon, and color.
- Modified services constant to be typed as const satisfies Record<string, info>.
- Renamed service type to serviceName.
src/components/Bio/Bio.astro - Refactored property access by destructuring Astro.props for name, description, and icon.
src/components/Contact/Contact.astro - Updated Props type to use serviceName.
- Modified destructuring of Astro.props to directly extract service and id.
- Updated JSX to use destructured variables.
src/components/Homepage/Homepage.astro - Changed Props type to Readonly<{ url: string }>.
- Updated props variable to enforce the new Readonly type.
src/types/meta.ts - Updated meta type to be Readonly.
- Changed contacts property type to use serviceName.

Possibly related PRs

  • Add contact component #9: The changes in src/types/services.ts regarding the renaming of the service type to serviceName are directly related to the main PR's updates in src/libs/contact.ts, where the same type renaming occurs.
  • Add more test cases for anomalous conditions #10: The modifications in src/components/Contact/Contact.astro to replace service with serviceName align with the changes made in the main PR, which also updates the getContact function to use serviceName.
  • Hover to change the color #21: The updates in src/libs/contact.ts to include a new color property in the contact type and the getContact function are relevant as they enhance the structure of the contact information, which is also utilized in the Contact.astro component.
  • Improve image a11y #24: The changes to the aria-label in src/components/Contact/Contact.astro improve accessibility and are relevant to the overall enhancements made in the main PR regarding the contact type and its properties.

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

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

🧹 Outside diff range and nitpick comments (1)
src/types/services.ts (1)

1-5: Consider improving the type definition.

  1. The type name info is too generic. Consider a more specific name like ServiceConfig or ContactServiceInfo to better convey its purpose.
  2. The type should be exported since it's used in the exported services constant.
  3. Consider adding JSDoc comments to document the purpose of each field.
+/**
+ * Configuration for a contact service
+ */
-type info = {
+export type ServiceConfig = {
+  /** The base URL for the service */
   url: string;
+  /** The icon identifier from the icon set */
   icon: string;
+  /** The brand color in hex format */
   color: string;
 };
🛑 Comments failed to post (1)
src/libs/contact.ts (1)

24-24: 🛠️ Refactor suggestion

Improve type safety by properly declaring readonly types.

The as const assertion makes the returned object readonly, but this contradicts the mutable contact type declaration. This could lead to type inconsistencies where the object is treated as readonly in some places but mutable in others.

Consider this approach instead:

-type contact = { url: string; icon: string; color: string };
+type contact = Readonly<{ url: string; icon: string; color: string }>;

 export const getContact = (service: service, id: string): contact => {
   // ...
-  return { url, icon: specified.icon, color: specified.color } as const;
+  return { url, icon: specified.icon, color: specified.color };
 };

This change:

  1. Makes the contact type explicitly readonly
  2. Ensures consistent immutability throughout the codebase
  3. Removes the need for as const assertion
  4. Better aligns with TypeScript's type system

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

Avoid slow types and make objects readonly.
@5ouma 5ouma force-pushed the refactor-ts-types branch from efea44c to 27e6c7c Compare November 10, 2024 06:53
Signed-off-by: Souma <101255979+5ouma@users.noreply.github.com>
@5ouma
Copy link
Owner Author

5ouma commented Nov 10, 2024

@coderabbitai full 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.

Actionable comments posted: 0

🧹 Outside diff range and nitpick comments (7)
src/types/meta.ts (2)

1-1: Remove the file extension from the import statement.

TypeScript/JavaScript imports typically work better without file extensions. Some bundlers might have issues with explicit ".ts" extensions.

-import type { serviceName } from "./services.ts";
+import type { serviceName } from "./services";

3-9: LGTM! Great improvements to type safety.

The changes effectively enhance type safety by:

  • Making the meta type immutable with Readonly
  • Ensuring contact objects are immutable
  • Using the standardized serviceName type

Consider extracting the contact type to improve reusability:

+type Contact = Readonly<{ service: serviceName; id: string }>;
+
 export type meta = Readonly<{
   name: string;
   description: string;
   icon: string;
-  contacts: Readonly<{ service: serviceName; id: string }>[];
+  contacts: Contact[];
   homepage: string;
 }>;
src/libs/contact.ts (2)

7-7: LGTM! Enhanced type safety with readonly properties.

Making the type readonly prevents accidental mutations, which is a good practice.

Consider adding URL validation to the url property using a template literal type for additional type safety:

type ValidUrl = `https://${string}`;
export type contact = Readonly<{ url: ValidUrl; icon: string; color: string }>;

Line range hint 9-24: Consider performance and type safety improvements.

The function implementation is correct, but could benefit from some optimizations.

Consider these improvements:

 export const getContact = (service: serviceName, id: string): contact => {
   const specified: contact = services[service];
 
   if (!specified) throw new Error(`Unsupported service: ${service}`);
 
+  // Memoize this check to avoid repeated string comparisons
+  const isServiceFediverse = isFediverse(service);
- 
-  if (isFediverse(service)) {
+  if (isServiceFediverse) {
     const parts: string[] = id.split("@");
     if (parts.length !== 3 || parts[0] !== "") {
       throw new Error(`Invalid ${service} ID format`);
     }
   }
 
-  const url: string = isFediverse(service)
+  const url: string = isServiceFediverse
     ? `https://${id.split("@")[2]}/${id}`
     : specified.url + id;
   return { url, icon: specified.icon, color: specified.color };
 };

This change:

  1. Memoizes the Fediverse check to avoid repeated function calls
  2. Improves readability by using a more descriptive variable name
src/types/services.ts (2)

1-5: Consider enhancing type safety with readonly and stricter types.

The info type could be strengthened with:

  1. Readonly properties to prevent accidental mutations
  2. Template literal type for URL to ensure valid URL formats
  3. More specific type for color to ensure valid CSS colors
-type info = {
-  url: string;
-  icon: string;
-  color: string;
-};
+type info = {
+  readonly url: `https://${string}` | `mailto:${string}`;
+  readonly icon: string;
+  readonly color: string | ''; // Consider using a union of specific color values
+};

53-53: LGTM! Type assertion ensures both immutability and type safety.

The use of as const satisfies Record<string, info> is excellent as it:

  1. Makes the object deeply readonly
  2. Ensures type checking while preserving literal types

Consider grouping similar services (e.g., social media, communication) using nested objects for better maintainability:

export const services = {
  social: {
    Bluesky: { /* ... */ },
    Facebook: { /* ... */ },
    // ...
  },
  communication: {
    Mail: { /* ... */ }
  }
} as const satisfies Record<string, Record<string, info>>;
src/components/Contact/Contact.astro (1)

9-9: Consider leveraging TypeScript's type inference.

While the current implementation is correct, the explicit type annotation on the destructuring assignment might be unnecessary since TypeScript can infer the types from getContact's return type.

-const { url, icon, color }: contact = getContact(service, id);
+const { url, icon, color } = getContact(service, id);

Also applies to: 11-11

📜 Review details

Configuration used: CodeRabbit UI
Review profile: CHILL

📥 Commits

Reviewing files that changed from the base of the PR and between bf87e2b and b82befe.

📒 Files selected for processing (6)
  • src/components/Bio/Bio.astro (1 hunks)
  • src/components/Contact/Contact.astro (2 hunks)
  • src/components/Homepage/Homepage.astro (2 hunks)
  • src/libs/contact.ts (1 hunks)
  • src/types/meta.ts (1 hunks)
  • src/types/services.ts (2 hunks)
🔇 Additional comments (12)
src/libs/contact.ts (2)

1-1: LGTM! Improved type naming.

The rename from service to serviceName is more descriptive and better represents the type's purpose.


3-5: LGTM! Clean and type-safe implementation.

The function is well-typed and correctly identifies Fediverse services.

src/components/Bio/Bio.astro (3)

11-11: LGTM: Clean props destructuring

The destructuring of props follows Astro's best practices and improves code readability by eliminating repetitive props. prefixes while maintaining type safety.


16-19: LGTM: Clean property references

The template correctly uses the destructured properties, maintaining the same functionality while improving code readability.


16-16: Verify the inferSize prop usage

The inferSize={true} prop on the Image component automatically infers image dimensions at build time. Ensure this is intentional as it affects build-time behavior and could impact performance if the images are large or frequently updated.

✅ Verification successful

Let me gather more information about the Image component usage and configuration to better understand the context.


The inferSize prop usage is appropriate and follows best practices

The usage of inferSize={true} in the Image component is correct and well-implemented:

  • It's using the official astro:assets Image component (version 4.16.10)
  • The prop is only used once in the codebase, specifically for the avatar image in the Bio component
  • Being an avatar image, it's likely a small, static asset where build-time dimension inference is beneficial for layout stability
🏁 Scripts executed

The following scripts were executed for the analysis:

Script:

#!/bin/bash
# Description: Check for consistent usage of inferSize prop across Image components
# and verify image file locations

# Check for Image component usage patterns
echo "Checking Image component usage patterns:"
rg -A 2 "Image.*inferSize" 

# Find all image files to verify they're properly located
echo -e "\nLocating image files referenced in components:"
fd -e png -e jpg -e jpeg -e gif -e webp -e avif

Length of output: 461


Script:

#!/bin/bash
# Check for Image component imports and configuration
echo "Checking Image component imports and configuration:"
rg "import.*Image.*from.*astro" -A 2

# Look for Image component documentation or type definitions
echo -e "\nLooking for Image component documentation:"
fd "astro.d.ts|Image.d.ts|Image.ts"

# Check package.json for astro version
echo -e "\nChecking Astro version:"
cat package.json | grep "astro"

Length of output: 851

src/types/services.ts (1)

55-55: Verify the type rename impact across the codebase.

The rename from service to serviceName is more descriptive and the type derivation using keyof typeof is correct.

Let's verify all usages have been updated:

✅ Verification successful

Type rename has been properly updated across the codebase

The verification shows that:

  • No references to the old service type definition remain
  • All usages of serviceName are properly imported and used consistently across the codebase:
    • Imported in meta.ts, contact.ts, and Contact.astro
    • Used correctly in function parameters and type definitions
🏁 Scripts executed

The following scripts were executed for the analysis:

Script:

#!/bin/bash
# Description: Check for any remaining uses of the old type name and verify new type usage

# Test 1: Check for any remaining 'service' type references
echo "Checking for old 'service' type references..."
rg "type\s+service\s*=" || rg ":\s*service[\s;]"

# Test 2: Verify all new 'serviceName' usages
echo "Checking new 'serviceName' usage..."
rg "serviceName"

Length of output: 927

src/components/Contact/Contact.astro (4)

4-5: LGTM! Import changes improve type clarity.

The rename from service to serviceName is more descriptive and the addition of the contact type import enhances type safety.


8-8: LGTM! Props type updated consistently.

The Props type definition correctly reflects the type rename from service to serviceName.


15-15: LGTM! Template changes improve maintainability and accessibility.

The use of destructured properties simplifies the code, and the aria-label provides clear context for screen readers.

Also applies to: 18-18, 20-20


Line range hint 24-36: LGTM! Styling implementation is clean and maintainable.

The use of CSS custom properties and well-defined transitions creates a polished user experience.

src/components/Homepage/Homepage.astro (2)

8-9: LGTM! Type safety improvements look good.

The changes enhance type safety by:

  1. Making the Props type readonly, preventing accidental mutations
  2. Adding explicit type annotation to props variable

This aligns well with the PR objectives of improving TypeScript types and making objects read-only.


38-38: Skip reviewing this formatting change.

This is just an empty line addition for better code formatting.

@5ouma 5ouma merged commit 82a151b into main Nov 10, 2024
12 checks passed
@5ouma 5ouma deleted the refactor-ts-types branch November 10, 2024 09:34
@github-actions github-actions bot mentioned this pull request Nov 10, 2024
@coderabbitai coderabbitai bot mentioned this pull request Nov 16, 2024
11 tasks
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
🧹 Refactoring A code change that neither fixes a bug nor adds a feature
Projects
None yet
Development

Successfully merging this pull request may close these issues.

1 participant