Skip to content

fix(nuxt): use correct unit thresholds for relative time #32893

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

Merged
merged 6 commits into from
Aug 11, 2025

Conversation

mukundshah
Copy link
Contributor

🔗 Linked issue

No existing issue

📚 Description

This PR refines the relative time formatting logic by introducing explicit, accurate thresholds for all time units to decide when to switch to the next larger unit.

Issue:
The previous implementation used a uniform threshold of 60 for all units (seconds, minutes, hours, days, etc.). This approach caused unnatural outputs such as:

  • "25 hours ago" instead of "1 day ago"
  • "45 days ago" instead of "1 month ago"
  • "15 months ago" instead of "1 year ago"

Because it treated hours, days, and months as if they rolled over at 60, which is only true for seconds-to-minutes and minutes-to-hours.

What changed:

Added unit-specific thresholds to define when to switch units:

  • 60 seconds → minute
  • 60 minutes → hour
  • 24 hours → day
  • ~30 days → month
  • 12 months → year
  • Year has no upper threshold (infinity)

Example outputs before fix:

Time difference Output
25 hours "25 hours ago"
45 days "45 days ago"
15 months "15 months ago"

Example outputs after fix:

Time difference Output
25 hours "1 day ago"
45 days "1 month ago"
15 months "1 year ago"

@mukundshah mukundshah requested a review from danielroe as a code owner August 8, 2025 06:03
Copy link

Review PR in StackBlitz Codeflow Run & review this pull request in StackBlitz Codeflow.

Copy link

pkg-pr-new bot commented Aug 8, 2025

Open in StackBlitz

@nuxt/kit

npm i https://pkg.pr.new/@nuxt/kit@32893

nuxt

npm i https://pkg.pr.new/nuxt@32893

@nuxt/rspack-builder

npm i https://pkg.pr.new/@nuxt/rspack-builder@32893

@nuxt/schema

npm i https://pkg.pr.new/@nuxt/schema@32893

@nuxt/vite-builder

npm i https://pkg.pr.new/@nuxt/vite-builder@32893

@nuxt/webpack-builder

npm i https://pkg.pr.new/@nuxt/webpack-builder@32893

commit: 8c7f381

Copy link

codspeed-hq bot commented Aug 8, 2025

CodSpeed Performance Report

Merging #32893 will not alter performance

Comparing mukundshah:patch-1 (8c7f381) with main (dd138fa)

Summary

✅ 10 untouched benchmarks

@danielroe danielroe changed the title fix(nuxt-time): use correct unit thresholds for relative time fix(nuxt): use correct unit thresholds for relative time Aug 8, 2025
mukundshah and others added 4 commits August 8, 2025 17:07
Updated relative date formatting logic to switch units at correct boundaries:
- Hours now switch to days at 24 hours (instead of 60)
- Explicit thresholds defined for each unit
- Kept Infinity as the upper bound for years

Prevents cases like "25 hours ago" showing instead of "1 day ago".
@danielroe danielroe changed the base branch from 3.x to main August 10, 2025 20:05
Copy link

coderabbitai bot commented Aug 10, 2025

Walkthrough

The changes introduce a custom Vite plugin within the Nuxt configuration to modify tree-shaking and SSR composable handling. The plugin transforms source code at build time, ensuring the onPrehydrate composable is preserved on the client side and replacing SSR checks with runtime SSR attribute checks in the nuxt-time.vue component. The relative time formatting logic in nuxt-time.vue is refactored to use a more detailed unit definition with thresholds for more accurate unit transitions. A new parameterized test is added to verify the hydrateable output of the <NuxtTime> component, including its SSR prehydration behaviour and correct execution of injected scripts in the document head.

Estimated code review effort

🎯 3 (Moderate) | ⏱️ ~20 minutes

Note

🔌 MCP (Model Context Protocol) integration is now available in Early Access!

Pro users can now connect to remote MCP servers under the Integrations page to get reviews and chat conversations that understand additional development context.


📜 Recent review details

Configuration used: CodeRabbit UI
Review profile: CHILL
Plan: Pro

📥 Commits

Reviewing files that changed from the base of the PR and between 5407974 and 8c7f381.

📒 Files selected for processing (1)
  • test/nuxt/nuxt-time.test.ts (2 hunks)
