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: #321 use date-fns for localized datetime formatting #345

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

Conversation

adamkleizer
Copy link
Contributor

@adamkleizer adamkleizer commented Nov 20, 2024

What type of PR is this?

  • bug

What this PR does / why we need it:

Displays dates and times in correctly localized formats via date-fns functions.

Which issue(s) this PR fixes:

Fixes #321

Summary by CodeRabbit

  • New Features

    • Enhanced date formatting options with support for different date types.
    • Improved localization handling for date and time display.
  • Bug Fixes

    • Fixed potential issues with invalid date handling by returning an empty string for invalid inputs.
  • Refactor

    • Streamlined date formatting logic and removed redundant code for better performance.

Copy link
Contributor

coderabbitai bot commented Nov 20, 2024

Walkthrough

The changes in this pull request involve updates to the DateTime.vue component and the use-formatters.ts file. The DateTime.vue component now includes an additional parameter in the value computed property to enhance date formatting based on the type of date. The use-formatters.ts file has been significantly modified to improve date formatting and localization, including the introduction of a new getLocale function and changes to the fmtDate function to handle various date formatting scenarios more effectively.

Changes

File Path Change Summary
frontend/components/global/DateTime.vue Updated value computed property to include props.datetimeType in fmtDate function call.
frontend/composables/use-formatters.ts - Updated import statements to include format and formatDistance from date-fns.
- Removed ordinalIndicator function, added getLocale function.
- Modified useLocaleTimeAgo to use formatDistance.
- Updated fmtDate function to accept an additional type parameter and enhanced date formatting logic.

Assessment against linked issues

