Skip to content

armgit / papra

Public Imported from GitHub
0

The minimalistic document archiving platform.

feat(mobile): format dates by device locale (#1486)

Corentin Thomassetf3d36aac0d44
diff --git a/.changeset/orange-tips-search.md b/.changeset/orange-tips-search.md
new file mode 100644
index 00000000..ad27953c
--- /dev/null
+++ b/.changeset/orange-tips-search.md
@@ -0,0 +1,5 @@
+---
+'@papra/mobile': minor
+---
+
+Format date according to the user's locale in the mobile app.
diff --git a/apps/mobile/src/modules/documents/components/document-action-sheet.tsx b/apps/mobile/src/modules/documents/components/document-action-sheet.tsx
index 191f13be..c33d75c8 100644
--- a/apps/mobile/src/modules/documents/components/document-action-sheet.tsx
+++ b/apps/mobile/src/modules/documents/components/document-action-sheet.tsx
@@ -16,6 +16,7 @@ import {
View,
} from 'react-native';
import { useAppTranslations } from '@/modules/i18n/hooks/use-app-translations';
+import { useFormatters } from '@/modules/i18n/hooks/use-formatters';
import { useApiClient, useAuthClient } from '@/modules/api/providers/api.provider';
import { RenameDocumentDialog } from '@/modules/documents/components/rename-document-dialog';
import {
@@ -45,6 +46,7 @@ export function DocumentActionSheet({
onDeleted,
}: DocumentActionSheetProps) {
const t = useAppTranslations();
+ const { formatDate } = useFormatters();
const themeColors = useThemeColor();
const styles = createStyles({ themeColors });
const { showAlert } = useAlert();
@@ -57,15 +59,6 @@ export function DocumentActionSheet({
return null;
}
- const formatDate = (dateString: string): string => {
- const date = new Date(dateString);
- return date.toLocaleDateString('en-US', {
- month: 'short',
- day: 'numeric',
- year: 'numeric',
- });
- };
-
const handleView = async () => {
onClose();
router.push({
@@ -254,7 +247,7 @@ export function DocumentActionSheet({
{' · '}
{formatBytes({ bytes: document.originalSize })}
{' · '}
- {formatDate(document.createdAt.toISOString())}
+ {formatDate(document.createdAt)}
</Text>
</View>
</View>
diff --git a/apps/mobile/src/modules/documents/components/documents-list.tsx b/apps/mobile/src/modules/documents/components/documents-list.tsx
index db33cb66..9416fbb4 100644
--- a/apps/mobile/src/modules/documents/components/documents-list.tsx
+++ b/apps/mobile/src/modules/documents/components/documents-list.tsx
@@ -7,6 +7,7 @@ import { router } from 'expo-router';
import { useState } from 'react';
import { FlatList, StyleSheet, Text, TouchableOpacity, View } from 'react-native';
import { DocumentActionSheet } from '@/modules/documents/components/document-action-sheet';
+import { useFormatters } from '@/modules/i18n/hooks/use-formatters';
import { Tag } from '@/modules/tags/components/tag';
import { Icon } from '@/modules/ui/components/icon';
import { useThemeColor } from '@/modules/ui/providers/use-theme-color';
@@ -29,6 +30,7 @@ export function DocumentsList({
refreshControl,
keyboardShouldPersistTaps,
}: DocumentsListProps) {
+ const { formatDate } = useFormatters();
const themeColors = useThemeColor();
const [onDocumentActionSheet, setOnDocumentActionSheet] = useState<
CoerceDates<Document> | undefined
@@ -36,14 +38,6 @@ export function DocumentsList({
const styles = createStyles({ themeColors });
- const formatDate = (date: Date) => {
- return new Intl.DateTimeFormat('en-US', {
- month: 'short',
- day: 'numeric',
- year: 'numeric',
- }).format(date);
- };
-
return (
<>
{onDocumentActionSheet && (
diff --git a/apps/mobile/src/modules/documents/documents.models.test.ts b/apps/mobile/src/modules/documents/documents.models.test.ts
index b9b2a4bf..d086ea70 100644
--- a/apps/mobile/src/modules/documents/documents.models.test.ts
+++ b/apps/mobile/src/modules/documents/documents.models.test.ts
@@ -1,4 +1,5 @@
import { describe, expect, test } from 'vitest';
+import { createDateFormatter } from '../i18n/formatters.models';
import { formatCustomPropertyValue } from './documents.models';
describe('formatCustomPropertyValue', () => {
@@ -36,13 +37,35 @@ describe('formatCustomPropertyValue', () => {
{ type: 'date', value: 'invalid', expected: 'invalid' },
])('formats $type value $value as $expected', ({ type, value, expected }) => {
expect(
- formatCustomPropertyValue({
- key: 'property',
- name: 'Property',
- type,
- displayOrder: 0,
- value,
- }),
+ formatCustomPropertyValue(
+ {
+ key: 'property',
+ name: 'Property',
+ type,
+ displayOrder: 0,
+ value,
+ },
+ { formatDate: createDateFormatter({ locale: 'en-US' }) },
+ ),
+ ).toBe(expected);
+ });
+
+ test.each([
+ { locale: 'en-GB', expected: '15 Jan 2025' },
+ { locale: 'fr-CA', expected: '15 janv. 2025' },
+ { locale: 'it-IT', expected: '15 gen 2025' },
+ ])('formats custom-property dates using $locale', ({ locale, expected }) => {
+ expect(
+ formatCustomPropertyValue(
+ {
+ key: 'date',
+ name: 'Date',
+ type: 'date',
+ displayOrder: 0,
+ value: '2025-01-15T12:00:00',
+ },
+ { formatDate: createDateFormatter({ locale }) },
+ ),
).toBe(expected);
});
});
diff --git a/apps/mobile/src/modules/documents/documents.models.ts b/apps/mobile/src/modules/documents/documents.models.ts
index 74cdcae2..ef046dc5 100644
--- a/apps/mobile/src/modules/documents/documents.models.ts
+++ b/apps/mobile/src/modules/documents/documents.models.ts
@@ -1,13 +1,5 @@
import type { DocumentCustomProperty } from './documents.types';
-export function formatDate(date: Date): string {
- return new Intl.DateTimeFormat('en-US', {
- month: 'short',
- day: 'numeric',
- year: 'numeric',
- }).format(date);
-}
-
function formatSelectOption(value: unknown): string {
if (
typeof value === 'object' &&
@@ -21,7 +13,10 @@ function formatSelectOption(value: unknown): string {
return '';
}
-export function formatCustomPropertyValue({ type, value }: DocumentCustomProperty): string {
+export function formatCustomPropertyValue(
+ { type, value }: DocumentCustomProperty,
+ { formatDate }: { formatDate: (date: Date) => string },
+): string {
if (value == null || value === '' || (Array.isArray(value) && value.length === 0)) {
return '—';
}
diff --git a/apps/mobile/src/modules/documents/screens/document-details.screen.tsx b/apps/mobile/src/modules/documents/screens/document-details.screen.tsx
index d2d89a69..031ff978 100644
--- a/apps/mobile/src/modules/documents/screens/document-details.screen.tsx
+++ b/apps/mobile/src/modules/documents/screens/document-details.screen.tsx
@@ -17,9 +17,10 @@ import {
import { SafeAreaView } from 'react-native-safe-area-context';
import * as Sharing from 'expo-sharing';
import { useAppTranslations } from '@/modules/i18n/hooks/use-app-translations';
+import { useFormatters } from '@/modules/i18n/hooks/use-formatters';
import { useApiClient, useAuthClient } from '@/modules/api/providers/api.provider';
import { DocumentActionSheet } from '@/modules/documents/components/document-action-sheet';
-import { formatCustomPropertyValue, formatDate } from '@/modules/documents/documents.models';
+import { formatCustomPropertyValue } from '@/modules/documents/documents.models';
import { fetchDocument, fetchDocumentFile } from '@/modules/documents/documents.services';
import { Tag } from '@/modules/tags/components/tag';
import { Icon } from '@/modules/ui/components/icon';
@@ -73,6 +74,7 @@ function InfoRow({
export function DocumentDetailsScreen() {
const t = useAppTranslations();
+ const { formatDate } = useFormatters();
const router = useRouter();
const params = useLocalSearchParams<{ documentId: string; organizationId: string }>();
const themeColors = useThemeColor();
@@ -330,7 +332,7 @@ export function DocumentDetailsScreen() {
key={property.key}
icon={customPropertyTypeIcons[property.type] ?? 'tag'}
label={property.name}
- value={formatCustomPropertyValue(property)}
+ value={formatCustomPropertyValue(property, { formatDate })}
isLast={index === customProperties.length - 1}
styles={styles}
themeColors={themeColors}
diff --git a/apps/mobile/src/modules/i18n/formatters.models.test.ts b/apps/mobile/src/modules/i18n/formatters.models.test.ts
new file mode 100644
index 00000000..293a93af
--- /dev/null
+++ b/apps/mobile/src/modules/i18n/formatters.models.test.ts
@@ -0,0 +1,61 @@
+import { afterEach, describe, expect, test, vi } from 'vitest';
+import { createDateFormatter } from './formatters.models';
+
+// Use a local date so default-format tests do not depend on the machine's timezone.
+const date = new Date(2025, 0, 15, 12);
+
+describe('createDateFormatter', () => {
+ afterEach(() => {
+ vi.restoreAllMocks();
+ });
+
+ test.each([
+ { locale: 'en-US', expected: 'Jan 15, 2025' },
+ { locale: 'en-GB', expected: '15 Jan 2025' },
+ { locale: 'fr-CA', expected: '15 janv. 2025' },
+ { locale: 'it-IT', expected: '15 gen 2025' },
+ ])('formats dates using the full $locale tag', ({ locale, expected }) => {
+ expect(createDateFormatter({ locale })(date)).to.eql(expected);
+ });
+
+ test('custom options replace the default date fields', () => {
+ const formatDate = createDateFormatter({ locale: 'en-GB' });
+
+ expect(formatDate(date, { year: 'numeric' })).to.eql('2025');
+ expect(formatDate(date, { dateStyle: 'short' })).to.eql('15/01/2025');
+ expect(formatDate(date, { timeStyle: 'short' })).to.eql('12:00');
+ expect(formatDate(date)).to.eql('15 Jan 2025');
+ });
+
+ test('timestamps use the local timezone unless explicitly overridden', () => {
+ const formatDate = createDateFormatter({ locale: 'en-GB' });
+ const timestamp = new Date('2025-01-15T00:30:00Z');
+
+ expect(formatDate(timestamp)).to.eql(
+ new Intl.DateTimeFormat('en-GB', {
+ year: 'numeric',
+ month: 'short',
+ day: 'numeric',
+ }).format(timestamp),
+ );
+ expect(formatDate(timestamp, { dateStyle: 'short', timeZone: 'UTC' })).to.eql('15/01/2025');
+ expect(formatDate(timestamp, { dateStyle: 'short', timeZone: 'America/Los_Angeles' })).to.eql(
+ '14/01/2025',
+ );
+ });
+
+ test('reuses the default Intl formatter across calls', () => {
+ const DateTimeFormat = Intl.DateTimeFormat;
+ const dateTimeFormat = vi
+ .spyOn(Intl, 'DateTimeFormat')
+ .mockImplementation(function (locales, options) {
+ return new DateTimeFormat(locales, options);
+ });
+ const formatDate = createDateFormatter({ locale: 'en-GB' });
+
+ formatDate(date);
+ formatDate(new Date(2025, 0, 16, 12));
+
+ expect(dateTimeFormat).toHaveBeenCalledTimes(1);
+ });
+});
diff --git a/apps/mobile/src/modules/i18n/formatters.models.ts b/apps/mobile/src/modules/i18n/formatters.models.ts
new file mode 100644
index 00000000..ee2b7d2b
--- /dev/null
+++ b/apps/mobile/src/modules/i18n/formatters.models.ts
@@ -0,0 +1,14 @@
+export function createDateFormatter({ locale }: { locale: string }) {
+ const defaultFormatter = new Intl.DateTimeFormat(locale, {
+ year: 'numeric',
+ month: 'short',
+ day: 'numeric',
+ });
+
+ // Custom options replace the defaults so dateStyle/timeStyle can also be used.
+ return (date: Date, options?: Intl.DateTimeFormatOptions): string => {
+ const formatter = options ? new Intl.DateTimeFormat(locale, options) : defaultFormatter;
+
+ return formatter.format(date);
+ };
+}
diff --git a/apps/mobile/src/modules/i18n/hooks/use-formatters.ts b/apps/mobile/src/modules/i18n/hooks/use-formatters.ts
new file mode 100644
index 00000000..35890ab5
--- /dev/null
+++ b/apps/mobile/src/modules/i18n/hooks/use-formatters.ts
@@ -0,0 +1,13 @@
+import { useMemo } from 'react';
+import { createDateFormatter } from '../formatters.models';
+import { useLocale } from './use-locale';
+
+export function useFormatters() {
+ const { deviceLanguageTag } = useLocale();
+
+ // Keep regional formatting independent of the app's translation preference.
+ return useMemo(
+ () => ({ formatDate: createDateFormatter({ locale: deviceLanguageTag }) }),
+ [deviceLanguageTag],
+ );
+}
diff --git a/apps/mobile/src/modules/i18n/hooks/use-locale.tsx b/apps/mobile/src/modules/i18n/hooks/use-locale.tsx
index 7588f81c..a2161a6b 100644
--- a/apps/mobile/src/modules/i18n/hooks/use-locale.tsx
+++ b/apps/mobile/src/modules/i18n/hooks/use-locale.tsx
@@ -2,12 +2,13 @@ import { createContext, useContext, useEffect, useState } from 'react';
import type { ReactNode } from 'react';
import type { LocaleKey } from '../locales';
import { useLocales } from 'expo-localization';
-import { resolveUserLocale } from '../locales.models';
+import { getDeviceLanguageTag, resolveUserLocale } from '../locales.models';
import type { LocalePreference } from '../i18n.local-storage';
import { i18nLocalStorage } from '../i18n.local-storage';
type LocaleProviderContext = {
locale: LocaleKey;
+ deviceLanguageTag: string;
localePreference: LocalePreference;
setLocalePreference: (preference: LocalePreference) => Promise<void>;
};
@@ -41,6 +42,7 @@ export function LocaleProvider({ children }: { children: ReactNode }) {
};
const locale = localePreference ?? resolveUserLocale<LocaleKey>(userLocales);
+ const deviceLanguageTag = getDeviceLanguageTag(userLocales);
if (!isLocaleLoaded) {
return null;
@@ -50,6 +52,7 @@ export function LocaleProvider({ children }: { children: ReactNode }) {
<LocaleContext.Provider
value={{
locale,
+ deviceLanguageTag,
localePreference,
setLocalePreference,
}}
diff --git a/apps/mobile/src/modules/i18n/locales.models.test.ts b/apps/mobile/src/modules/i18n/locales.models.test.ts
index 3a3ff4b7..bb9088c4 100644
--- a/apps/mobile/src/modules/i18n/locales.models.test.ts
+++ b/apps/mobile/src/modules/i18n/locales.models.test.ts
@@ -1,7 +1,30 @@
import { describe, expect, test } from 'vitest';
-import { resolveUserLocale } from './locales.models';
+import { getDeviceLanguageTag, resolveUserLocale } from './locales.models';
describe('locales.models', () => {
+ describe('getDeviceLanguageTag', () => {
+ test.each(['en-GB', 'fr-CA', 'it-IT', 'zh-Hant-TW', 'en-US-u-ca-gregory'])(
+ 'it preserves the full device language tag %s',
+ (languageTag) => {
+ expect(getDeviceLanguageTag([{ languageTag }])).to.eql(languageTag);
+ },
+ );
+
+ test('it uses the first device language even when translations use a later one', () => {
+ const userLocales = [
+ { languageCode: 'it', languageTag: 'it-IT' },
+ { languageCode: 'fr', languageTag: 'fr-CA' },
+ ];
+
+ expect(getDeviceLanguageTag(userLocales)).to.eql('it-IT');
+ expect(resolveUserLocale(userLocales)).to.eql('fr');
+ });
+
+ test('it falls back to English when no device locales are available', () => {
+ expect(getDeviceLanguageTag([])).to.eql('en');
+ });
+ });
+
describe('resolveUserLocale', () => {
const localeConfig = {
supportedLocaleKeys: ['en', 'fr'],
diff --git a/apps/mobile/src/modules/i18n/locales.models.ts b/apps/mobile/src/modules/i18n/locales.models.ts
index 24406b38..4931f961 100644
--- a/apps/mobile/src/modules/i18n/locales.models.ts
+++ b/apps/mobile/src/modules/i18n/locales.models.ts
@@ -1,6 +1,11 @@
import type { LocaleKey } from './locales';
import { DEFAULT_LOCALE_KEY, LOCALE_KEYS } from './locales';
+// Formatting follows the preferred device language, even when it has no translations.
+export function getDeviceLanguageTag(userLocales: { languageTag: string }[]): string {
+ return userLocales[0]?.languageTag ?? DEFAULT_LOCALE_KEY;
+}
+
export function resolveUserLocale<Key extends string = LocaleKey>(
userLocales: { languageCode?: string | null; languageTag: string }[],
{