🚧 Files skipped from review as they are similar to previous changes (1)
  • test/nuxt/nuxt-time.test.ts
✨ Finishing Touches
  • 📝 Generate Docstrings
🧪 Generate unit tests
  • Create PR with unit tests
  • Post copyable unit tests in a comment

Thanks for using CodeRabbit! It's free for OSS, and your support helps us grow. If you like it, consider giving us a shout-out.

❤️ 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.
    • Explain this complex logic.
    • 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 explain this code block.
  • 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 explain its main purpose.
    • @coderabbitai read the files in the src/scheduler package and generate a class diagram using mermaid and a README in the markdown format.

Support

Need help? Create a ticket on our support page for assistance with any issues or questions.

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.
  • @coderabbitai generate sequence diagram to generate a sequence diagram of the changes in this PR.
  • @coderabbitai generate unit tests to generate unit tests for this 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.

Actionable comments posted: 3

🧹 Nitpick comments (1)
packages/nuxt/src/app/components/nuxt-time.vue (1)

73-92: Unit-threshold selection logic looks correct; consider rounding nuance

The thresholds map aligns with the intended behaviour (60s, 60m, 24h, ~30d, 12m, ∞y). One small nit: rounding can occasionally show “60 seconds” at ~59.5s. If you want to avoid that, round toward zero (or floor/ceil by sign) before formatting.

-  const value = diffInSeconds / seconds
-  return (formatter.value as Intl.RelativeTimeFormat).format(Math.round(value), unit)
+  const value = diffInSeconds / seconds
+  const rounded = value < 0 ? Math.ceil(value) : Math.floor(value)
+  return (formatter.value as Intl.RelativeTimeFormat).format(rounded, unit)

Optional: If you prefer rounding to nearest, keep as-is.

📜 Review details

Configuration used: CodeRabbit UI
Review profile: CHILL
Plan: Pro

📥 Commits

Reviewing files that changed from the base of the PR and between 6ca8008 and 5407974.

📒 Files selected for processing (3)
  • nuxt.config.ts (2 hunks)
  • packages/nuxt/src/app/components/nuxt-time.vue (2 hunks)
  • test/nuxt/nuxt-time.test.ts (2 hunks)
🧰 Additional context used
📓 Path-based instructions (3)
**/*.{ts,tsx}

📄 CodeRabbit Inference Engine (.github/copilot-instructions.md)

Follow standard TypeScript conventions and best practices

Files:

  • test/nuxt/nuxt-time.test.ts
  • nuxt.config.ts
**/*.{test,spec}.{ts,tsx,js,jsx}

📄 CodeRabbit Inference Engine (.github/copilot-instructions.md)

Write unit tests for core functionality using vitest

Files:

  • test/nuxt/nuxt-time.test.ts
**/*.vue

📄 CodeRabbit Inference Engine (.github/copilot-instructions.md)

Use <script setup lang="ts"> and the composition API when creating Vue components

Files:

  • packages/nuxt/src/app/components/nuxt-time.vue
🧠 Learnings (5)
📓 Common learnings
Learnt from: GalacticHypernova
PR: nuxt/nuxt#26468
File: packages/nuxt/src/components/plugins/loader.ts:24-24
Timestamp: 2024-11-05T15:22:54.759Z
Learning: In `packages/nuxt/src/components/plugins/loader.ts`, the references to `resolve` and `distDir` are legacy code from before Nuxt used the new unplugin VFS and will be removed.
📚 Learning: 2025-07-18T16:46:07.446Z
Learnt from: CR
PR: nuxt/nuxt#0
File: .github/copilot-instructions.md:0-0
Timestamp: 2025-07-18T16:46:07.446Z
Learning: Applies to **/*.{test,spec}.{ts,tsx,js,jsx} : Write unit tests for core functionality using `vitest`

Applied to files:

  • test/nuxt/nuxt-time.test.ts
📚 Learning: 2025-07-18T16:46:07.446Z
Learnt from: CR
PR: nuxt/nuxt#0
File: .github/copilot-instructions.md:0-0
Timestamp: 2025-07-18T16:46:07.446Z
Learning: Applies to **/e2e/**/*.{ts,js} : Write end-to-end tests using Playwright and `nuxt/test-utils`

