Skip to content

armgit / papra

Public Imported from GitHub
0

The minimalistic document archiving platform.

feat(i18n): added internationalization support (#107)

Corentin THOMASSET7c1aecd5fa91
diff --git a/.github/workflows/ci-apps-papra-client.yaml b/.github/workflows/ci-apps-papra-client.yaml
index ab5dde68..6fc58749 100644
--- a/.github/workflows/ci-apps-papra-client.yaml
+++ b/.github/workflows/ci-apps-papra-client.yaml
@@ -37,4 +37,10 @@ jobs:
run: pnpm test
- name: Build the app
- run: pnpm build
\ No newline at end of file
+ run: pnpm build
+
+ # Ensure locales types are up to date
+ - name: Check locales types
+ run: |
+ pnpm script:generate-i18n-types
+ git diff --exit-code -- src/modules/i18n/locales.types.ts > /dev/null || (echo "Locales types are outdated, please run 'pnpm script:generate-i18n-types' and commit the changes." && exit 1)
\ No newline at end of file
diff --git a/CONTRIBUTING.md b/CONTRIBUTING.md
index b787cf9d..06c79ad3 100644
--- a/CONTRIBUTING.md
+++ b/CONTRIBUTING.md
@@ -39,11 +39,28 @@ We use **[Conventional Commits](https://www.conventionalcommits.org/)** to keep
## i18n
-Information about the translation process can be found in the [locales README](./packages/app-client/src/locales/README.md).
+We welcome contributions to improve and expand the app's internationalization (i18n) support. Below are the guidelines for adding a new language or updating an existing translation.
+
+### Adding a New Language
+
+1. **Create a Language File**: To add a new language, create a YAML file named with the appropriate [ISO language code](https://en.wikipedia.org/wiki/List_of_ISO_639-1_codes) (e.g., `fr.yml` for French) in the [`apps/papra-client/src/locales`](./apps/papra-client/src/locales) directory.
+
+2. **Use the Reference File**: Refer to the [`en.yml`](./apps/papra-client/src/locales/en.yml) file, which contains all keys used in the app. Use it as a base to ensure consistency when creating your new language file. And act as a fallback if a key is missing in the new language file.
+
+3. **Update the Locale List**: After adding the new language file, include the language code in the `locales` array found in the [`apps/papra-client/src/modules/i18n/i18n.constants.ts`](./apps/papra-client/src/modules/i18n/i18n.constants.ts) file.
+
+4. **Submit a Pull Request**: Once you've added the file and updated `i18n.constants.ts`, create a pull request (PR) with your changes. Ensure that your PR is clearly titled with the language being added (e.g., "Add French translations").
### Updating an Existing Language
-If you want to update an existing language file, you can do so directly in the corresponding JSON file in the [`packages/app-client/src/locales`](./packages/app-client/src/locales) directory.
+If you want to update an existing language file, you can do so directly in the corresponding JSON file in the [`apps/papra-client/src/locales`](./apps/papra-client/src/locales) directory. If you're adding or removing keys in the default language file ([`en.yml`](./apps/papra-client/src/locales/en.yml)), please run the following command to update the types (used for type checking the translations keys in the app):
+
+```bash
+pnpm script:generate-i18n-types
+```
+
+- This command will update the file [`locales.types.ts`](./apps/papra-client/src/modules/i18n/locale.types.ts) with the new/removed keys.
+- Will developing you can use `pnpm script:generate-i18n-types:watch` to automatically update the types when you touch the [`en.yml`](./apps/papra-client/src/locales/en.yml) file.
## Development Setup
diff --git a/README.md b/README.md
index 57fc0b86..461cd9c4 100644
--- a/README.md
+++ b/README.md
@@ -51,12 +51,12 @@ A live demo of the platform is available at [demo.papra.cc](https://demo.papra.c
- **Tags**: Organize your documents with tags.
- **Email ingestion**: Send/forward emails to a generated address to automatically import documents.
- **Content extraction**: Automatically extract text from images or scanned documents for search.
+- **i18n**: Support for multiple languages.
- *Coming soon:* **Tagging Rules**: Automatically tag documents based on custom rules.
-- *Coming soon:* **i18n**: Support for multiple languages.
+- *Coming soon:* **Folder ingestion**: Automatically import documents from a folder.
- *Coming soon:* **SDK and API**: Build your own applications on top of Papra.
- *Coming soon:* **CLI**: Manage your documents from the command line.
- *Coming soon:* **Document sharing**: Share documents with others.
-- *Coming soon:* **Folder ingestion**: Automatically import documents from a folder.
- *Coming maybe one day:* **Mobile app**: Access and upload documents on the go.
- *Coming maybe one day:* **Desktop app**: Access and upload documents from your computer.
@@ -78,7 +78,7 @@ If you find this project helpful, please consider [supporting my work](https://b
### Stack
-Enclosed would not have been possible without the following open-source projects:
+Papra would not have been possible without the following open-source projects:
- **Frontend**
- **[SolidJS](https://www.solidjs.com)**: A declarative JavaScript library for building user interfaces.
diff --git a/apps/papra-client/package.json b/apps/papra-client/package.json
index cd79cb6d..c02a9223 100644
--- a/apps/papra-client/package.json
+++ b/apps/papra-client/package.json
@@ -20,12 +20,13 @@
"serve": "vite preview",
"lint": "eslint .",
"lint:fix": "eslint --fix .",
- "test": "pnpm run test:unit",
- "test:unit": "vitest run",
- "test:unit:watch": "vitest watch",
+ "test": "vitest run",
+ "test:watch": "vitest watch",
"test:e2e": "playwright test",
"typecheck": "tsc --noEmit",
- "script:get-missing-i18n-keys": "tsx src/scripts/get-missing-i18n-keys.script.ts"
+ "script:get-missing-i18n-keys": "tsx src/scripts/get-missing-i18n-keys.script.ts",
+ "script:generate-i18n-types": "tsx src/scripts/generate-i18n-types.script.ts",
+ "script:generate-i18n-types:watch": "tsx watch --include src/locales/en.yml src/scripts/generate-i18n-types.script.ts"
},
"dependencies": {
"@corentinth/chisels": "^1.0.2",
@@ -33,7 +34,6 @@
"@kobalte/utils": "^0.9.1",
"@modular-forms/solid": "^0.25.0",
"@pdfslick/solid": "^2.0.0",
- "@solid-primitives/i18n": "^2.1.1",
"@solid-primitives/storage": "^4.2.1",
"@solidjs/router": "^0.14.3",
"@tanstack/solid-query": "^5.61.5",
@@ -69,6 +69,7 @@
"unocss": "0.65.0-beta.2",
"vite": "^5.0.11",
"vite-plugin-solid": "^2.8.2",
- "vitest": "catalog:"
+ "vitest": "catalog:",
+ "yaml": "^2.7.0"
}
}
diff --git a/apps/papra-client/src/index.tsx b/apps/papra-client/src/index.tsx
index f7eccf5c..b87c3760 100644
--- a/apps/papra-client/src/index.tsx
+++ b/apps/papra-client/src/index.tsx
@@ -9,6 +9,7 @@ import { render, Suspense } from 'solid-js/web';
import { CommandPaletteProvider } from './modules/command-palette/command-palette.provider';
import { ConfigProvider } from './modules/config/config.provider';
import { DemoIndicator } from './modules/demo/demo.provider';
+import { I18nProvider } from './modules/i18n/i18n.provider';
import { PlausibleTracker } from './modules/plausible/components/plausible-tracker.component';
import { ConfirmModalProvider } from './modules/shared/confirm';
import { queryClient } from './modules/shared/query/query-client';
@@ -31,25 +32,27 @@ render(
<QueryClientProvider client={queryClient}>
<PlausibleTracker />
<Suspense>
- <ConfirmModalProvider>
- <ColorModeScript storageType={localStorageManager.type} storageKey={colorModeStorageKey} initialColorMode={initialColorMode} />
- <ColorModeProvider
- initialColorMode={initialColorMode}
- storageManager={localStorageManager}
- >
- <CommandPaletteProvider>
- <ConfigProvider>
- <div class="min-h-screen font-sans text-sm font-400">
- {props.children}
- </div>
- <DemoIndicator />
- </ConfigProvider>
+ <I18nProvider>
+ <ConfirmModalProvider>
+ <ColorModeScript storageType={localStorageManager.type} storageKey={colorModeStorageKey} initialColorMode={initialColorMode} />
+ <ColorModeProvider
+ initialColorMode={initialColorMode}
+ storageManager={localStorageManager}
+ >
+ <CommandPaletteProvider>
+ <ConfigProvider>
+ <div class="min-h-screen font-sans text-sm font-400">
+ {props.children}
+ </div>
+ <DemoIndicator />
+ </ConfigProvider>
- <Toaster />
- </CommandPaletteProvider>
- </ColorModeProvider>
+ <Toaster />
+ </CommandPaletteProvider>
+ </ColorModeProvider>
- </ConfirmModalProvider>
+ </ConfirmModalProvider>
+ </I18nProvider>
</Suspense>
</QueryClientProvider>
)}
diff --git a/apps/papra-client/src/locales/en.yml b/apps/papra-client/src/locales/en.yml
new file mode 100644
index 00000000..cd4f5455
--- /dev/null
+++ b/apps/papra-client/src/locales/en.yml
@@ -0,0 +1,28 @@
+auth:
+ login:
+ title: Login to Papra
+ description: Enter your email or use social login to access your Papra account.
+ login-with-provider: Login with {{ provider }}
+ no-account: Don't have an account?
+ register: Register
+
+tags:
+ no-tags:
+ title: No tags yet
+ description: This organization has no tags yet. Tags are used to categorize documents. You can add tags to your documents to make them easier to find and organize.
+ create-tag: Create tag
+
+layout:
+ menu:
+ home: Home
+ documents: Documents
+ tags: Tags
+ integrations: Integrations
+ deleted-documents: Deleted documents
+ organization-settings: Organization settings
+
+demo:
+ popup:
+ description: This is a demo environment, all data is save to your browser local storage.
+ reset: Reset demo data
+ hide: Hide
diff --git a/apps/papra-client/src/locales/fr.yml b/apps/papra-client/src/locales/fr.yml
new file mode 100644
index 00000000..ec9d9cfd
--- /dev/null
+++ b/apps/papra-client/src/locales/fr.yml
@@ -0,0 +1,28 @@
+auth:
+ login:
+ title: Connexion à Papra
+ description: Entrez votre adresse e-mail ou utilisez un service tiers pour accéder à votre compte Papra.
+ login-with-provider: Connexion via {{ provider }}
+ no-account: Vous n'avez pas de compte ?
+ register: S'inscrire
+
+tags:
+ no-tags:
+ title: Aucun tag pour le moment
+ description: Cette organisation n'a pas encore de tags. Les tags sont utilisés pour catégoriser les documents. Vous pouvez ajouter des tags à vos documents pour les rendre plus faciles à trouver et à organiser.
+ create-tag: Créer un tag
+
+layout:
+ menu:
+ home: Accueil
+ documents: Documents
+ tags: Tags
+ integrations: Intégrations
+ deleted-documents: Documents supprimés
+ organization-settings: Paramètres de l'orga.
+
+demo:
+ popup:
+ description: Ceci est un environnement de démo, toutes les données sont enregistrées dans le local storage de votre navigateur.
+ reset: Réinitialiser la démo
+ hide: Masquer
diff --git a/apps/papra-client/src/modules/auth/pages/login.page.tsx b/apps/papra-client/src/modules/auth/pages/login.page.tsx
index 794b3e03..450f112f 100644
--- a/apps/papra-client/src/modules/auth/pages/login.page.tsx
+++ b/apps/papra-client/src/modules/auth/pages/login.page.tsx
@@ -1,5 +1,6 @@
import type { SsoProviderKey } from '../auth.types';
import { useConfig } from '@/modules/config/config.provider';
+import { useI18n } from '@/modules/i18n/i18n.provider';
import { createForm } from '@/modules/shared/form/form';
import { createVitrineUrl } from '@/modules/shared/utils/urls';
import { Button } from '@/modules/ui/components/button';
@@ -98,30 +99,27 @@ export const EmailLoginForm: Component = () => {
export const LoginPage: Component = () => {
const { config } = useConfig();
+ const { t } = useI18n();
const [getShowEmailLogin, setShowEmailLogin] = createSignal(false);
const loginWithProvider = async (provider: { key: SsoProviderKey }) => {
- await signIn.social({ provider: provider.key });
+ await signIn.social({ provider: provider.key, callbackURL: config.baseUrl });
};
return (
<AuthLayout>
<div class="flex items-center justify-center min-h-screen p-6 pb-18">
<div class="max-w-sm w-full">
- <h1 class="text-xl font-bold">
- Login to Papra
- </h1>
- <p class="text-muted-foreground mt-1 mb-4">
- Enter your email or use social login to access your Papra account.
- </p>
+ <h1 class="text-xl font-bold">{t('auth.login.title')}</h1>
+ <p class="text-muted-foreground mt-1 mb-4">{t('auth.login.description')}</p>
{getShowEmailLogin()
? <EmailLoginForm />
: (
<Button onClick={() => setShowEmailLogin(true)} class="w-full">
<div class="i-tabler-mail mr-2 size-4.5" />
- Login with email
+ {t('auth.login.login-with-provider', { provider: 'Email' })}
</Button>
)}
@@ -130,16 +128,21 @@ export const LoginPage: Component = () => {
<div class="flex flex-col gap-2">
<For each={getEnabledSsoProviderConfigs({ config })}>
{provider => (
- <SsoProviderButton name={provider.name} icon={provider.icon} onClick={() => loginWithProvider(provider)} label={`Login with ${provider.name}`} />
+ <SsoProviderButton
+ name={provider.name}
+ icon={provider.icon}
+ onClick={() => loginWithProvider(provider)}
+ label={t('auth.login.login-with-provider', { provider: provider.name })}
+ />
)}
</For>
</div>
<p class="text-muted-foreground mt-4">
- Don't have an account?
+ {t('auth.login.no-account')}
{' '}
<Button variant="link" as={A} class="inline px-0" href="/register">
- Register
+ {t('auth.login.register')}
</Button>
</p>
diff --git a/apps/papra-client/src/modules/demo/demo.provider.tsx b/apps/papra-client/src/modules/demo/demo.provider.tsx
index 3efae35c..ad4acf0f 100644
--- a/apps/papra-client/src/modules/demo/demo.provider.tsx
+++ b/apps/papra-client/src/modules/demo/demo.provider.tsx
@@ -2,12 +2,14 @@ import { useNavigate } from '@solidjs/router';
import { type Component, createSignal } from 'solid-js';
import { Portal } from 'solid-js/web';
import { buildTimeConfig } from '../config/config';
+import { useI18n } from '../i18n/i18n.provider';
import { Button } from '../ui/components/button';
import { clearDemoStorage } from './demo.storage';
export const DemoIndicator: Component = () => {
const [getIsMinified, setIsMinified] = createSignal(false);
const navigate = useNavigate();
+ const { t } = useI18n();
const clearDemo = async () => {
await clearDemoStorage();
@@ -29,15 +31,15 @@ export const DemoIndicator: Component = () => {
: (
<div class="fixed bottom-4 right-4 z-50 bg-primary text-primary-foreground p-5 py-4 rounded-xl shadow-md max-w-300px">
<p class="text-sm">
- This is a demo environment, all data is save to your browser local storage.
+ {t('demo.popup.description')}
</p>
<div class="flex justify-end mt-4 gap-2">
<Button variant="secondary" onClick={clearDemo} size="sm" class="text-primary shadow-none">
- Reset demo data
+ {t('demo.popup.reset')}
</Button>
<Button onClick={() => setIsMinified(true)} class="bg-transparent hover:text-primary" variant="outline" size="sm">
- Hide
+ {t('demo.popup.hide')}
</Button>
</div>
</div>
diff --git a/apps/papra-client/src/modules/i18n/i18n.constants.ts b/apps/papra-client/src/modules/i18n/i18n.constants.ts
new file mode 100644
index 00000000..7011f516
--- /dev/null
+++ b/apps/papra-client/src/modules/i18n/i18n.constants.ts
@@ -0,0 +1,4 @@
+export const locales = [
+ { key: 'en', name: 'English' },
+ { key: 'fr', name: 'Français' },
+];
diff --git a/apps/papra-client/src/modules/i18n/i18n.models.test.ts b/apps/papra-client/src/modules/i18n/i18n.models.test.ts
new file mode 100644
index 00000000..0d299a6a
--- /dev/null
+++ b/apps/papra-client/src/modules/i18n/i18n.models.test.ts
@@ -0,0 +1,127 @@
+import { describe, expect, test } from 'vitest';
+import { createTranslator, findMatchingLocale } from './i18n.models';
+
+describe('i18n models', () => {
+ describe('findMatchingLocale', () => {
+ test('preferred regional language to regional language', () => {
+ const preferredLocales = ['pt-BR'].map(x => new Intl.Locale(x));
+ const supportedLocales = ['en', 'pt-BR'].map(x => new Intl.Locale(x));
+ const locale = findMatchingLocale({ preferredLocales, supportedLocales });
+
+ expect(locale).to.eql('pt-BR');
+ });
+
+ test('preferred non-regional language to non-regional language', () => {
+ const preferredLocales = ['pt'].map(x => new Intl.Locale(x));
+ const supportedLocales = ['pt-BR', 'pt'].map(x => new Intl.Locale(x));
+ const locale = findMatchingLocale({ preferredLocales, supportedLocales });
+
+ expect(locale).to.eql('pt');
+ });
+
+ test('preferred regional language to non-regional language', () => {
+ const preferredLocales = ['en-GB'].map(x => new Intl.Locale(x));
+ const supportedLocales = ['pt-BR', 'en'].map(x => new Intl.Locale(x));
+ const locale = findMatchingLocale({ preferredLocales, supportedLocales });
+
+ expect(locale).to.eql('en');
+ });
+
+ test('preferred language with different region to supported language', () => {
+ const preferredLocales = ['en-CA'].map(x => new Intl.Locale(x));
+ const supportedLocales = ['fr-FR', 'en-US'].map(x => new Intl.Locale(x));
+ const locale = findMatchingLocale({ preferredLocales, supportedLocales });
+
+ expect(locale).to.eql('en-US');
+ });
+
+ test('preferred language not in supported locales', () => {
+ const preferredLocales = ['it-IT'].map(x => new Intl.Locale(x));
+ const supportedLocales = ['es-ES', 'de-DE'].map(x => new Intl.Locale(x));
+ const locale = findMatchingLocale({ preferredLocales, supportedLocales });
+
+ expect(locale).to.eql('en');
+ });
+
+ test('empty preferred locales', () => {
+ const preferredLocales: Intl.Locale[] = [];
+ const supportedLocales = ['en', 'pt-BR'].map(x => new Intl.Locale(x));
+ const locale = findMatchingLocale({ preferredLocales, supportedLocales });
+
+ expect(locale).to.eql('en');
+ });
+
+ test('empty supported locales', () => {
+ const preferredLocales = ['en-GB', 'pt-BR'].map(x => new Intl.Locale(x));
+ const supportedLocales: Intl.Locale[] = [];
+ const locale = findMatchingLocale({ preferredLocales, supportedLocales });
+
+ expect(locale).to.eql('en');
+ });
+ });
+
+ describe('createTranslator', () => {
+ test('it build a function that return the value of a key in the provided dictionary', () => {
+ const dictionary = {
+ hello: 'Hello!',
+ };
+ const t = createTranslator({ getDictionary: () => dictionary });
+
+ expect(t('hello')).to.eql('Hello!');
+ });
+
+ test('the translator returns the key if the key is not in the dictionary', () => {
+ const dictionary = {
+ hello: 'Hello!',
+ };
+ const t = createTranslator({ getDictionary: () => dictionary });
+
+ expect(t('world' as any)).to.eql('world');
+ });
+
+ test('the translator replaces the placeholders in the translation', () => {
+ const dictionary = {
+ hello: 'Hello, {{ name }}!',
+ };
+ const t = createTranslator({ getDictionary: () => dictionary });
+
+ expect(t('hello', { name: 'John' })).to.eql('Hello, John!');
+ });
+
+ test('the translator replaces all occurrences of the placeholder', () => {
+ const dictionary = {
+ hello: 'Hello, {{ name }}! How are you, {{ name }}?',
+ };
+ const t = createTranslator({ getDictionary: () => dictionary });
+
+ expect(t('hello', { name: 'John' })).to.eql('Hello, John! How are you, John?');
+ });
+
+ test('the translator replaces multiple placeholders', () => {
+ const dictionary = {
+ hello: 'Hello, {{ name }} {{ surname }}!',
+ };
+ const t = createTranslator({ getDictionary: () => dictionary });
+
+ expect(t('hello', { name: 'John', surname: 'Doe' })).to.eql('Hello, John Doe!');
+ });
+
+ test('when no value is provided for a placeholder, it keeps the placeholder', () => {
+ const dictionary = {
+ hello: 'Hello, {{ name }}!',
+ };
+ const t = createTranslator({ getDictionary: () => dictionary });
+
+ expect(t('hello')).to.eql('Hello, {{ name }}!');
+ });
+
+ test('the spaces around the placeholder are optional', () => {
+ const dictionary = {
+ hello: '{{name}}, {{ name }}, {{ name}} and {{ name }}!',
+ };
+ const t = createTranslator({ getDictionary: () => dictionary });
+
+ expect(t('hello', { name: 'John' })).to.eql('John, John, John and John!');
+ });
+ });
+});
diff --git a/apps/papra-client/src/modules/i18n/i18n.models.ts b/apps/papra-client/src/modules/i18n/i18n.models.ts
new file mode 100644
index 00000000..2574ec3e
--- /dev/null
+++ b/apps/papra-client/src/modules/i18n/i18n.models.ts
@@ -0,0 +1,42 @@
+import type { Locale } from './i18n.provider';
+
+// 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
+// For example:
+// en-GB -> en
+// pt-BR -> pt-BR
+export function findMatchingLocale({
+ preferredLocales,
+ supportedLocales,
+}: {
+ preferredLocales: Intl.Locale[];
+ supportedLocales: Intl.Locale[];
+}) {
+ for (const locale of preferredLocales) {
+ const localeMatchRegion = supportedLocales.find(x => x.baseName === locale.baseName);
+
+ if (localeMatchRegion) {
+ return localeMatchRegion.baseName as Locale;
+ }
+
+ const localeMatchLanguage = supportedLocales.find(x => x.language === locale.language);
+ if (localeMatchLanguage) {
+ return localeMatchLanguage.baseName as Locale;
+ }
+ }
+ return 'en';
+}
+
+export function createTranslator<Dict extends Record<string, string>>({ getDictionary }: { getDictionary: () => Dict }) {
+ return (key: keyof Dict, args?: Record<string, string | number>) => {
+ let translation: string = getDictionary()[key] ?? key;
+
+ if (args) {
+ for (const [key, value] of Object.entries(args)) {
+ translation = translation.replace(new RegExp(`{{\\s*${key}\\s*}}`, 'g'), String(value));
+ }
+ }
+
+ return translation;
+ };
+}
diff --git a/apps/papra-client/src/modules/i18n/i18n.provider.tsx b/apps/papra-client/src/modules/i18n/i18n.provider.tsx
new file mode 100644
index 00000000..b53a73dc
--- /dev/null
+++ b/apps/papra-client/src/modules/i18n/i18n.provider.tsx
@@ -0,0 +1,67 @@
+import type { Accessor, ParentComponent, Setter } from 'solid-js';
+import type { LocaleKeys } from './locales.types';
+import { makePersisted } from '@solid-primitives/storage';
+import { createContext, createEffect, createResource, createSignal, Show, useContext } from 'solid-js';
+import defaultDict from '../../locales/en.yml?flattened';
+import { locales } from './i18n.constants';
+import { createTranslator, findMatchingLocale } from './i18n.models';
+
+export type Locale = typeof locales[number]['key'];
+type Dictionary = Record<LocaleKeys, string>;
+
+const I18nContext = createContext<{
+ t: ReturnType<typeof createTranslator<Dictionary>>;
+ getLocale: Accessor<Locale>;
+ setLocale: Setter<Locale>;
+ locales: typeof locales;
+}>();
+
+export function useI18n() {
+ const context = useContext(I18nContext);
+
+ if (!context) {
+ throw new Error('I18n context not found, useI18n must be used within I18nProvider');
+ }
+
+ return context;
+}
+
+async function fetchDictionary(locale: Locale): Promise<Dictionary> {
+ const { default: dict } = await import(`../../locales/${locale}.yml?flattened`);
+
+ return {
+ ...defaultDict,
+ ...dict,
+ };
+}
+
+export const I18nProvider: ParentComponent = (props) => {
+ const browserLocale = findMatchingLocale({
+ preferredLocales: navigator.languages.map(x => new Intl.Locale(x)),
+ supportedLocales: locales.map(x => new Intl.Locale(x.key)),
+ });
+ const [getLocale, setLocale] = makePersisted(createSignal<Locale>(browserLocale), { name: 'papra_locale', storage: localStorage });
+
+ const [dict] = createResource(getLocale, fetchDictionary);
+
+ createEffect(() => {
+ document.documentElement.lang = getLocale();
+ });
+
+ return (
+ <Show when={dict.latest}>
+ {getDictionary => (
+ <I18nContext.Provider
+ value={{
+ t: createTranslator({ getDictionary }),
+ getLocale,
+ setLocale,
+ locales,
+ }}
+ >
+ {props.children}
+ </I18nContext.Provider>
+ )}
+ </Show>
+ );
+};
diff --git a/apps/papra-client/src/modules/i18n/locales.test.ts b/apps/papra-client/src/modules/i18n/locales.test.ts
new file mode 100644
index 00000000..e84b489b
--- /dev/null
+++ b/apps/papra-client/src/modules/i18n/locales.test.ts
@@ -0,0 +1,29 @@
+import { describe, expect, test } from 'vitest';
+
+const rawLocales = import.meta.glob('../../locales/*.yml', { eager: true, query: '?flattened' });
+const { en: defaultLocal, ...locales } = Object.fromEntries(
+ Object.entries(rawLocales).map(([key, value]: [string, any]) => [key.replace('../../locales/', '').replace('.yml', ''), value.default]),
+);
+
+describe('locales', () => {
+ for (const [locale, translations] of Object.entries(locales)) {
+ describe(locale, () => {
+ test(`locale ${locale} must not have extra keys compared to default`, () => {
+ const extraKeys = Object
+ .keys(translations)
+ .filter(key => !(key in defaultLocal));
+
+ expect(extraKeys).to.eql([], `Extra keys found in ${locale}`);
+ });
+
+ test(`all translations in ${locale} must be strings`, () => {
+ const nonStringTranslations = Object
+ .entries(translations)
+ .filter(([, value]) => typeof value !== 'string')
+ .map(([key]) => key);
+
+ expect(nonStringTranslations).to.eql([], `Non-string translations found in ${locale}`);
+ });
+ });
+ }
+});
diff --git a/apps/papra-client/src/modules/i18n/locales.types.ts b/apps/papra-client/src/modules/i18n/locales.types.ts
new file mode 100644
index 00000000..11f4a609
--- /dev/null
+++ b/apps/papra-client/src/modules/i18n/locales.types.ts
@@ -0,0 +1,2 @@
+// Dynamically generated file. Use "pnpm script:generate-i18n-types" to update.
+export type LocaleKeys = 'auth.login.title' | 'auth.login.description' | 'auth.login.login-with-provider' | 'auth.login.no-account' | 'auth.login.register' | 'tags.no-tags.title' | 'tags.no-tags.description' | 'tags.no-tags.create-tag' | 'layout.menu.home' | 'layout.menu.documents' | 'layout.menu.tags' | 'layout.menu.integrations' | 'layout.menu.deleted-documents' | 'layout.menu.organization-settings' | 'demo.popup.description' | 'demo.popup.reset' | 'demo.popup.hide';
diff --git a/apps/papra-client/src/modules/tags/pages/tags.page.tsx b/apps/papra-client/src/modules/tags/pages/tags.page.tsx
index 3635f2bc..f0006177 100644
--- a/apps/papra-client/src/modules/tags/pages/tags.page.tsx
+++ b/apps/papra-client/src/modules/tags/pages/tags.page.tsx
@@ -1,5 +1,6 @@
import type { DialogTriggerProps } from '@kobalte/core/dialog';
import type { Tag as TagType } from '../tags.types';
+import { useI18n } from '@/modules/i18n/i18n.provider';
import { useConfirmModal } from '@/modules/shared/confirm';
import { timeAgo } from '@/modules/shared/date/time-ago';
import { createForm } from '@/modules/shared/form/form';
@@ -190,6 +191,7 @@ const UpdateTagModal: Component<{
export const TagsPage: Component = () => {
const params = useParams();
const { confirm } = useConfirmModal();
+ const { t } = useI18n();
const query = createQuery(() => ({
queryKey: ['organizations', params.organizationId, 'tags'],
@@ -239,15 +241,15 @@ export const TagsPage: Component = () => {
when={getTags().length > 0}
fallback={(
<EmptyState
- title="No tags yet"
+ title={t('tags.no-tags.title')}
icon="i-tabler-tag"
- description="This organization has no tags yet. Tags are used to categorize documents. You can add tags to your documents to make them easier to find and organize."
+ description={t('tags.no-tags.description')}
cta={(
<CreateTagModal organizationId={params.organizationId}>
{props => (
<Button {...props}>
<div class="i-tabler-plus size-4 mr-2" />
- Create tag
+ {t('tags.no-tags.create-tag')}
</Button>
)}
</CreateTagModal>
diff --git a/apps/papra-client/src/modules/ui/layouts/organization.layout.tsx b/apps/papra-client/src/modules/ui/layouts/organization.layout.tsx
index 3da7404d..785b891f 100644
--- a/apps/papra-client/src/modules/ui/layouts/organization.layout.tsx
+++ b/apps/papra-client/src/modules/ui/layouts/organization.layout.tsx
@@ -1,7 +1,8 @@
import type { Organization } from '@/modules/organizations/organizations.types';
-import { fetchOrganization, fetchOrganizations } from '@/modules/organizations/organizations.services';
+import { useI18n } from '@/modules/i18n/i18n.provider';
+import { fetchOrganization, fetchOrganizations } from '@/modules/organizations/organizations.services';
import { useNavigate, useParams } from '@solidjs/router';
import { createQueries, createQuery } from '@tanstack/solid-query';
import { get } from 'lodash-es';
@@ -18,26 +19,27 @@ import { SideNav, SidenavLayout } from './sidenav.layout';
const OrganizationLayoutSideNav: Component = () => {
const navigate = useNavigate();
const params = useParams();
+ const { t } = useI18n();
const getMainMenuItems = () => [
{
- label: 'Home',
+ label: t('layout.menu.home'),
icon: 'i-tabler-home',
href: `/organizations/${params.organizationId}`,
},
{
- label: 'Documents',
+ label: t('layout.menu.documents'),
icon: 'i-tabler-file-text',
href: `/organizations/${params.organizationId}/documents`,
},
{
- label: 'Tags',
+ label: t('layout.menu.tags'),
icon: 'i-tabler-tag',
href: `/organizations/${params.organizationId}/tags`,
},
{
- label: 'Integrations',
+ label: t('layout.menu.integrations'),
icon: 'i-tabler-link',
href: `/organizations/${params.organizationId}/intake-emails`,
},
@@ -46,12 +48,12 @@ const OrganizationLayoutSideNav: Component = () => {
const getFooterMenuItems = () => [
{
- label: 'Deleted documents',
+ label: t('layout.menu.deleted-documents'),
icon: 'i-tabler-trash',
href: `/organizations/${params.organizationId}/deleted`,
},
{
- label: 'Organization settings',
+ label: t('layout.menu.organization-settings'),
icon: 'i-tabler-settings',
href: `/organizations/${params.organizationId}/settings`,
},
diff --git a/apps/papra-client/src/modules/ui/layouts/sidenav.layout.tsx b/apps/papra-client/src/modules/ui/layouts/sidenav.layout.tsx
index 9302f2ae..6bf18472 100644
--- a/apps/papra-client/src/modules/ui/layouts/sidenav.layout.tsx
+++ b/apps/papra-client/src/modules/ui/layouts/sidenav.layout.tsx
@@ -5,15 +5,16 @@ import { useConfig } from '@/modules/config/config.provider';
import { GlobalDropArea } from '@/modules/documents/components/global-drop-area.component';
import { uploadDocument } from '@/modules/documents/documents.services';
+import { useI18n } from '@/modules/i18n/i18n.provider';
import { promptUploadFiles } from '@/modules/shared/files/upload';
-import { queryClient } from '@/modules/shared/query/query-client';
+import { queryClient } from '@/modules/shared/query/query-client';
import { cn } from '@/modules/shared/style/cn';
import { useThemeStore } from '@/modules/theme/theme.store';
import { Button } from '@/modules/ui/components/button';
import { A, useNavigate, useParams } from '@solidjs/router';
-import { type Component, type ComponentProps, type JSX, type ParentComponent, Suspense } from 'solid-js';
-import { DropdownMenu, DropdownMenuContent, DropdownMenuItem, DropdownMenuTrigger } from '../components/dropdown-menu';
+import { type Component, type ComponentProps, type JSX, type ParentComponent, Show, Suspense } from 'solid-js';
+import { DropdownMenu, DropdownMenuContent, DropdownMenuItem, DropdownMenuSub, DropdownMenuSubContent, DropdownMenuSubTrigger, DropdownMenuTrigger } from '../components/dropdown-menu';
import { Sheet, SheetContent, SheetTrigger } from '../components/sheet';
import { Tooltip, TooltipContent, TooltipTrigger } from '../components/tooltip';
@@ -47,8 +48,8 @@ export const SideNav: Component<{
const getShortSideNavItems = () => [
{
- to: '/organizations',
label: 'All organizations',
+ to: '/organizations',
icon: 'i-tabler-building-community',
},
{
@@ -145,6 +146,33 @@ const ThemeSwitcher: Component = () => {
);
};
+const LanguageSwitcher: Component = () => {
+ const { getLocale, setLocale, locales } = useI18n();
+ const languageName = new Intl.DisplayNames(getLocale(), {
+ type: 'language',
+ languageDisplay: 'standard',
+ });
+
+ return (
+ <>
+ {locales.map(locale => (
+ <DropdownMenuItem onClick={() => setLocale(locale.key)} class={cn('cursor-pointer', { 'font-bold': getLocale() === locale.key })}>
+ <span translate="no" lang={getLocale() === locale.key ? undefined : locale.key}>
+ {locale.name}
+ </span>
+ <Show when={getLocale() !== locale.key}>
+ <span class="text-muted-foreground pl-1">
+ (
+ {languageName.of(locale.key)}
+ )
+ </span>
+ </Show>
+ </DropdownMenuItem>
+ ))}
+ </>
+ );
+};
+
export const SidenavLayout: ParentComponent<{
sideNav: Component;
showSearch?: boolean;
@@ -233,6 +261,17 @@ export const SidenavLayout: ParentComponent<{
Account settings
</DropdownMenuItem>
+ <DropdownMenuSub>
+ <DropdownMenuSubTrigger class="flex items-center gap-2 cursor-pointer">
+ <div class="i-tabler-language size-4 text-muted-foreground"></div>
+ Language
+ </DropdownMenuSubTrigger>
+
+ <DropdownMenuSubContent>
+ <LanguageSwitcher />
+ </DropdownMenuSubContent>
+ </DropdownMenuSub>
+
<DropdownMenuItem
onClick={async () => {
await signOut();
diff --git a/apps/papra-client/src/plugins/yaml-flattened/yaml-flattened.models.ts b/apps/papra-client/src/plugins/yaml-flattened/yaml-flattened.models.ts
new file mode 100644
index 00000000..4611c887
--- /dev/null
+++ b/apps/papra-client/src/plugins/yaml-flattened/yaml-flattened.models.ts
@@ -0,0 +1,24 @@
+import { parse } from 'yaml';
+
+function flattenObject(
+ obj: Record<string, any>,
+ parentKeys: string[] = [],
+ result: Record<string, string> = {},
+): Record<string, string> {
+ for (const key in obj) {
+ const newKey = [...parentKeys, key];
+ if (typeof obj[key] === 'object' && obj[key] !== null) {
+ flattenObject(obj[key], newKey, result);
+ } else {
+ result[newKey.join('.')] = obj[key];
+ }
+ }
+ return result;
+}
+
+export function flattenYaml({ code }: { code: string }): Record<string, string> {
+ const parsed = parse(code);
+ const flattenedData = flattenObject(parsed);
+
+ return flattenedData;
+}
diff --git a/apps/papra-client/src/plugins/yaml-flattened/yaml-flattened.plugin.ts b/apps/papra-client/src/plugins/yaml-flattened/yaml-flattened.plugin.ts
new file mode 100644
index 00000000..d3bc30da
--- /dev/null
+++ b/apps/papra-client/src/plugins/yaml-flattened/yaml-flattened.plugin.ts
@@ -0,0 +1,21 @@
+import type { Plugin } from 'vite';
+import { flattenYaml } from './yaml-flattened.models';
+
+export function yamlFlattenPlugin(): Plugin {
+ return {
+ name: 'vite-plugin-yaml-flatten',
+ enforce: 'pre',
+
+ async transform(code, id) {
+ if (id.endsWith('.yml?flattened') || id.endsWith('.yaml?flattened')) {
+ const flattenedData = flattenYaml({ code });
+
+ return {
+ code: `export default ${JSON.stringify(flattenedData)};`,
+ map: null,
+ };
+ }
+ return null;
+ },
+ };
+}
diff --git a/apps/papra-client/src/scripts/generate-i18n-types.script.ts b/apps/papra-client/src/scripts/generate-i18n-types.script.ts
new file mode 100644
index 00000000..3cff2500
--- /dev/null
+++ b/apps/papra-client/src/scripts/generate-i18n-types.script.ts
@@ -0,0 +1,15 @@
+import { readFile, writeFile } from 'node:fs/promises';
+import { flattenYaml } from '@/plugins/yaml-flattened/yaml-flattened.models';
+
+const enLocales = await readFile('src/locales/en.yml', 'utf-8');
+const parsedLocales = flattenYaml({ code: enLocales });
+
+const localKeys = Object.keys(parsedLocales);
+const localesTypeDefinition = `
+// Dynamically generated file. Use "pnpm script:generate-i18n-types" to update.
+export type LocaleKeys = ${localKeys.map(key => `'${key}'`).join(' | ')};
+`.trimStart();
+
+await writeFile('src/modules/i18n/locales.types.ts', localesTypeDefinition);
+
+console.log('Successfully generated i18n types');
diff --git a/apps/papra-client/vite.config.ts b/apps/papra-client/vite.config.ts
index 0d2e1a97..ad8717f0 100644
--- a/apps/papra-client/vite.config.ts
+++ b/apps/papra-client/vite.config.ts
@@ -3,9 +3,11 @@ import unoCssPlugin from 'unocss/vite';
import { defineConfig } from 'vite';
import solidPlugin from 'vite-plugin-solid';
import { version } from './package.json';
+import { yamlFlattenPlugin } from './src/plugins/yaml-flattened/yaml-flattened.plugin';
export default defineConfig({
plugins: [
+ yamlFlattenPlugin(),
unoCssPlugin(),
solidPlugin(),
],
diff --git a/apps/papra-client/vite.env.d.ts b/apps/papra-client/vite.env.d.ts
new file mode 100644
index 00000000..a92a9d54
--- /dev/null
+++ b/apps/papra-client/vite.env.d.ts
@@ -0,0 +1,6 @@
+declare module '*.yml?flattened' {
+ import type { LocaleKeys } from './types'; // Adjust the import path as needed
+
+ const value: Record<LocaleKeys, string>;
+ export default value;
+}
diff --git a/pnpm-lock.yaml b/pnpm-lock.yaml
index e00e0b08..21387812 100644
--- a/pnpm-lock.yaml
+++ b/pnpm-lock.yaml
@@ -12,9 +12,6 @@ catalogs:
'@types/node':
specifier: ^22.5.4
version: 22.10.7
- '@vitest/coverage-v8':
- specifier: ^3.0.2
- version: 3.0.2
eslint:
specifier: ^9.10.0
version: 9.18.0
@@ -96,9 +93,6 @@ importers:
'@pdfslick/solid':
specifier: ^2.0.0
- '@solid-primitives/i18n':
- specifier: ^2.1.1
- version: 2.1.1([email protected])
'@solid-primitives/storage':
specifier: ^4.2.1
version: 4.2.1([email protected])
@@ -202,6 +196,9 @@ importers:
vitest:
specifier: 'catalog:'
+ yaml:
+ specifier: ^2.7.0
+ version: 2.7.0
apps/papra-server:
dependencies:
@@ -2293,11 +2290,6 @@ packages:
peerDependencies:
solid-js: ^1.6.12
- '@solid-primitives/[email protected]':
- resolution: {integrity: sha512-1p9B8hveu+gzFRWfXcRtdzzEdr7gw3c8uLXm+2bU33JHgiI8kYJsWvG128sE6vU1ZtYGPrGq980Jd6hxYupyZQ==}
- peerDependencies:
- solid-js: ^1.6.12
-
'@solid-primitives/[email protected]':
resolution: {integrity: sha512-Tlm2wCKcXEVxqd1speWjPhGvDhuuo/VeWSvNF6r2h77BUOHRKmNwz9uVKKMQmYSaLwiptJTp+fPZY2dOVPWQRQ==}
peerDependencies:
@@ -8389,10 +8381,6 @@ snapshots:
'@solid-primitives/utils': 6.2.3([email protected])
solid-js: 1.9.4
- '@solid-primitives/[email protected]([email protected])':
- dependencies:
- solid-js: 1.9.4
-
'@solid-primitives/[email protected]([email protected])':
dependencies:
solid-js: 1.9.4
@@ -9920,7 +9908,7 @@ snapshots:
dependencies:
'@eslint-community/eslint-utils': 4.4.1([email protected]([email protected]))
'@jridgewell/sourcemap-codec': 1.5.0
- '@typescript-eslint/types': 8.19.1
+ '@typescript-eslint/types': 8.21.0
astro-eslint-parser: 1.1.0([email protected])
eslint: 9.18.0([email protected])
eslint-compat-utils: 0.6.4([email protected]([email protected]))