The minimalistic document archiving platform.
feat(i18n): add date and time ago formatting functions (#583)
Corentin Thomassetb0abf7f78a85
diff --git a/.changeset/purple-comics-roll.md b/.changeset/purple-comics-roll.mdnew file mode 100644index 00000000..07ebee79--- /dev/null+++ b/.changeset/purple-comics-roll.md@@ -0,0 +1,5 @@+---+"@papra/docker": patch+---++Improved the translation of dates and relative timediff --git a/apps/papra-client/src/modules/api-keys/pages/api-keys.page.tsx b/apps/papra-client/src/modules/api-keys/pages/api-keys.page.tsxindex 6c2f74c3..0cc60993 100644--- a/apps/papra-client/src/modules/api-keys/pages/api-keys.page.tsx+++ b/apps/papra-client/src/modules/api-keys/pages/api-keys.page.tsx@@ -2,7 +2,6 @@ import type { Component } from 'solid-js';import type { ApiKey } from '../api-keys.types';import { A } from '@solidjs/router';import { useMutation, useQuery } from '@tanstack/solid-query';-import { format } from 'date-fns';import { For, Match, Show, Suspense, Switch } from 'solid-js';import { useI18n } from '@/modules/i18n/i18n.provider';import { useConfirmModal } from '@/modules/shared/confirm';@@ -13,7 +12,7 @@ import { createToast } from '@/modules/ui/components/sonner';import { deleteApiKey, fetchApiKeys } from '../api-keys.services';export const ApiKeyCard: Component<{ apiKey: ApiKey }> = ({ apiKey }) => {- const { t } = useI18n();+ const { t, formatRelativeTime, formatDate } = useI18n();const { confirm } = useConfirmModal();const deleteApiKeyMutation = useMutation(() => ({@@ -57,15 +56,15 @@ export const ApiKeyCard: Component<{ apiKey: ApiKey }> = ({ apiKey }) => {</div><div>- <p class="text-muted-foreground text-xs">+ {/* <p class="text-muted-foreground text-xs">{t('api-keys.list.card.last-used')}{' '}- {apiKey.lastUsedAt ? format(apiKey.lastUsedAt, 'MMM d, yyyy') : t('api-keys.list.card.never')}- </p>- <p class="text-muted-foreground text-xs">+ {apiKey.lastUsedAt ? formatDate(apiKey.lastUsedAt) : t('api-keys.list.card.never')}+ </p> */}+ <p class="text-muted-foreground text-xs" title={formatDate(apiKey.createdAt, { dateStyle: 'short', timeStyle: 'long' })}>{t('api-keys.list.card.created')}{' '}- {format(apiKey.createdAt, 'MMM d, yyyy')}+ {formatRelativeTime(apiKey.createdAt)}</p></div>diff --git a/apps/papra-client/src/modules/i18n/i18n.models.test.ts b/apps/papra-client/src/modules/i18n/i18n.models.test.tsindex e05b2b4b..0703a567 100644--- a/apps/papra-client/src/modules/i18n/i18n.models.test.ts+++ b/apps/papra-client/src/modules/i18n/i18n.models.test.ts@@ -1,5 +1,5 @@import { describe, expect, test } from 'vitest';-import { createTranslator, findMatchingLocale } from './i18n.models';+import { createDateFormatter, createRelativeTimeFormatter, createTranslator, findMatchingLocale } from './i18n.models';describe('i18n models', () => {describe('findMatchingLocale', () => {@@ -125,4 +125,99 @@ describe('i18n models', () => {expect(t('hello', { name: 'John' })).to.eql('John, John, John and John!');});});++ describe('createDateFormatter', () => {+ test('formats date according to locale, by default in short format', () => {+ expect(+ createDateFormatter({ getLocale: () => 'en' })(new Date('2025-01-15')),+ ).to.eql('Jan 15, 2025');++ expect(+ createDateFormatter({ getLocale: () => 'fr' })(new Date('2025-01-15')),+ ).to.eql('15 janv. 2025');++ expect(+ createDateFormatter({ getLocale: () => 'pt-BR' })(new Date('2025-01-15')),+ ).to.eql('15 de jan. de 2025');+ });+ });++ describe('createRelativeTimeFormatter', () => {+ test('formats relative time according to locale', () => {+ expect(+ createRelativeTimeFormatter({ getLocale: () => 'en' })(new Date('2021-01-01T00:00:00Z'), { now: new Date('2021-01-01T00:00:00Z') }),+ ).to.eql('now');++ expect(+ createRelativeTimeFormatter({ getLocale: () => 'en' })(new Date('2021-01-01T00:00:00Z'), { now: new Date('2021-01-01T00:00:06Z') }),+ ).to.eql('6 seconds ago');++ expect(+ createRelativeTimeFormatter({ getLocale: () => 'fr' })(new Date('2021-01-01T00:00:00Z'), { now: new Date('2021-01-01T00:02:00Z') }),+ ).to.eql('il y a 2 minutes');++ expect(+ createRelativeTimeFormatter({ getLocale: () => 'pt-BR' })(new Date('2021-01-01T00:00:00Z'), { now: new Date('2021-01-03T00:00:00Z') }),+ ).to.eql('anteontem');+ });++ test('use the best unit for relative time', () => {+ const formatter = createRelativeTimeFormatter({ getLocale: () => 'en' });+ const timeAgo = (now: Date) => formatter(new Date('2021-01-01T00:00:00Z'), { now });++ expect(timeAgo(new Date('2021-01-01T00:00:00Z'))).toBe('now');+ expect(timeAgo(new Date('2021-01-01T00:00:06Z'))).toBe('6 seconds ago');+ expect(timeAgo(new Date('2021-01-01T00:01:00Z'))).toBe('1 minute ago');+ expect(timeAgo(new Date('2021-01-01T00:02:00Z'))).toBe('2 minutes ago');+ expect(timeAgo(new Date('2021-01-01T01:00:00Z'))).toBe('1 hour ago');+ expect(timeAgo(new Date('2021-01-01T02:00:00Z'))).toBe('2 hours ago');+ expect(timeAgo(new Date('2021-01-02T00:00:00Z'))).toBe('yesterday');+ expect(timeAgo(new Date('2021-01-03T00:00:00Z'))).toBe('2 days ago');+ expect(timeAgo(new Date('2021-02-01T00:00:00Z'))).toBe('last month');+ expect(timeAgo(new Date('2021-03-02T00:00:00Z'))).toBe('2 months ago');+ expect(timeAgo(new Date('2022-01-12T00:00:00Z'))).toBe('last year');+ expect(timeAgo(new Date('2023-01-01T00:00:00Z'))).toBe('2 years ago');+ });++ test('handles future dates correctly', () => {+ const formatter = createRelativeTimeFormatter({ getLocale: () => 'en' });+ const timeUntil = (now: Date) => formatter(new Date('2021-01-01T00:00:00Z'), { now });++ expect(timeUntil(new Date('2020-12-31T23:59:54Z'))).toBe('in 6 seconds');+ expect(timeUntil(new Date('2020-12-31T23:59:00Z'))).toBe('in 1 minute');+ expect(timeUntil(new Date('2020-12-31T23:58:00Z'))).toBe('in 2 minutes');+ expect(timeUntil(new Date('2020-12-31T23:00:00Z'))).toBe('in 1 hour');+ expect(timeUntil(new Date('2020-12-31T22:00:00Z'))).toBe('in 2 hours');+ expect(timeUntil(new Date('2020-12-31T00:00:00Z'))).toBe('tomorrow');+ expect(timeUntil(new Date('2020-12-30T00:00:00Z'))).toBe('in 2 days');+ expect(timeUntil(new Date('2020-12-01T00:00:00Z'))).toBe('next month');+ expect(timeUntil(new Date('2020-11-01T00:00:00Z'))).toBe('in 2 months');+ expect(timeUntil(new Date('2020-01-01T00:00:00Z'))).toBe('next year');+ expect(timeUntil(new Date('2019-01-01T00:00:00Z'))).toBe('in 2 years');+ });++ test('formats future dates according to locale', () => {+ expect(+ createRelativeTimeFormatter({ getLocale: () => 'en' })(new Date('2021-01-01T00:02:00Z'), { now: new Date('2021-01-01T00:00:00Z') }),+ ).to.eql('in 2 minutes');++ expect(+ createRelativeTimeFormatter({ getLocale: () => 'fr' })(new Date('2021-01-01T00:02:00Z'), { now: new Date('2021-01-01T00:00:00Z') }),+ ).to.eql('dans 2 minutes');++ expect(+ createRelativeTimeFormatter({ getLocale: () => 'pt-BR' })(new Date('2021-01-03T00:00:00Z'), { now: new Date('2021-01-01T00:00:00Z') }),+ ).to.eql('depois de amanhã');+ });++ test('the date can be a parsable string', () => {+ expect(+ createRelativeTimeFormatter({ getLocale: () => 'en' })('2021-01-01T00:00:00Z', { now: new Date('2021-01-01T00:00:00Z') }),+ ).to.eql('now');++ expect(+ createRelativeTimeFormatter({ getLocale: () => 'en' })('2021-01-01', { now: new Date('2021-01-01T00:02:00Z') }),+ ).to.eql('2 minutes ago');+ });+ });});diff --git a/apps/papra-client/src/modules/i18n/i18n.models.ts b/apps/papra-client/src/modules/i18n/i18n.models.tsindex 205c2da1..a53db2b7 100644--- a/apps/papra-client/src/modules/i18n/i18n.models.ts+++ b/apps/papra-client/src/modules/i18n/i18n.models.ts@@ -1,6 +1,7 @@import type { JSX } from 'solid-js';import type { Locale } from './i18n.provider';import { createBranchlet } from '@branchlet/core';+import { IN_MS } from '../shared/utils/units';// This tries to get the most preferred language compatible with the supported languages// It tries to find a supported language by comparing both region and language, if not, then just language@@ -71,3 +72,46 @@ export function createFragmentTranslator<Dict extends Record<string, string>>({return translation;};}++export function createDateFormatter({ getLocale }: { getLocale: () => string }) {+ return (date: Date, options: Intl.DateTimeFormatOptions = { year: 'numeric', month: 'short', day: 'numeric' }) => {+ return new Intl.DateTimeFormat(getLocale(), options).format(date);+ };+}++export function createRelativeTimeFormatter({ getLocale }: { getLocale: () => string }) {+ return (rawDate: Date | string, { now = new Date(), numeric = 'auto', style = 'long' }: { now?: Date; numeric?: 'auto' | 'always'; style?: 'long' | 'short' } = {}) => {+ const formatter = new Intl.RelativeTimeFormat(getLocale(), { numeric, style });++ const date = typeof rawDate === 'string' ? new Date(rawDate) : rawDate;+ const msDiff = now.getTime() - date.getTime();+ const absDiff = Math.abs(msDiff);+ const sign = msDiff >= 0 ? -1 : 1;++ if (absDiff < IN_MS.MINUTE) {+ return formatter.format(sign * Math.round(absDiff / 1_000), 'second');+ }++ if (absDiff < IN_MS.HOUR) {+ return formatter.format(sign * Math.round(absDiff / IN_MS.MINUTE), 'minute');+ }++ if (absDiff < IN_MS.DAY) {+ return formatter.format(sign * Math.round(absDiff / IN_MS.HOUR), 'hour');+ }++ if (absDiff < IN_MS.WEEK) {+ return formatter.format(sign * Math.round(absDiff / IN_MS.DAY), 'day');+ }++ if (absDiff < IN_MS.MONTH) {+ return formatter.format(sign * Math.round(absDiff / IN_MS.WEEK), 'week');+ }++ if (absDiff < IN_MS.YEAR) {+ return formatter.format(sign * Math.round(absDiff / IN_MS.MONTH), 'month');+ }++ return formatter.format(sign * Math.round(absDiff / IN_MS.YEAR), 'year');+ };+}diff --git a/apps/papra-client/src/modules/i18n/i18n.provider.tsx b/apps/papra-client/src/modules/i18n/i18n.provider.tsxindex 747c225f..b770234f 100644--- a/apps/papra-client/src/modules/i18n/i18n.provider.tsx+++ b/apps/papra-client/src/modules/i18n/i18n.provider.tsx@@ -4,7 +4,7 @@ import { makePersisted } from '@solid-primitives/storage';import { createContext, createEffect, createResource, createSignal, Show, useContext } from 'solid-js';import { translations as defaultTranslations } from '../../locales/en.dictionary';import { locales } from './i18n.constants';-import { createFragmentTranslator, createTranslator, findMatchingLocale } from './i18n.models';+import { createDateFormatter, createFragmentTranslator, createRelativeTimeFormatter, createTranslator, findMatchingLocale } from './i18n.models';export type Locale = typeof locales[number]['key'];@@ -14,6 +14,8 @@ const I18nContext = createContext<{getLocale: Accessor<Locale>;setLocale: Setter<Locale>;locales: typeof locales;+ formatDate: ReturnType<typeof createDateFormatter>;+ formatRelativeTime: ReturnType<typeof createRelativeTimeFormatter>;}>();export function useI18n() {@@ -58,6 +60,8 @@ export const I18nProvider: ParentComponent = (props) => {getLocale,setLocale,locales,+ formatDate: createDateFormatter({ getLocale }),+ formatRelativeTime: createRelativeTimeFormatter({ getLocale }),}}>{props.children}diff --git a/apps/papra-client/src/modules/organizations/pages/deleted-organizations.page.tsx b/apps/papra-client/src/modules/organizations/pages/deleted-organizations.page.tsxindex f6e37108..ed5a7b33 100644--- a/apps/papra-client/src/modules/organizations/pages/deleted-organizations.page.tsx+++ b/apps/papra-client/src/modules/organizations/pages/deleted-organizations.page.tsx@@ -11,7 +11,7 @@ import { createToast } from '@/modules/ui/components/sonner';import { fetchDeletedOrganizations, restoreOrganization } from '../organizations.services';export const DeletedOrganizationsPage: Component = () => {- const { t } = useI18n();+ const { t, formatDate } = useI18n();const queryClient = useQueryClient();const { confirm } = useConfirmModal();const { config } = useConfig();@@ -49,14 +49,6 @@ export const DeletedOrganizationsPage: Component = () => {restoreMutation.mutate({ organizationId });};- const formatDate = (date: Date) => {- return new Intl.DateTimeFormat(undefined, {- year: 'numeric',- month: 'short',- day: 'numeric',- }).format(date);- };-return (<div class="p-6 mt-4 pb-32 max-w-5xl mx-auto"><Button variant="ghost" as={A} href="/organizations" class="text-muted-foreground gap-2 ml--4">diff --git a/apps/papra-client/src/modules/shared/http/http-client.models.ts b/apps/papra-client/src/modules/shared/http/http-client.models.tsindex 4a765f5f..09c8313b 100644--- a/apps/papra-client/src/modules/shared/http/http-client.models.ts+++ b/apps/papra-client/src/modules/shared/http/http-client.models.ts@@ -25,6 +25,7 @@ export function coerceDates<T extends Record<string, any>>(obj: T): CoerceDates<...('updatedAt' in obj ? { updatedAt: toDate(obj.updatedAt) } : {}),...('deletedAt' in obj ? { deletedAt: toDate(obj.deletedAt) } : {}),...('expiresAt' in obj ? { expiresAt: toDate(obj.expiresAt) } : {}),+ ...('lastTriggeredAt' in obj ? { lastTriggeredAt: toDate(obj.lastTriggeredAt) } : {}),...('lastUsedAt' in obj ? { lastUsedAt: toDate(obj.lastUsedAt) } : {}),...('scheduledPurgeAt' in obj ? { scheduledPurgeAt: toDate(obj.scheduledPurgeAt) } : {}),};diff --git a/apps/papra-client/src/modules/shared/utils/units.ts b/apps/papra-client/src/modules/shared/utils/units.tsnew file mode 100644index 00000000..879f7560--- /dev/null+++ b/apps/papra-client/src/modules/shared/utils/units.ts@@ -0,0 +1,9 @@+export const IN_MS = {+ SECOND: 1_000,+ MINUTE: 60_000, // 60 * 1_000+ HOUR: 3_600_000, // 60 * 60 * 1_000+ DAY: 86_400_000, // 24 * 60 * 60 * 1_000+ WEEK: 604_800_000, // 7 * 24 * 60 * 60 * 1_000+ MONTH: 2_630_016_000, // 30.44 * 24 * 60 * 60 * 1_000 -- approximation using average month length+ YEAR: 31_556_736_000, // 365.24 * 24 * 60 * 60 * 1_000 -- approximation using average year length+};diff --git a/apps/papra-client/src/modules/webhooks/pages/webhooks.page.tsx b/apps/papra-client/src/modules/webhooks/pages/webhooks.page.tsxindex 275b28b2..6d65ab2a 100644--- a/apps/papra-client/src/modules/webhooks/pages/webhooks.page.tsx+++ b/apps/papra-client/src/modules/webhooks/pages/webhooks.page.tsx@@ -2,7 +2,6 @@ import type { Component } from 'solid-js';import type { Webhook } from '../webhooks.types';import { A, useParams } from '@solidjs/router';import { useMutation, useQuery } from '@tanstack/solid-query';-import { format } from 'date-fns';import { For, Match, Show, Suspense, Switch } from 'solid-js';import { useI18n } from '@/modules/i18n/i18n.provider';import { useConfirmModal } from '@/modules/shared/confirm';@@ -13,7 +12,7 @@ import { createToast } from '@/modules/ui/components/sonner';import { deleteWebhook, fetchWebhooks } from '../webhooks.services';export const WebhookCard: Component<{ webhook: Webhook }> = ({ webhook }) => {- const { t } = useI18n();+ const { t, formatRelativeTime } = useI18n();const { confirm } = useConfirmModal();const params = useParams();@@ -61,12 +60,12 @@ export const WebhookCard: Component<{ webhook: Webhook }> = ({ webhook }) => {<p class="text-muted-foreground text-xs">{t('webhooks.list.card.last-triggered')}{' '}- {webhook.lastTriggeredAt ? format(webhook.lastTriggeredAt, 'MMM d, yyyy') : t('webhooks.list.card.never')}+ {webhook.lastTriggeredAt ? formatRelativeTime(webhook.lastTriggeredAt) : t('webhooks.list.card.never')}</p><p class="text-muted-foreground text-xs">{t('webhooks.list.card.created')}{' '}- {format(webhook.createdAt, 'MMM d, yyyy')}+ {formatRelativeTime(webhook.createdAt)}</p></div>