Applied to files:

  • test/nuxt/nuxt-time.test.ts
📚 Learning: 2024-11-05T15:22:54.759Z
Learnt from: GalacticHypernova
PR: nuxt/nuxt#26468
File: packages/nuxt/src/components/plugins/loader.ts:24-24
Timestamp: 2024-11-05T15:22:54.759Z
Learning: In `packages/nuxt/src/components/plugins/loader.ts`, the references to `resolve` and `distDir` are legacy code from before Nuxt used the new unplugin VFS and will be removed.

Applied to files:

  • nuxt.config.ts
📚 Learning: 2024-12-12T12:36:34.871Z
Learnt from: huang-julien
PR: nuxt/nuxt#29366
File: packages/nuxt/src/app/components/nuxt-root.vue:16-19
Timestamp: 2024-12-12T12:36:34.871Z
Learning: In `packages/nuxt/src/app/components/nuxt-root.vue`, when optimizing bundle size by conditionally importing components based on route metadata, prefer using inline conditional imports like:

```js
const IsolatedPage = route?.meta?.isolate ? defineAsyncComponent(() => import('#build/isolated-page.mjs')) : null
```

instead of wrapping the import in a computed property or importing the component unconditionally.

Applied to files:

  • nuxt.config.ts
⏰ Context from checks skipped due to timeout of 90000ms. You can increase the timeout in your CodeRabbit configuration to a maximum of 15 minutes (900000ms). (3)
  • GitHub Check: codeql (javascript-typescript)
  • GitHub Check: build
  • GitHub Check: code
🔇 Additional comments (3)
nuxt.config.ts (1)

24-41: Enhance transform robustness and restrict to test environment

To avoid brittle string matches and unintended production changes:

  • Wrap the Vite plugin registration so it only runs in test mode (e.g. process.env.VITEST or NODE_ENV === 'test').
  • Use regular expressions that tolerate varying whitespace when stripping the onPrehydrate guard and replacing the server‐only guard.
  • Verify whether useAttrs is auto-imported in your setup. If not, inject import { useAttrs } from 'vue' into the <script setup> block of the SFC.

Suggested diff:

