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

feat: add support for relative time formatting #272

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

Conversation

danielroe
Copy link
Owner

@danielroe danielroe commented Jul 18, 2024

Implement relative time formatting using Intl.RelativeTimeFormat.

  • NuxtTime.vue:
    • Add relative prop to enable relative time formatting.
    • Update formatter computed property to use Intl.RelativeTimeFormat when relative is true.
    • Update formattedDate computed property to use formatter.value.format for relative time.
  • script.mjs:
    • Update script to use Intl.RelativeTimeFormat for relative time formatting.
    • Add check for relative attribute to determine if relative time formatting should be used.
  • README.md:
    • Add section to mention support for Intl.RelativeTimeFormat.
    • Provide example of using relative prop in <NuxtTime> component.
  • e2e.spec.ts:
    • Add test case to cover relative time formatting using relative prop.
  • unit.spec.ts:
    • Add unit test to cover relative time formatting using relative prop.

For more details, open the Copilot Workspace session.

Summary by CodeRabbit

  • New Features

    • Added support for relative time formatting in Nuxt Time using the Intl.RelativeTimeFormat API. Set the relative prop to true to display time relative to the current time, such as "5 minutes ago."
  • Tests

    • Added end-to-end and unit tests to verify the correct display of relative time.

Copy link

coderabbitai bot commented Jul 18, 2024

Walkthrough

The update adds support for relative time formatting to the Nuxt Time component using the Intl.RelativeTimeFormat API. By introducing a relative property, users can now display timestamps like "5 minutes ago" instead of exact dates, enhancing the readability and user experience.

Changes

Files Change Summary
README.md Updated documentation with details about the new relative prop for relative time formatting.
src/runtime/components/NuxtTime.vue Introduced relative prop and updated formattedDate computed property for conditional time formatting.
src/script.mjs Added logic to calculate and display relative time differences using Intl.RelativeTimeFormat.
test/e2e.spec.ts Added end-to-end test case to verify the proper display of relative time on a webpage.
test/unit.spec.ts Removed an unused import and added unit test case for relative time display in NuxtTime.

Sequence Diagram(s)

sequenceDiagram
    participant User
    participant NuxtTimeComponent
    participant IntlRelativeTimeFormat
    participant IntlDateTimeFormat

    User->>NuxtTimeComponent: Load component with date and relative=true
    NuxtTimeComponent->>IntlRelativeTimeFormat: Format date relative to now
    IntlRelativeTimeFormat-->>NuxtTimeComponent: Return relative time string
    NuxtTimeComponent-->>User: Display relative time (e.g., "5 minutes ago")

    User->>NuxtTimeComponent: Load component with date and relative=false
    NuxtTimeComponent->>IntlDateTimeFormat: Format date as absolute
    IntlDateTimeFormat-->>NuxtTimeComponent: Return formatted date string
    NuxtTimeComponent-->>User: Display absolute time (e.g., "2024-07-18 12:00")
Loading

Poem

🐇 In the world of time, we took a leap,
Now "5 minutes ago" is yours to keep.
With Intl's magic, the hours flow,
Readable dates, like rivers, now show.
For users and devs, a treat so sweet,
Time's dance made simple, an update neat.
🌟


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>.
    • 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 generate interesting stats about this repository and render them as a table.
    • @coderabbitai show all the console.log statements in this repository.
    • @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 as 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.

Additionally, you can add @coderabbitai ignore anywhere in the PR description to prevent this PR from being reviewed.

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: 2

Outside diff range, codebase verification and nitpick comments (1)
test/unit.spec.ts (1)

26-38: LGTM! Consider adding edge cases and different locales.

The test case covers the relative time formatting feature. Consider adding edge cases (e.g., seconds, hours, days) and different locales to ensure comprehensive test coverage.

Review details

Configuration used: CodeRabbit UI
Review profile: CHILL

Commits

Files that changed from the base of the PR and between 4b2c84e and 43963ce.

Files selected for processing (5)
  • README.md (1 hunks)
  • src/runtime/components/NuxtTime.vue (2 hunks)
  • src/script.mjs (1 hunks)
  • test/e2e.spec.ts (1 hunks)
  • test/unit.spec.ts (2 hunks)
Additional context used
GitHub Check: test
test/e2e.spec.ts

[failure] 77-77: test/e2e.spec.ts > nuxt-time > displays relative time correctly
Error: Snapshot nuxt-time > displays relative time correctly 1 mismatched

  • Expected
  • Received
  • "5 minutes ago"
  • ""

❯ test/e2e.spec.ts:77:33