Objective Addressed Explanation
Use established solution to show relative time in languages (#321)

Possibly related PRs

  • feat: improve languages support #295: Enhances language support and localization, directly related to the modifications in the fmtDate function in this PR, focusing on improving date formatting and localization handling.

Security Recommendations

  • Ensure that all date inputs are properly validated to prevent potential injection attacks or unexpected behavior in date formatting. Consider implementing additional error handling for edge cases.

📜 Recent review details

Configuration used: CodeRabbit UI
Review profile: CHILL

📥 Commits

Reviewing files that changed from the base of the PR and between 73ef333 and 1de13d2.

📒 Files selected for processing (1)
  • frontend/composables/use-formatters.ts (2 hunks)
🚧 Files skipped from review as they are similar to previous changes (1)
  • frontend/composables/use-formatters.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.

Copy link
Contributor

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

🧹 Outside diff range and nitpick comments (2)
frontend/composables/use-formatters.ts (2)

41-75: Optimize getLocale() calls by caching the result

The getLocale() function is called multiple times within fmtDate, which may introduce unnecessary overhead. Consider retrieving the locale once and reusing it within the function scope.

You can modify the fmtDate function as follows:

 export function fmtDate(
   value: string | Date,
   fmt: DateTimeFormat = "human",
   type: DateTimeType = "date"
 ): string {
+  const locale = getLocale();
   const dt = typeof value === "string" ? new Date(value) : value;

   if (!dt || !validDate(dt)) {
     return "";
   }

   if (fmt === "relative") {
-    return useLocaleTimeAgo(dt);
+    return formatDistance(dt, new Date(), { locale });
   }

   if (type === "time") {
-    return format(dt, "p", { locale: getLocale() });
+    return format(dt, "p", { locale });
   }

   let formatStr = "";

   switch (fmt) {
     case "human":
       formatStr = "PPP";
       break;
     case "long":
       formatStr = "PP";
       break;
     case "short":
       formatStr = "P";
       break;
     default:
       return "";
   }

   if (type === "datetime") {
     formatStr += "p";
   }

-  return format(dt, formatStr, { locale: getLocale() });
+  return format(dt, formatStr, { locale });
 }

38-38: Ensure consistent time zones when formatting relative time

In useLocaleTimeAgo, you're calculating the distance between the input date and the current date using new Date(). Ensure that both dates are in the same time zone to prevent inaccuracies in the relative time display.

🛑 Comments failed to post (4)
frontend/composables/use-formatters.ts (4)

44-44: ⚠️ Potential issue

Undefined function validDate

The function validDate(dt) is called but not defined within this file. Ensure that validDate is properly defined or imported to prevent runtime errors.


41-44: ⚠️ Potential issue

Validate date inputs to prevent potential security risks

When parsing date strings using new Date(value), ensure that the input is validated and sanitized. Malformed or malicious inputs could lead to unexpected behavior or security vulnerabilities.


30-34: ⚠️ Potential issue

Validate locale codes to prevent potential runtime errors

The getLocale function uses locale codes derived from user input, which might be invalid or unsupported. Consider adding validation to ensure that localeCode corresponds to an available locale to prevent runtime errors.

You could add a validation step:

 function getLocale() {
   const t = useI18n();
   const localeCode = t?.locale?.value as string ?? "en-US";
+  const supportedLocales = ['en-US', 'hu'];
+  if (!supportedLocales.includes(localeCode)) {
+    localeCode = 'en-US';
+  }
   const region = localeCode.length > 2 ? localeCode.substring(3) : "";
   return (Locales[(localeCode.substring(0,2) + region) as keyof typeof Locales] ?? Locales[localeCode.substring(0,2) as keyof typeof Locales] ?? Locales.enUS);
 }

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


2-3: 🛠️ Refactor suggestion

Consider importing only necessary locales to reduce bundle size

Importing all locales from date-fns/locale can significantly increase your bundle size, impacting application performance. It's recommended to import only the locales you need.

You can modify the import statements as follows:

-import * as Locales from "date-fns/locale";
+import enUS from "date-fns/locale/en-US";
+import hu from "date-fns/locale/hu";

And update the getLocale function accordingly:

 function getLocale() {
   const t = useI18n();
   const localeCode = t?.locale?.value as string ?? "en-US";
   const region = localeCode.length > 2 ? localeCode.substring(3) : "";
-  return (Locales[(localeCode.substring(0,2) + region) as keyof typeof Locales] ?? Locales[localeCode.substring(0,2) as keyof typeof Locales] ?? Locales.enUS);
+  const localesMap = { 'enUS': enUS, 'hu': hu };
+  const localeKey = (localeCode.substring(0, 2) + region) || 'enUS';
+  return localesMap[localeKey] || enUS;
 }

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

Copy link
Contributor

@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 (2)
frontend/composables/use-formatters.ts (2)

31-38: Consider caching the locale result.

The locale resolution logic is correct, but consider caching the result to avoid repeated calculations on every format operation.

+const localeCache = new Map<string, Locale>();
 function getLocale() {
   const t = useI18n();
   const localeCode = (t?.locale?.value as string) ?? "en-US";
+  if (localeCache.has(localeCode)) {
+    return localeCache.get(localeCode);
+  }
   const lang = localeCode.length > 1 ? localeCode.substring(0, 2) : localeCode;
   const region = localeCode.length > 2 ? localeCode.substring(3) : "";
-  return (
+  const locale = (
     Locales[(lang + region) as keyof typeof Locales] ?? Locales[lang as keyof typeof Locales] ?? Locales.enUS
   );
+  localeCache.set(localeCode, locale);
+  return locale;
 }

45-79: Extract format strings as constants.

The implementation looks good, but consider extracting the format strings as named constants for better maintainability and reusability.

+const FORMAT_PATTERNS = {
+  HUMAN: 'PPP',
+  LONG: 'PP',
+  SHORT: 'P',
+  TIME: 'p'
+} as const;

 export function fmtDate(value: string | Date, fmt: DateTimeFormat = "human", type: DateTimeType = "date"): string {
   // ... existing validation ...
   
   if (type === "time") {
-    return format(dt, "p", { locale: getLocale() });
+    return format(dt, FORMAT_PATTERNS.TIME, { locale: getLocale() });
   }

   let formatStr = "";
   switch (fmt) {
     case "human":
-      formatStr = "PPP";
+      formatStr = FORMAT_PATTERNS.HUMAN;
       break;
     case "long":
-      formatStr = "PP";
+      formatStr = FORMAT_PATTERNS.LONG;
       break;
     case "short":
-      formatStr = "P";
+      formatStr = FORMAT_PATTERNS.SHORT;
       break;
     // ... rest of the function
🛑 Comments failed to post (1)
frontend/composables/use-formatters.ts (1)

42-42: 🛠️ Refactor suggestion

Add date validation check.

The function should validate the input date to prevent potential runtime errors.

 export function useLocaleTimeAgo(date: Date) {
+  if (!date || !validDate(date)) {
+    return "";
+  }
   return formatDistance(date, new Date(), { locale: getLocale() });
 }

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

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.

Use established solution to show relative time in languages
1 participant