-      addVitePlugin(() => ({
+      // only for tests
+      if (!(process.env.VITEST || process.env.NODE_ENV === 'test')) {
+        return
+      }
+      addVitePlugin(() => ({
         name: 'preserve-ssr-composables',
         enforce: 'pre',
         transform(code, id) {
           let replaced = false
           if (code.includes('export function onPrehydrate')) {
             replaced = true
-            code = code.replaceAll('if (import.meta.client) { return }', '')
+            // tolerate varying whitespace
+            code = code.replace(/\bif\s*\(\s*import\.meta\.client\s*\)\s*\{\s*return\s*\}/g, '')
           }
           if (id.includes('nuxt-time.vue')) {
             replaced = true
-            code = code.replace('if (import.meta.server) {', 'if (useAttrs().ssr) {')
+            // replace the first server-only guard, tolerant to spacing
+            code = code.replace(/\bif\s*\(\s*import\.meta\.server\s*\)\s*\{/,
+                                 'if (useAttrs().ssr) {')
           }
           if (replaced) {
             return code
           }
         },
       }))

Please confirm that useAttrs is available via auto-imports in this Nuxt config; otherwise, inject the Vue import into the SFC.

test/nuxt/nuxt-time.test.ts (1)

4-4: LGTM: head access added for prehydration assertions

Importing injectHead is appropriate for validating the injected script and hydration flow.

packages/nuxt/src/app/components/nuxt-time.vue (1)

69-71: Early return for non-relative path is clear and efficient

Good simplification; avoids unnecessary branching later.

Comment on lines +21 to +23
nuxt.options.optimization.treeShake.composables.client ||= {}
nuxt.options.optimization.treeShake.composables.client['#app'] = nuxt.options.optimization.treeShake.composables.client['#app']?.filter(c => c !== 'onPrehydrate') || []

Copy link

Choose a reason for hiding this comment

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

💡 Verification agent

❓ Verification inconclusive

Guard tree-shake override to test-only and ensure safety on missing paths

This mutation currently runs unconditionally. Restrict to test runs to avoid impacting dev/prod builds, and guard the nested path in case optimization is undefined in some environments.

-      // this preserves onPrehydrate so we can make assertions on the client
-      nuxt.options.optimization.treeShake.composables.client ||= {}
-      nuxt.options.optimization.treeShake.composables.client['#app'] = nuxt.options.optimization.treeShake.composables.client['#app']?.filter(c => c !== 'onPrehydrate') || []
+      // this preserves onPrehydrate so we can make assertions on the client (test-only)
+      if (process.env.VITEST || process.env.NODE_ENV === 'test') {
+        nuxt.options.optimization ??= {} as any
+        nuxt.options.optimization.treeShake ??= {} as any
+        nuxt.options.optimization.treeShake.composables ??= {} as any
+        nuxt.options.optimization.treeShake.composables.client ??= {}
+        nuxt.options.optimization.treeShake.composables.client['#app'] =
+          nuxt.options.optimization.treeShake.composables.client['#app']?.filter(c => c !== 'onPrehydrate') || []
+      }

Action: Please confirm this module only runs in tests (or wrap the entire module body with the same guard).


Guard test-only tree-shake override & safe-guard nested options

To avoid impacting dev/prod builds and prevent runtime errors if nested properties are missing, please:

  • Wrap the override so it only runs in a test environment (process.env.VITEST || process.env.NODE_ENV === 'test').
  • Nullish-assign at each level (optimization, treeShake, composables, composables.client) before filtering out onPrehydrate.

Proposed diff in nuxt.config.ts:

-      // this preserves onPrehydrate so we can make assertions on the client
-      nuxt.options.optimization.treeShake.composables.client ||= {}
-      nuxt.options.optimization.treeShake.composables.client['#app'] =
-        nuxt.options.optimization.treeShake.composables.client['#app']?.filter(c => c !== 'onPrehydrate') || []
+      // test-only: preserve onPrehydrate for client assertions
+      if (process.env.VITEST || process.env.NODE_ENV === 'test') {
+        nuxt.options.optimization     ??= {} as any
+        nuxt.options.optimization.treeShake ??= {} as any
+        nuxt.options.optimization.treeShake.composables ??= {} as any
+        nuxt.options.optimization.treeShake.composables.client ??= {}
+        nuxt.options.optimization.treeShake.composables.client['#app'] =
+          nuxt.options.optimization.treeShake.composables.client['#app']
+            ?.filter(c => c !== 'onPrehydrate') || []
+      }

Action: Confirm this code block only needs to run in tests, or apply the same guard around the entire module registration.

📝 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
nuxt.options.optimization.treeShake.composables.client ||= {}
nuxt.options.optimization.treeShake.composables.client['#app'] = nuxt.options.optimization.treeShake.composables.client['#app']?.filter(c => c !== 'onPrehydrate') || []
// test-only: preserve onPrehydrate for client assertions
if (process.env.VITEST || process.env.NODE_ENV === 'test') {
nuxt.options.optimization ??= {} as any
nuxt.options.optimization.treeShake ??= {} as any
nuxt.options.optimization.treeShake.composables??= {} as any
nuxt.options.optimization.treeShake.composables.client ??= {}
nuxt.options.optimization.treeShake.composables.client['#app'] =
nuxt.options.optimization.treeShake.composables.client['#app']
?.filter(c => c !== 'onPrehydrate') || []
}
🤖 Prompt for AI Agents
In nuxt.config.ts around lines 21 to 23, the code modifies nested properties
without checking if they exist and runs unconditionally, which can cause runtime
errors and affect non-test environments. To fix this, wrap the entire block in a
condition that checks if the environment is a test environment
(process.env.VITEST or process.env.NODE_ENV === 'test'), and use nullish
assignment (??=) at each nested level (optimization, treeShake, composables,
composables.client) before accessing or modifying properties to ensure they
exist safely.

@danielroe danielroe merged commit 61d1580 into nuxt:main Aug 11, 2025
46 checks passed
@github-actions github-actions bot mentioned this pull request Aug 10, 2025
@github-actions github-actions bot mentioned this pull request Aug 11, 2025
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Projects
None yet
Development

Successfully merging this pull request may close these issues.

2 participants