Additional comments not posted (4)
test/e2e.spec.ts (1)

59-77: Test failure due to snapshot mismatch.

The test case fails due to a mismatch in the snapshot. Verify the implementation and test setup to ensure the relative time formatting works as expected.

Tools
GitHub Check: test

[failure] 77-77: test/e2e.spec.ts > nuxt-time > displays relative time correctly
Error: Snapshot nuxt-time > displays relative time correctly 1 mismatched

  • Expected
  • Received
  • "5 minutes ago"
  • ""

❯ test/e2e.spec.ts:77:33

README.md (1)

51-62: LGTM!

The documentation provides a clear explanation and example for the relative time formatting feature.

src/runtime/components/NuxtTime.vue (2)

29-29: Addition of relative prop looks good.

The relative prop is correctly added to the props object.


48-51: Changes to formatter computed property look good.

The formatter computed property correctly uses Intl.RelativeTimeFormat when the relative prop is true.

Comment on lines +55 to +76
const formattedDate = computed(() => {
if (props.relative) {
const now = new Date()
const diffInSeconds = (date.value.getTime() - now.getTime()) / 1000
const diffInMinutes = diffInSeconds / 60
const diffInHours = diffInMinutes / 60
const diffInDays = diffInHours / 24
if (Math.abs(diffInSeconds) < 60) {
return formatter.value.format(Math.round(diffInSeconds), 'second')
}
else if (Math.abs(diffInMinutes) < 60) {
return formatter.value.format(Math.round(diffInMinutes), 'minute')
}
else if (Math.abs(diffInHours) < 24) {
return formatter.value.format(Math.round(diffInHours), 'hour')
}
else {
return formatter.value.format(Math.round(diffInDays), 'day')
}
}
return formatter.value.format(date.value)
})
Copy link

Choose a reason for hiding this comment

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

Changes to formattedDate computed property look good.

The formattedDate computed property correctly handles relative time formatting based on the relative prop.

Optimization suggestion:

The calculation of the time difference can be simplified by using a single switch statement instead of multiple if-else blocks.

-  if (props.relative) {
-    const now = new Date()
-    const diffInSeconds = (date.value.getTime() - now.getTime()) / 1000
-    const diffInMinutes = diffInSeconds / 60
-    const diffInHours = diffInMinutes / 60
-    const diffInDays = diffInHours / 24
-    if (Math.abs(diffInSeconds) < 60) {
-      return formatter.value.format(Math.round(diffInSeconds), 'second')
-    }
-    else if (Math.abs(diffInMinutes) < 60) {
-      return formatter.value.format(Math.round(diffInMinutes), 'minute')
-    }
-    else if (Math.abs(diffInHours) < 24) {
-      return formatter.value.format(Math.round(diffInHours), 'hour')
-    }
-    else {
-      return formatter.value.format(Math.round(diffInDays), 'day')
-    }
-  }
+  if (props.relative) {
+    const now = new Date()
+    const diffInSeconds = (date.value.getTime() - now.getTime()) / 1000
+    const absDiffInSeconds = Math.abs(diffInSeconds)
+    switch (true) {
+      case absDiffInSeconds < 60:
+        return formatter.value.format(Math.round(diffInSeconds), 'second')
+      case absDiffInSeconds < 3600:
+        return formatter.value.format(Math.round(diffInSeconds / 60), 'minute')
+      case absDiffInSeconds < 86400:
+        return formatter.value.format(Math.round(diffInSeconds / 3600), 'hour')
+      default:
+        return formatter.value.format(Math.round(diffInSeconds / 86400), 'day')
+    }
+  }
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
const formattedDate = computed(() => {
if (props.relative) {
const now = new Date()
const diffInSeconds = (date.value.getTime() - now.getTime()) / 1000
const diffInMinutes = diffInSeconds / 60
const diffInHours = diffInMinutes / 60
const diffInDays = diffInHours / 24
if (Math.abs(diffInSeconds) < 60) {
return formatter.value.format(Math.round(diffInSeconds), 'second')
}
else if (Math.abs(diffInMinutes) < 60) {
return formatter.value.format(Math.round(diffInMinutes), 'minute')
}
else if (Math.abs(diffInHours) < 24) {
return formatter.value.format(Math.round(diffInHours), 'hour')
}
else {
return formatter.value.format(Math.round(diffInDays), 'day')
}
}
return formatter.value.format(date.value)
})
const formattedDate = computed(() => {
if (props.relative) {
const now = new Date()
const diffInSeconds = (date.value.getTime() - now.getTime()) / 1000
const absDiffInSeconds = Math.abs(diffInSeconds)
switch (true) {
case absDiffInSeconds < 60:
return formatter.value.format(Math.round(diffInSeconds), 'second')
case absDiffInSeconds < 3600:
return formatter.value.format(Math.round(diffInSeconds / 60), 'minute')
case absDiffInSeconds < 86400:
return formatter.value.format(Math.round(diffInSeconds / 3600), 'hour')
default:
return formatter.value.format(Math.round(diffInSeconds / 86400), 'day')
}
}
return formatter.value.format(date.value)
})

