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

Merged
merged 7 commits into from
Sep 17, 2024
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
13 changes: 13 additions & 0 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -48,6 +48,19 @@ It accepts `datetime` and `locale` (optional) properties, along with any propert
</template>
```

## Relative Time Formatting

Nuxt Time also supports relative time formatting using the `Intl.RelativeTimeFormat` API. You can enable this feature by setting the `relative` prop to `true`.

```vue
<template>
<!--
This will display the time relative to the current time, e.g., "5 minutes ago"
-->
<NuxtTime :datetime="Date.now() - 5 * 60 * 1000" relative />
</template>
```

## 💻 Development

- Clone this repository
Expand Down
1 change: 1 addition & 0 deletions playground/nuxt.config.ts
Original file line number Diff line number Diff line change
@@ -1,3 +1,4 @@
export default defineNuxtConfig({
compatibilityDate: '2024-09-17',
danielroe marked this conversation as resolved.
Show resolved Hide resolved
modules: ['nuxt-time'],
})
6 changes: 6 additions & 0 deletions playground/pages/index.vue
Original file line number Diff line number Diff line change
Expand Up @@ -42,6 +42,12 @@ const changeDate = () => {
time-zone="America/New_York"
/>
<br>
<NuxtTime
data-testid="relative"
:datetime="Date.now() - (1 * 30 * 1000)"
relative
/>
<br>
<button @click="switchLocale">
Switch locale
</button>
Expand Down
71 changes: 64 additions & 7 deletions src/runtime/components/NuxtTime.vue
Original file line number Diff line number Diff line change
Expand Up @@ -25,6 +25,7 @@ const props = withDefaults(defineProps<{
dateStyle?: 'full' | 'long' | 'medium' | 'short'
timeStyle?: 'full' | 'long' | 'medium' | 'short'
hourCycle?: 'h11' | 'h12' | 'h23' | 'h24'
relative?: boolean
}>(), {
hour12: undefined,
})
Expand All @@ -42,23 +43,57 @@ const date = computed(() => {
return new Date(date)
})

const now = ref(import.meta.client && nuxtApp.isHydrating && window._nuxtTimeNow ? new Date(window._nuxtTimeNow) : new Date())
if (import.meta.client && props.relative) {
const handler = () => {
now.value = new Date()
}
const interval = setInterval(handler, 1000)
onBeforeUnmount(() => clearInterval(interval))
}

const formatter = computed(() => {
const { locale: propsLocale, ...rest } = props
const { locale: propsLocale, relative, ...rest } = props
if (relative) {
return new Intl.RelativeTimeFormat(_locale ?? propsLocale, rest)
}
return new Intl.DateTimeFormat(_locale ?? propsLocale, rest)
})
const formattedDate = computed(() => formatter.value.format(date.value))

const formattedDate = computed(() => {
if (props.relative) {
const diffInSeconds = (date.value.getTime() - now.value.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 },
] as const
const { unit, value } = units.find(({ value }) => Math.abs(value) < 60) || units[units.length - 1]
return formatter.value.format(Math.round(value), unit)
}

return (formatter.value as Intl.DateTimeFormat).format(date.value)
})

const isoDate = computed(() => date.value.toISOString())

const dataset: Record<string, string | number | boolean | Date | undefined> = {}

if (import.meta.server) {
for (const prop in props) {
if (prop !== 'datetime') {
const propInKebabCase = prop.split(/(?=[A-Z])/).join('-')
dataset[`data-${propInKebabCase}`] = props?.[prop as keyof typeof props]
const value = props?.[prop as keyof typeof props]
if (value) {
const propInKebabCase = prop.split(/(?=[A-Z])/).join('-')
dataset[`data-${propInKebabCase}`] = props?.[prop as keyof typeof props]
}
}
}
onPrehydrate((el) => {
const now = window._nuxtTimeNow = window._nuxtTimeNow || Date.now()
const toCamelCase = (name: string, index: number) => {
if (index > 0) {
return name[0].toUpperCase() + name.slice(1)
Expand All @@ -67,7 +102,7 @@ if (import.meta.server) {
}

const date = new Date(el.getAttribute('datetime')!)
const options: Intl.DateTimeFormatOptions & { locale?: Intl.LocalesArgument } = {}
const options: Intl.DateTimeFormatOptions & { locale?: Intl.LocalesArgument, relative?: boolean } = {}
for (const name of el.getAttributeNames()) {
if (name.startsWith('data-')) {
const optionName = name.slice(5).split('-').map(toCamelCase).join('') as keyof Intl.DateTimeFormatOptions
Expand All @@ -76,10 +111,32 @@ if (import.meta.server) {
}
}

const formatter = new Intl.DateTimeFormat(options.locale, options)
el.textContent = formatter.format(date)
if (options.relative) {
const diffInSeconds = (date.getTime() - now) / 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 },
] as const
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)
}
})
}

declare global {
interface Window {
_nuxtTimeNow?: number
}
}
</script>

<template>
Expand Down
22 changes: 22 additions & 0 deletions test/e2e.spec.ts
Original file line number Diff line number Diff line change
Expand Up @@ -55,4 +55,26 @@ describe('nuxt-time', async () => {
// No hydration errors
expect(logs.join('')).toMatchInlineSnapshot('""')
})

it('displays relative time correctly', async () => {
const page = await createPage(undefined, { locale: 'en-GB' })
const logs: string[] = []

page.on('console', (event) => {
if (!event.text().includes('<Suspense>')) {
logs.push(event.text())
}
})

await page.goto(url('/'), { waitUntil: 'networkidle' })

expect(await page.getByTestId('relative').textContent()).toMatchInlineSnapshot(
'"30 seconds ago"',
)

await page.getByTestId('relative').getByText('32 seconds ago').textContent()

// No hydration errors
expect(logs.join('')).toMatchInlineSnapshot('""')
})
})
16 changes: 16 additions & 0 deletions test/unit.spec.ts
Original file line number Diff line number Diff line change
Expand Up @@ -23,4 +23,20 @@ describe('<NuxtTime>', () => {
`"<time datetime="2023-02-11T18:26:41.058Z">11 February at 41</time>"`,
)
})

it('should display relative time correctly', async () => {
const datetime = Date.now() - 5 * 60 * 1000
const thing = await mountSuspended(
defineComponent({
render: () =>
h(NuxtTime, {
datetime,
relative: true,
}),
}),
)
expect(thing.html()).toMatchInlineSnapshot(
`"<time datetime="${new Date(datetime).toISOString()}">5 minutes ago</time>"`,
)
})
})
Loading