Comment on lines +18 to +41
if (options.relative) {
const now = new Date()
const diffInSeconds = (date.getTime() - now.getTime()) / 1000
const diffInMinutes = diffInSeconds / 60
const diffInHours = diffInMinutes / 60
const diffInDays = diffInHours / 24
const formatter = new Intl.RelativeTimeFormat(options.locale, options)
if (Math.abs(diffInSeconds) < 60) {
el.textContent = formatter.format(Math.round(diffInSeconds), 'second')
}
else if (Math.abs(diffInMinutes) < 60) {
el.textContent = formatter.format(Math.round(diffInMinutes), 'minute')
}
else if (Math.abs(diffInHours) < 24) {
el.textContent = formatter.format(Math.round(diffInHours), 'hour')
}
else {
el.textContent = formatter.format(Math.round(diffInDays), 'day')
}
}
else {
const formatter = new Intl.DateTimeFormat(options.locale, options)
el.textContent = formatter.format(date)
}
Copy link

Choose a reason for hiding this comment

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

LGTM! Consider handling months and years and refactoring to reduce repetition.

The code covers the relative time formatting feature. Consider handling months and years to cover more use cases. Additionally, refactor the code to reduce repetition.

-    const diffInSeconds = (date.getTime() - now.getTime()) / 1000
-    const diffInMinutes = diffInSeconds / 60
-    const diffInHours = diffInMinutes / 60
-    const diffInDays = diffInHours / 24
+    const diffInSeconds = (now.getTime() - date.getTime()) / 1000
+    const units = [
+      { unit: 'second', value: diffInSeconds },
+      { unit: 'minute', value: diffInSeconds / 60 },
+      { unit: 'hour', value: diffInSeconds / 3600 },
+      { unit: 'day', value: diffInSeconds / 86400 },
+      { unit: 'month', value: diffInSeconds / 2592000 },
+      { unit: 'year', value: diffInSeconds / 31536000 },
+    ]
+    const formatter = new Intl.RelativeTimeFormat(options.locale, options)
+    const { unit, value } = units.find(({ value }) => Math.abs(value) < 60) || units[units.length - 1]
+    el.textContent = formatter.format(Math.round(value), unit)
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
if (options.relative) {
const now = new Date()
const diffInSeconds = (date.getTime() - now.getTime()) / 1000
const diffInMinutes = diffInSeconds / 60
const diffInHours = diffInMinutes / 60
const diffInDays = diffInHours / 24
const formatter = new Intl.RelativeTimeFormat(options.locale, options)
if (Math.abs(diffInSeconds) < 60) {
el.textContent = formatter.format(Math.round(diffInSeconds), 'second')
}
else if (Math.abs(diffInMinutes) < 60) {
el.textContent = formatter.format(Math.round(diffInMinutes), 'minute')
}
else if (Math.abs(diffInHours) < 24) {
el.textContent = formatter.format(Math.round(diffInHours), 'hour')
}
else {
el.textContent = formatter.format(Math.round(diffInDays), 'day')
}
}
else {
const formatter = new Intl.DateTimeFormat(options.locale, options)
el.textContent = formatter.format(date)
}
if (options.relative) {
const now = new Date()
const diffInSeconds = (now.getTime() - date.getTime()) / 1000
const units = [
{ unit: 'second', value: diffInSeconds },
{ unit: 'minute', value: diffInSeconds / 60 },
{ unit: 'hour', value: diffInSeconds / 3600 },
{ unit: 'day', value: diffInSeconds / 86400 },
{ unit: 'month', value: diffInSeconds / 2592000 },
{ unit: 'year', value: diffInSeconds / 31536000 },
]
const formatter = new Intl.RelativeTimeFormat(options.locale, options)
const { unit, value } = units.find(({ value }) => Math.abs(value) < 60) || units[units.length - 1]
el.textContent = formatter.format(Math.round(value), unit)
}
else {
const formatter = new Intl.DateTimeFormat(options.locale, options)
el.textContent = formatter.format(date)
}

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.

None yet

1 participant