Send files directly between devices over the internet - no cloud storage, no size limits.
TypeScript cross-platformdata-transferdecentralizedfile-sharingfile-transferhole-punchingopen-sourcep2ppeer-to-peerprivacyprivacy-tools
Translations: add shared i18n infrastructure (#12)
André Sichelerobd90cb66ecb8
diff --git a/.github/workflows/checks.yml b/.github/workflows/checks.ymlindex a557067..b0f3328 100644--- a/.github/workflows/checks.yml+++ b/.github/workflows/checks.yml@@ -33,11 +33,12 @@ jobs:run: npm run knip- name: Build packages- run: npm run build --workspaces --if-present+ run: npm run build- name: Type-checkrun: |npm run typecheck -w packages/core+ npm run typecheck -w packages/localesnpm run typecheck -w packages/domainnpm run typecheck -w packages/componentsnpm run typecheck -w apps/desktopdiff --git a/apps/desktop/package.json b/apps/desktop/package.jsonindex e3f5b95..9165d99 100644--- a/apps/desktop/package.json+++ b/apps/desktop/package.json@@ -36,6 +36,7 @@"@altersend/components": "1.1.0","@altersend/core": "1.1.0","@altersend/domain": "1.1.0",+ "@altersend/locales": "1.1.0","@sentry/electron": "^7.13.0","b4a": "^1.8.0","bare-rpc": "^1.2.0",diff --git a/apps/desktop/src/renderer/components/Select.tsx b/apps/desktop/src/renderer/components/Select.tsxnew file mode 100644index 0000000..9e32570--- /dev/null+++ b/apps/desktop/src/renderer/components/Select.tsx@@ -0,0 +1,49 @@+import { ChevronDownIcon } from '@altersend/components/icons'++interface SelectOption {+ value: string+ label: string+}++interface SelectProps {+ value: string+ onChange: (value: string) => void+ options: SelectOption[]+ 'aria-label': string+ id?: string+ className?: string+}++/**+ * Styled dropdown shared across the desktop renderer (camera picker, language+ * picker, …). Wraps a native `<select>` with a chevron affordance.+ */+export function Select({+ value,+ onChange,+ options,+ id,+ className,+ 'aria-label': ariaLabel+}: SelectProps) {+ return (+ <div className={`relative${className ? ` ${className}` : ''}`}>+ <select+ id={id}+ aria-label={ariaLabel}+ className='w-full cursor-pointer appearance-none rounded-[10px] border border-border-primary bg-background-subtle py-3 pl-4 pr-10 text-[13px] text-text-primary transition-colors hover:border-border-strong focus:border-border-strong focus:outline-none'+ value={value}+ onChange={(e) => onChange(e.currentTarget.value)}+ >+ {options.map((option) => (+ <option key={option.value} value={option.value}>+ {option.label}+ </option>+ ))}+ </select>+ <span className='pointer-events-none absolute right-3 top-1/2 -translate-y-1/2 text-text-muted'>+ <ChevronDownIcon size={16} />+ </span>+ </div>+ )+}diff --git a/apps/desktop/src/renderer/lifecycle/localeStorage.ts b/apps/desktop/src/renderer/lifecycle/localeStorage.tsnew file mode 100644index 0000000..ce9437c--- /dev/null+++ b/apps/desktop/src/renderer/lifecycle/localeStorage.ts@@ -0,0 +1,17 @@+import type { LocalePreference } from '@altersend/locales'++const KEY = 'altersend.locale'++export function getSavedLocale(): LocalePreference | null {+ try {+ return window.localStorage.getItem(KEY) as LocalePreference | null+ } catch {+ return null+ }+}++export function setSavedLocale(locale: LocalePreference): void {+ try {+ window.localStorage.setItem(KEY, locale)+ } catch {}+}diff --git a/apps/desktop/src/renderer/main.tsx b/apps/desktop/src/renderer/main.tsxindex 9eeed7a..40e3d55 100644--- a/apps/desktop/src/renderer/main.tsx+++ b/apps/desktop/src/renderer/main.tsx@@ -6,11 +6,13 @@ import {startBackgroundReconnectEffect,startPeerWatchdog} from '@altersend/domain'+import { changeLocale, getInitialLocale } from '@altersend/locales'import App from './App.js'import { bridgeApi, hasBridge } from './api/bridgeApi'import { startDeepLinkHandler } from './lifecycle/deepLinkHandler'import { initSentry, captureException } from './sentry'import { isCrashReportingEnabled } from './lifecycle/crashReportingStorage'+import { getSavedLocale } from './lifecycle/localeStorage'import './strict.css'import './index.css'@@ -26,24 +28,35 @@ if (hasBridge()) {startDeepLinkHandler()}-ReactDOM.createRoot(document.getElementById('root')!).render(- <React.StrictMode>- <ThemeProvider theme={ThemeType.Dark}>- <ErrorBoundary- fallback={(error) => {- captureException(error)- return (- <CrashScreen- error={error}- onRestart={() => bridgeApi.appRestart?.()}- description='AlterSend hit an unexpected error and needs to restart. The transfer worker may be in an inconsistent state, so a restart is the safest option.'- restartLabel='Restart AlterSend'- />- )- }}- >- <App />- </ErrorBoundary>- </ThemeProvider>- </React.StrictMode>-)+async function bootstrap() {+ const savedLocale = getSavedLocale() || 'system'+ try {+ await changeLocale(getInitialLocale(savedLocale))+ } catch (err) {+ console.warn('Failed to bootstrap locale', err)+ }++ ReactDOM.createRoot(document.getElementById('root')!).render(+ <React.StrictMode>+ <ThemeProvider theme={ThemeType.Dark}>+ <ErrorBoundary+ fallback={(error) => {+ captureException(error)+ return (+ <CrashScreen+ error={error}+ onRestart={() => bridgeApi.appRestart?.()}+ description='AlterSend hit an unexpected error and needs to restart. The transfer worker may be in an inconsistent state, so a restart is the safest option.'+ restartLabel='Restart AlterSend'+ />+ )+ }}+ >+ <App />+ </ErrorBoundary>+ </ThemeProvider>+ </React.StrictMode>+ )+}++void bootstrap()diff --git a/apps/desktop/src/renderer/pages/ReceivePage/WebcamScanView.tsx b/apps/desktop/src/renderer/pages/ReceivePage/WebcamScanView.tsxindex b7827be..6bd1bda 100644--- a/apps/desktop/src/renderer/pages/ReceivePage/WebcamScanView.tsx+++ b/apps/desktop/src/renderer/pages/ReceivePage/WebcamScanView.tsx@@ -1,9 +1,9 @@import { useEffect, useRef, useState } from 'react'import QrScanner from 'qr-scanner'import { Button } from '@altersend/components'-import { ChevronDownIcon } from '@altersend/components/icons'import { extractJoinCode, joinSession } from '@altersend/domain'import { bridgeApi } from '../../api/bridgeApi'+import { Select } from '../../components/Select'interface WebcamScanViewProps {onCancel: () => void@@ -208,23 +208,12 @@ export function WebcamScanView({ onCancel }: WebcamScanViewProps) {{cameras.length > 1 ? (<div className='flex flex-col gap-1.5'><span className='text-[12px] font-medium text-text-secondary'>Camera</span>- <div className='relative'>- <select- aria-label='Camera'- className='w-full cursor-pointer appearance-none rounded-[10px] border border-border-primary bg-background-subtle py-3 pl-4 pr-10 text-[13px] text-text-primary transition-colors hover:border-border-strong focus:border-border-strong focus:outline-none'- onChange={(e) => void switchCamera(e.currentTarget.value)}- value={activeCamera ?? undefined}- >- {cameras.map((cam) => (- <option key={cam.id} value={cam.id}>- {cam.label || 'Camera'}- </option>- ))}- </select>- <span className='pointer-events-none absolute right-3 top-1/2 -translate-y-1/2 text-text-muted'>- <ChevronDownIcon size={16} />- </span>- </div>+ <Select+ aria-label='Camera'+ value={activeCamera ?? ''}+ onChange={(value) => void switchCamera(value)}+ options={cameras.map((cam) => ({ value: cam.id, label: cam.label || 'Camera' }))}+ /></div>) : null}diff --git a/apps/desktop/src/renderer/pages/SendPage/index.tsx b/apps/desktop/src/renderer/pages/SendPage/index.tsxindex 9b7958f..c2b0771 100644--- a/apps/desktop/src/renderer/pages/SendPage/index.tsx+++ b/apps/desktop/src/renderer/pages/SendPage/index.tsx@@ -7,18 +7,20 @@ import {isShareStep,useTransferStore} from '@altersend/domain'+import { useTranslation } from '@altersend/locales'import { TransferActionGroup, TransferCardFrame } from '../../components/TransferPrimitives'import { PreparingView } from './PreparingView'import { SelectFilesView } from './SelectFilesView'import { ShareView } from './ShareView'export default function SendPage() {+ const { t } = useTranslation('send')const selectedFiles = useTransferStore((s) => s.selectedFiles)const draftPhase = useTransferStore((s) => s.draftPhase)const connectionState = useTransferStore((s) => s.connectionState)const step = getSendStep({ draftPhase, isPeerConnected: connectionState === 'peer-connected' })- const copy = getSendPageCopy(step)+ const copy = getSendPageCopy(step, t)const hasSelectedFiles = selectedFiles.length > 0function renderView() {diff --git a/apps/desktop/src/renderer/pages/TransferPage/FooterBar.tsx b/apps/desktop/src/renderer/pages/TransferPage/FooterBar.tsxindex e0b4db2..5495c7a 100644--- a/apps/desktop/src/renderer/pages/TransferPage/FooterBar.tsx+++ b/apps/desktop/src/renderer/pages/TransferPage/FooterBar.tsx@@ -17,13 +17,22 @@ import {termsOfServiceUrl,websiteUrl} from '@altersend/domain'+import {+ MULTI_LANG_ENABLED,+ PICKABLE_LANGUAGES,+ useTranslation,+ changeLocale,+ type LocalePreference+} from '@altersend/locales'import logo from '../../../../../../assets/logo.png'import { bridgeApi } from '../../api/bridgeApi'+import { Select } from '../../components/Select'import { closeSentry, initSentry } from '../../sentry'import {isCrashReportingEnabled,setCrashReportingEnabled} from '../../lifecycle/crashReportingStorage'+import { setSavedLocale } from '../../lifecycle/localeStorage'const PLACEHOLDERS: Record<FeedbackType, string> = {'Bug report': 'Describe what went wrong…',@@ -45,6 +54,8 @@ export function FooterBar({ version }: { version: string }) {const [reportMessage, setReportMessage] = useState('')const [reportState, setReportState] = useState<'idle' | 'sending' | 'sent' | 'error'>('idle')const [crashReporting, setCrashReporting] = useState(isCrashReportingEnabled)+ const { i18n } = useTranslation()+ const locale = i18n.languageconst handleCrashReportingToggle = (next: boolean) => {setCrashReporting(next)@@ -142,6 +153,29 @@ export function FooterBar({ version }: { version: string }) {label='Crash reports'description='Share anonymous crash data to help improve AlterSend'/>+ {MULTI_LANG_ENABLED && (+ <div className='mt-3'>+ <label className='mb-2 block text-[13px] font-medium text-text-secondary'>+ Language+ </label>+ <Select+ aria-label='Language'+ value={locale}+ onChange={async (value) => {+ try {+ await changeLocale(value as LocalePreference)+ setSavedLocale(value as LocalePreference)+ } catch (err) {+ console.warn('Failed to change language', err)+ }+ }}+ options={PICKABLE_LANGUAGES.map((l) => ({+ value: l.code,+ label: l.label+ }))}+ />+ </div>+ )}</div><div className='border-t border-border-primary py-1'>{MENU_ITEMS.map(({ icon: Icon, label, key, ...rest }) => (diff --git a/apps/mobile/app.json b/apps/mobile/app.jsonindex f877576..3992402 100644--- a/apps/mobile/app.json+++ b/apps/mobile/app.json@@ -119,7 +119,8 @@},"androidIntentFilters": ["*/*"]}- ]+ ],+ "expo-localization"],"extra": {"eas": {diff --git a/apps/mobile/app/(tabs)/send/index.tsx b/apps/mobile/app/(tabs)/send/index.tsxindex bb232b5..c0357f7 100644--- a/apps/mobile/app/(tabs)/send/index.tsx+++ b/apps/mobile/app/(tabs)/send/index.tsx@@ -6,6 +6,7 @@ import { SelectFilesView } from '@/src/transfer/send'import { usePathname, useRouter } from 'expo-router'import { getSendPageCopy, getSendStep, isShareStep, useTransferStore } from '@altersend/domain'import { continueShare } from '@altersend/domain'+import { useTranslation } from '@altersend/locales'function NavigationController() {const router = useRouter()@@ -38,13 +39,14 @@ function NavigationController() {}export default function SendSelectScreen() {+ const { t } = useTranslation('send')const selectedFiles = useTransferStore((s) => s.selectedFiles)const draftPhase = useTransferStore((s) => s.draftPhase)const connectionState = useTransferStore((s) => s.connectionState)const router = useRouter()const step = getSendStep({ draftPhase, isPeerConnected: connectionState === 'peer-connected' })- const copy = getSendPageCopy(step)+ const copy = getSendPageCopy(step, t)const hasSelectedFiles = selectedFiles.length > 0const openMenu = useCallback(() => router.push('/settings'), [router])diff --git a/apps/mobile/app/_layout.tsx b/apps/mobile/app/_layout.tsxindex 8cf9c6d..77061d8 100644--- a/apps/mobile/app/_layout.tsx+++ b/apps/mobile/app/_layout.tsx@@ -12,8 +12,13 @@ import {startPeerWatchdog,useSimulatedLoading} from '@altersend/domain'+import { changeLocale, getInitialLocale } from '@altersend/locales'import { Stack } from 'expo-router'import { StyleSheet, View } from 'react-native'+import { useEffect, useState } from 'react'+import * as SplashScreen from 'expo-splash-screen'++SplashScreen.preventAutoHideAsync().catch(() => {})import { LoadingScreen } from '../src/loading'import { SafeAreaProvider } from 'react-native-safe-area-context'import { mobileApi } from '../src/api/mobileApi'@@ -21,6 +26,7 @@ import { ToastProvider } from '../src/components/Toast'import { UpdateBanner } from '../src/components/UpdateBanner'import { startAppStateBridge } from '../src/lifecycle/appStateBridge'import { startDeepLinkHandler } from '../src/lifecycle/deepLinkHandler'+import { getSavedLocale } from '../src/lifecycle/localeStorage'import { ShareIntentHandler } from '../src/lifecycle/ShareIntentHandler'import { startPhotosCopyEffect } from '../src/transfer/receive'import { initSentry, captureException } from '../src/sentry'@@ -60,6 +66,7 @@ function ThemedStack() {<Stack.Screen name='(tabs)' options={{ headerShown: false }} /><Stack.Screen name='onboarding' options={{ headerShown: false, gestureEnabled: false }} /><Stack.Screen name='settings' options={flowScreenOptions} />+ <Stack.Screen name='language' options={flowScreenOptions} /><Stack.Screen name='report' options={flowScreenOptions} /><Stack.Screenname='send/preparing'@@ -83,6 +90,33 @@ function ThemedStack() {}export default function RootLayout() {+ const [isReady, setIsReady] = useState(false)++ useEffect(() => {+ let isMounted = true+ async function initLocale() {+ try {+ const savedLocale = await getSavedLocale()+ if (!isMounted) return+ const preference = savedLocale || 'system'+ await changeLocale(getInitialLocale(preference))+ } catch (err) {+ console.warn(err)+ } finally {+ if (isMounted) {+ setIsReady(true)+ SplashScreen.hideAsync().catch(console.warn)+ }+ }+ }+ void initLocale()+ return () => {+ isMounted = false+ }+ }, [])++ if (!isReady) return null+return (<SafeAreaProvider><View style={styles.root}>diff --git a/apps/mobile/app/language.tsx b/apps/mobile/app/language.tsxnew file mode 100644index 0000000..c10bb14--- /dev/null+++ b/apps/mobile/app/language.tsx@@ -0,0 +1,90 @@+import { Pressable, StyleSheet, Text, View } from 'react-native'+import { useRouter } from 'expo-router'+import {+ PICKABLE_LANGUAGES,+ changeLocale,+ useTranslation,+ type LocalePreference+} from '@altersend/locales'+import { useTheme } from '@altersend/components'+import { CheckIcon } from '@altersend/components/icons'+import { Layout } from '@/src/components'+import { setSavedLocale } from '@/src/lifecycle/localeStorage'++export default function LanguageScreen() {+ const { theme } = useTheme()+ const router = useRouter()+ const { i18n } = useTranslation()+ const locale = i18n.language++ const handleSelect = async (code: string) => {+ try {+ await changeLocale(code as LocalePreference)+ void setSavedLocale(code as LocalePreference)+ router.back()+ } catch (err) {+ console.warn('Failed to change language', err)+ }+ }++ const cardStyle = {+ backgroundColor: theme.colors.colorBackgroundSubtle,+ borderColor: theme.colors.colorBorderPrimary+ }++ return (+ <Layout title='Language' description='' hasNativeHeader>+ <View style={[styles.card, cardStyle]}>+ {PICKABLE_LANGUAGES.map((language, index) => {+ const selected = language.code === locale+ return (+ <View key={language.code}>+ <Pressable+ accessibilityRole='button'+ accessibilityState={{ selected }}+ onPress={() => handleSelect(language.code)}+ style={({ pressed }) => [+ styles.row,+ pressed && { backgroundColor: theme.colors.colorSurfacePrimary }+ ]}+ >+ <Text style={[styles.label, { color: theme.colors.colorTextPrimary }]}>+ {language.label}+ </Text>+ {selected && <CheckIcon size={18} color={theme.colors.colorTextPrimary} />}+ </Pressable>+ {index < PICKABLE_LANGUAGES.length - 1 && (+ <View+ style={[styles.divider, { backgroundColor: theme.colors.colorBorderPrimary }]}+ />+ )}+ </View>+ )+ })}+ </View>+ </Layout>+ )+}++const styles = StyleSheet.create({+ card: {+ borderRadius: 16,+ borderWidth: 1,+ overflow: 'hidden'+ },+ row: {+ flexDirection: 'row',+ alignItems: 'center',+ justifyContent: 'space-between',+ paddingHorizontal: 16,+ paddingVertical: 15+ },+ label: {+ fontSize: 15,+ fontWeight: '500'+ },+ divider: {+ height: StyleSheet.hairlineWidth,+ marginLeft: 16+ }+})diff --git a/apps/mobile/app/send/preparing.tsx b/apps/mobile/app/send/preparing.tsxindex d1751a8..bbfbcf4 100644--- a/apps/mobile/app/send/preparing.tsx+++ b/apps/mobile/app/send/preparing.tsx@@ -4,16 +4,18 @@ import { useTheme } from '@altersend/components'import { ArrowLeftIcon } from '@altersend/components/icons'import { getSendPageCopy, getSendStep, isShareStep, useTransferStore } from '@altersend/domain'import { clearSenderFlow } from '@altersend/domain'+import { useTranslation } from '@altersend/locales'import { Layout } from '@/src/components'import { PreparingView } from '@/src/transfer/send'import { useNavigation, useRouter } from 'expo-router'export default function SendPreparingScreen() {+ const { t } = useTranslation('send')const { theme } = useTheme()const draftPhase = useTransferStore((s) => s.draftPhase)const connectionState = useTransferStore((s) => s.connectionState)const step = getSendStep({ draftPhase, isPeerConnected: connectionState === 'peer-connected' })- const copy = getSendPageCopy(step)+ const copy = getSendPageCopy(step, t)const navigation = useNavigation()const router = useRouter()diff --git a/apps/mobile/app/send/share.tsx b/apps/mobile/app/send/share.tsxindex 1afb311..e9f9840 100644--- a/apps/mobile/app/send/share.tsx+++ b/apps/mobile/app/send/share.tsx@@ -4,16 +4,18 @@ import { Button, useTheme } from '@altersend/components'import { ArrowLeftIcon } from '@altersend/components/icons'import { getSendPageCopy, getSendStep, useTransferStore } from '@altersend/domain'import { clearSenderFlow } from '@altersend/domain'+import { useTranslation } from '@altersend/locales'import { Layout } from '@/src/components'import { ShareView } from '@/src/transfer/send'import { useNavigation } from 'expo-router'export default function SendShareScreen() {+ const { t } = useTranslation('send')const { theme } = useTheme()const draftPhase = useTransferStore((s) => s.draftPhase)const connectionState = useTransferStore((s) => s.connectionState)const step = getSendStep({ draftPhase, isPeerConnected: connectionState === 'peer-connected' })- const copy = getSendPageCopy(step)+ const copy = getSendPageCopy(step, t)const navigation = useNavigation()const handleBack = useCallback(() => {diff --git a/apps/mobile/app/settings.tsx b/apps/mobile/app/settings.tsxindex 3c77932..d4311fa 100644--- a/apps/mobile/app/settings.tsx+++ b/apps/mobile/app/settings.tsx@@ -9,6 +9,7 @@ import {termsOfServiceUrl,websiteUrl} from '@altersend/domain'+import { MULTI_LANG_ENABLED, getLanguage, useTranslation } from '@altersend/locales'import { ToggleSwitch, useTheme } from '@altersend/components'import {AlertCircleIcon,@@ -71,6 +72,8 @@ export default function SettingsScreen() {const router = useRouter()const version = Constants.expoConfig?.version ?? '0.0.0'const [crashReporting, setCrashReporting] = useState(isCrashReportingEnabled)+ const { i18n } = useTranslation()+ const locale = i18n.languageconst handleCrashReportingToggle = (value: boolean) => {setCrashReporting(value)@@ -91,6 +94,20 @@ export default function SettingsScreen() {return (<Layout title='Settings' description='' hasNativeHeader><View style={styles.content}>+ {MULTI_LANG_ENABLED && (+ <View style={styles.section}>+ <View style={[styles.card, cardStyle]}>+ <LinkRow+ label='Language'+ hint={getLanguage(locale)?.label ?? locale}+ icon={<GlobeIcon size={16} color={theme.colors.colorTextSecondary} />}+ onPress={() => router.push('/language')}+ isLast+ />+ </View>+ </View>+ )}+<View style={styles.section}><Text style={[styles.sectionTitle, { color: theme.colors.colorTextMuted }]}>Privacy</Text><View style={[styles.card, styles.toggleCardPad, cardStyle]}>diff --git a/apps/mobile/package.json b/apps/mobile/package.jsonindex d3a9037..b10b183 100644--- a/apps/mobile/package.json+++ b/apps/mobile/package.json@@ -8,7 +8,7 @@"prestart": "npm run bundle-bare","start": "expo start --dev-client","postinstall": "npm run barekit:link-ios-addons && npm run barekit:link-android-addons",- "eas-build-post-install": "cd ../.. && npm run build -w packages/core && npm run build -w packages/domain && npm run build -w packages/components && npm run bundle-bare -w apps/mobile",+ "eas-build-post-install": "cd ../.. && npm run build -w packages/core && npm run build -w packages/locales && npm run build -w packages/domain && npm run build -w packages/components && npm run bundle-bare -w apps/mobile","barekit:link-ios-addons": "node ./scripts/link-ios-addons.cjs","barekit:link-android-addons": "node ./scripts/link-android-addons.cjs","pods:install": "cd ios && LANG=en_US.UTF-8 pod install",@@ -37,6 +37,7 @@"@altersend/components": "1.1.0","@altersend/core": "1.1.0","@altersend/domain": "1.1.0",+ "@altersend/locales": "1.1.0","@expo/vector-icons": "^15.0.2","@sentry/react-native": "^8.11.0","b4a": "^1.6.7",@@ -51,10 +52,12 @@"expo-haptics": "~15.0.7","expo-image-picker": "~55.0.18","expo-linking": "~55.0.13",+ "expo-localization": "~55.0.15","expo-media-library": "~55.0.15","expo-router": "~55.0.5","expo-share-intent": "^6.1.0","expo-sharing": "~55.0.18",+ "expo-splash-screen": "~55.0.21","expo-system-ui": "~55.0.9","lucide-react-native": "^1.8.0","react": "19.2.0",diff --git a/apps/mobile/src/lifecycle/localeStorage.ts b/apps/mobile/src/lifecycle/localeStorage.tsnew file mode 100644index 0000000..43b18f4--- /dev/null+++ b/apps/mobile/src/lifecycle/localeStorage.ts@@ -0,0 +1,35 @@+import { Directory, File, Paths } from 'expo-file-system'+import type { LocalePreference } from '@altersend/locales'++const DIRNAME = 'altersend'+const FILENAME = 'locale.txt'++function getLocaleFile(): File | null {+ const documentDirectory = Paths.document+ if (!documentDirectory?.uri) return null+ return new File(new Directory(documentDirectory, DIRNAME), FILENAME)+}++export async function getSavedLocale(): Promise<LocalePreference | null> {+ try {+ const file = getLocaleFile()+ if (!file?.exists) return null+ const content = await file.text()+ return (content.trim() || null) as LocalePreference | null+ } catch {+ return null+ }+}++export async function setSavedLocale(locale: LocalePreference): Promise<void> {+ try {+ const documentDirectory = Paths.document+ if (!documentDirectory?.uri) return+ const dir = new Directory(documentDirectory, DIRNAME)+ if (!dir.exists) dir.create({ idempotent: true, intermediates: true })+ const file = new File(dir, FILENAME)+ file.write(locale)+ } catch (err) {+ console.warn('localeStorage: setSavedLocale failed', err)+ }+}diff --git a/docs/architecture.md b/docs/architecture.mdindex 75f7d2e..e9c0ed5 100644--- a/docs/architecture.md+++ b/docs/architecture.md@@ -49,6 +49,7 @@ packages/The protocol layer. Runs entirely inside a **Bare worklet** — a lightweight JS runtime (Bare) spawned by the host app. This isolates P2P networking from Electron / React Native.Key modules:+- `worklet/index.ts` — entrypoint; wires Bare IPC → RPC server → orchestrator- `worklet/transfer/orchestrator.ts` — top-level coordinator; owns session lifecycle + state and composes the three subsystems below- `worklet/transfer/swarm.ts` — `TransferSwarm`: Hyperswarm peer connectivity, Corestore replication, and per-peer control channels@@ -63,6 +64,7 @@ Key modules:State and business logic, shared across desktop and mobile.Key modules:+- `transfer/store.ts` — Zustand store- `transfer/reducer.ts` — pure reducer (all state transitions)- `transfer/binding.ts` — `bindTransferApi()` wires the store to the core worklet@@ -72,6 +74,10 @@ Key modules:Shared React components using **React Strict DOM** (works on both web and native) and Tailwind for styling. Built with Storybook for visual development.+### `packages/locales`++Shared multi-language (i18n) setup, consumed by both apps. Translations are JSON split by context (`common`, `send`, …) under `src/locales/<code>/`, with vanilla **i18next** initialized via **react-i18next** bindings; formatting leans on the platform `Intl` APIs. Each language declares a `productionReady` flag in its `meta.json`, and only ready languages are offered (`PICKABLE_LANGUAGES`); `resolveSupportedLocale()` normalizes any system/persisted BCP-47 tag down to a ready code. Locale preference lives in a small settings store in `packages/domain`; persistence is app-side (`localStorage` on desktop, a file on mobile). The picker UI is gated behind the `MULTI_LANG_ENABLED` release flag (currently `false`) so the app ships single-language until translations land. See `packages/locales/README.md` for the add-a-language guide.+## Transfer flow1. **Sender** enters the share screen → the core worklet generates a fresh, single-use swarm topic: a random 32-byte key, hex-encoded to a 64-char join code. Domain wraps it for display (QR / `com.altersend.mobile://join/<topic>` URL).diff --git a/knip.json b/knip.jsonindex 9801442..9d53b9d 100644--- a/knip.json+++ b/knip.json@@ -17,6 +17,9 @@"packages/domain": {"entry": ["src/**/*.test.ts"]},+ "packages/locales": {+ "entry": ["src/**/*.test.ts"]+ },"packages/components": {"entry": ["src/index.ts",diff --git a/package-lock.json b/package-lock.jsonindex 6798823..1e171bc 100644--- a/package-lock.json+++ b/package-lock.json@@ -37,6 +37,7 @@"@altersend/components": "1.1.0","@altersend/core": "1.1.0","@altersend/domain": "1.1.0",+ "@altersend/locales": "1.1.0","@sentry/electron": "^7.13.0","b4a": "^1.8.0","bare-rpc": "^1.2.0",@@ -109,6 +110,7 @@"@altersend/components": "1.1.0","@altersend/core": "1.1.0","@altersend/domain": "1.1.0",+ "@altersend/locales": "1.1.0","@expo/vector-icons": "^15.0.2","@sentry/react-native": "^8.11.0","b4a": "^1.6.7",@@ -123,10 +125,12 @@"expo-haptics": "~15.0.7","expo-image-picker": "~55.0.18","expo-linking": "~55.0.13",+ "expo-localization": "~55.0.15","expo-media-library": "~55.0.15","expo-router": "~55.0.5","expo-share-intent": "^6.1.0","expo-sharing": "~55.0.18",+ "expo-splash-screen": "~55.0.21","expo-system-ui": "~55.0.9","lucide-react-native": "^1.8.0","react": "19.2.0",@@ -147,6 +151,31 @@"typescript": "^5.3.3"}},+ "apps/mobile/node_modules/expo-localization": {+ "version": "55.0.15",+ "resolved": "https://registry.npmjs.org/expo-localization/-/expo-localization-55.0.15.tgz",+ "integrity": "sha512-+HD55LeeIWyVRLvpQ909Am89XS16dUBkbB4/ruCJXS9oWv1K8W+FoXuOPTpmdvwHfC9cxt0loiwPWUiw2fdgbg==",+ "license": "MIT",+ "dependencies": {+ "rtl-detect": "^1.0.2"+ },+ "peerDependencies": {+ "expo": "*",+ "react": "*"+ }+ },+ "apps/mobile/node_modules/expo-splash-screen": {+ "version": "55.0.21",+ "resolved": "https://registry.npmjs.org/expo-splash-screen/-/expo-splash-screen-55.0.21.tgz",+ "integrity": "sha512-hFGEap69ggCckbHIdDXMe5rqfBR9TwcnY5gBhyaACUxU64w827T6prOQcIvLmAdv00kp3Gqt7hgE+mNn37EF+A==",+ "license": "MIT",+ "dependencies": {+ "@expo/prebuild-config": "^55.0.18"+ },+ "peerDependencies": {+ "expo": "*"+ }+ },"node_modules/@adobe/css-tools": {"version": "4.4.4","resolved": "https://registry.npmjs.org/@adobe/css-tools/-/css-tools-4.4.4.tgz",@@ -170,6 +199,10 @@"resolved": "packages/domain","link": true},+ "node_modules/@altersend/locales": {+ "resolved": "packages/locales",+ "link": true+ },"node_modules/@altersend/mobile": {"resolved": "apps/mobile","link": true@@ -3881,12 +3914,12 @@"license": "MIT"},"node_modules/@expo/spawn-async": {- "version": "1.7.2",- "resolved": "https://registry.npmjs.org/@expo/spawn-async/-/spawn-async-1.7.2.tgz",- "integrity": "sha512-QdWi16+CHB9JYP7gma19OVVg0BFkvU8zNj9GjWorYI8Iv8FUxjOCcYRuAmX4s/h91e4e7BPsskc8cSrZYho9Ew==",+ "version": "1.8.0",+ "resolved": "https://registry.npmjs.org/@expo/spawn-async/-/spawn-async-1.8.0.tgz",+ "integrity": "sha512-eb9xxd/LbuEGSdua4NumCu/McVB9EM+F/JxB9pWgnERw4HQ9XyTNH1KapG6oqLWR8TuRK2LQfzJlmNi94CVobw==","license": "MIT","dependencies": {- "cross-spawn": "^7.0.3"+ "cross-spawn": "^7.0.6"},"engines": {"node": ">=12"@@ -16794,6 +16827,15 @@"dev": true,"license": "ISC"},+ "node_modules/html-parse-stringify": {+ "version": "3.0.1",+ "resolved": "https://registry.npmjs.org/html-parse-stringify/-/html-parse-stringify-3.0.1.tgz",+ "integrity": "sha512-KknJ50kTInJ7qIScF3jeaFRpMpE8/lfiTdzf/twXyPBLAGrLRTmkz3AdTnKeh40X8k9L2fdYwEp/42WGXIRGcg==",+ "license": "MIT",+ "dependencies": {+ "void-elements": "3.1.0"+ }+ },"node_modules/http-cache-semantics": {"version": "4.2.0","resolved": "https://registry.npmjs.org/http-cache-semantics/-/http-cache-semantics-4.2.0.tgz",@@ -17163,6 +17205,34 @@"unslab": "^1.3.0"}},+ "node_modules/i18next": {+ "version": "26.3.0",+ "resolved": "https://registry.npmjs.org/i18next/-/i18next-26.3.0.tgz",+ "integrity": "sha512-gHSgGpUXVmuqE2El1W61DmxeyeTlFfZgdJRWMo9jScAn5pu7TuTuiccb1zh3E2J9hEBVGJ23+96x0ieBhfuIHA==",+ "funding": [+ {+ "type": "individual",+ "url": "https://www.locize.com/i18next"+ },+ {+ "type": "individual",+ "url": "https://www.i18next.com/how-to/faq#i18next-is-awesome.-how-can-i-support-the-project"+ },+ {+ "type": "individual",+ "url": "https://www.locize.com"+ }+ ],+ "license": "MIT",+ "peerDependencies": {+ "typescript": "^5 || ^6"+ },+ "peerDependenciesMeta": {+ "typescript": {+ "optional": true+ }+ }+ },"node_modules/iconv-corefoundation": {"version": "1.1.7","resolved": "https://registry.npmjs.org/iconv-corefoundation/-/iconv-corefoundation-1.1.7.tgz",@@ -22608,6 +22678,33 @@"react": ">=17.0.0"}},+ "node_modules/react-i18next": {+ "version": "17.0.8",+ "resolved": "https://registry.npmjs.org/react-i18next/-/react-i18next-17.0.8.tgz",+ "integrity": "sha512-0ooKbGLU8JXhe1zwpQUWIeXSgLPOfwJmgheWRIUpcoA0CpyabpGhayjdG+/eA5esC1AQ8h2jWpXjJfzQzeDOCw==",+ "license": "MIT",+ "dependencies": {+ "@babel/runtime": "^7.29.2",+ "html-parse-stringify": "^3.0.1",+ "use-sync-external-store": "^1.6.0"+ },+ "peerDependencies": {+ "i18next": ">= 26.2.0",+ "react": ">= 16.8.0",+ "typescript": "^5 || ^6"+ },+ "peerDependenciesMeta": {+ "react-dom": {+ "optional": true+ },+ "react-native": {+ "optional": true+ },+ "typescript": {+ "optional": true+ }+ }+ },"node_modules/react-is": {"version": "19.2.6","resolved": "https://registry.npmjs.org/react-is/-/react-is-19.2.6.tgz",@@ -23676,6 +23773,12 @@"dev": true,"license": "MIT"},+ "node_modules/rtl-detect": {+ "version": "1.1.2",+ "resolved": "https://registry.npmjs.org/rtl-detect/-/rtl-detect-1.1.2.tgz",+ "integrity": "sha512-PGMBq03+TTG/p/cRB7HCLKJ1MgDIi07+QU1faSjiYRfmY5UsAttV9Hs08jDAHVwcOwmVLcSJkpwyfXszVjWfIQ==",+ "license": "BSD-3-Clause"+ },"node_modules/run-applescript": {"version": "7.1.0","resolved": "https://registry.npmjs.org/run-applescript/-/run-applescript-7.1.0.tgz",@@ -26389,6 +26492,15 @@"integrity": "sha512-gQpnTgkubC6hQgdIcRdYGDSDc+SaujOdyesZQMv6JlfQee/9Mp0Qhnys6WxDWvQnL5WZdT7o2Ul187aSt0Rq+w==","license": "MIT"},+ "node_modules/void-elements": {+ "version": "3.1.0",+ "resolved": "https://registry.npmjs.org/void-elements/-/void-elements-3.1.0.tgz",+ "integrity": "sha512-Dhxzh5HZuiHQhbvTW9AMetFfBHDMYpo23Uo9btPXgdYP+3T5S+p+jgNy7spra+veYhBP2dCSgxR/i2Y02h5/6w==",+ "license": "MIT",+ "engines": {+ "node": ">=0.10.0"+ }+ },"node_modules/walk-up-path": {"version": "4.0.0","resolved": "https://registry.npmjs.org/walk-up-path/-/walk-up-path-4.0.0.tgz",@@ -27166,10 +27278,12 @@"version": "1.1.0","license": "Apache-2.0","dependencies": {- "@altersend/core": "1.1.0"+ "@altersend/core": "1.1.0",+ "@altersend/locales": "1.1.0"},"devDependencies": {"@types/react": "^19.0.0",+ "i18next": "^26.2.0","react": "19.2.0","typescript": "^5.9.3","vitest": "^4.1.8",@@ -27179,6 +27293,24 @@"react": "^19.0.0","zustand": "^5.0.12"}+ },+ "packages/locales": {+ "name": "@altersend/locales",+ "version": "1.1.0",+ "license": "Apache-2.0",+ "dependencies": {+ "i18next": "^26.2.0",+ "react-i18next": "^17.0.8"+ },+ "devDependencies": {+ "@types/react": "^19.0.0",+ "react": "19.2.0",+ "typescript": "^5.9.3",+ "vitest": "^4.1.8"+ },+ "peerDependencies": {+ "react": "^19.0.0"+ }}}}diff --git a/package.json b/package.jsonindex bc249b8..c705b99 100644--- a/package.json+++ b/package.json@@ -8,19 +8,19 @@],"scripts": {"dev": "npm run desktop:dev",- "mobile": "npm run build -w packages/core && npm run build -w packages/domain && npm run build -w packages/components && npm run ios -w apps/mobile",+ "mobile": "npm run build -w packages/core && npm run build -w packages/locales && npm run build -w packages/domain && npm run build -w packages/components && npm run ios -w apps/mobile","mobile:setup": "npm run build -w packages/core && npm run setup:ios -w apps/mobile","mobile:start": "npm start -w apps/mobile",- "desktop:dev": "npm run build -w packages/core && npm run build -w packages/domain && npm run build -w packages/components && npm start -w apps/desktop",- "desktop:dev:peer2": "npm run build -w packages/core && npm run build -w packages/domain && npm run build -w packages/components && npm run start:peer2 -w apps/desktop",- "desktop:dev:peer3": "npm run build -w packages/core && npm run build -w packages/domain && npm run build -w packages/components && npm run start:peer3 -w apps/desktop",- "desktop:build": "npm run build -w packages/core && npm run build -w packages/domain && npm run build -w packages/components && npm run build -w apps/desktop",+ "desktop:dev": "npm run build -w packages/core && npm run build -w packages/locales && npm run build -w packages/domain && npm run build -w packages/components && npm start -w apps/desktop",+ "desktop:dev:peer2": "npm run build -w packages/core && npm run build -w packages/locales && npm run build -w packages/domain && npm run build -w packages/components && npm run start:peer2 -w apps/desktop",+ "desktop:dev:peer3": "npm run build -w packages/core && npm run build -w packages/locales && npm run build -w packages/domain && npm run build -w packages/components && npm run start:peer3 -w apps/desktop",+ "desktop:build": "npm run build -w packages/core && npm run build -w packages/locales && npm run build -w packages/domain && npm run build -w packages/components && npm run build -w apps/desktop","components:build": "npm run build -w packages/components","domain:build": "npm run build -w packages/domain","components:typecheck": "npm run typecheck -w packages/components","components:storybook": "npm run storybook -w packages/components","components:build-storybook": "npm run build-storybook -w packages/components",- "build": "npm run build --workspaces --if-present",+ "build": "npm run build -w packages/core && npm run build -w packages/locales && npm run build -w packages/domain && npm run build -w packages/components && npm run build --if-present -w apps/desktop","test": "npm test --workspaces --if-present","lint": "eslint apps packages --max-warnings=0","format": "prettier --write \"apps/**/*.{ts,tsx,js,jsx,json,md,yml,yaml}\" \"packages/**/*.{ts,tsx,js,jsx,json,md,yml,yaml}\"",diff --git a/packages/domain/package.json b/packages/domain/package.jsonindex 8239069..27535b4 100644--- a/packages/domain/package.json+++ b/packages/domain/package.json@@ -33,6 +33,7 @@},"devDependencies": {"@types/react": "^19.0.0",+ "i18next": "^26.2.0","react": "19.2.0","typescript": "^5.9.3","vitest": "^4.1.8",diff --git a/packages/domain/src/index.ts b/packages/domain/src/index.tsindex 204a118..858225c 100644--- a/packages/domain/src/index.ts+++ b/packages/domain/src/index.ts@@ -11,5 +11,6 @@ export * from './receive/pageUi'export * from './receive/joinCode'export * from './receive/downloadModel'export * from './transfer'+export * from './onboarding'export * from './useSimulatedLoading'diff --git a/packages/domain/src/send/pageUi.ts b/packages/domain/src/send/pageUi.tsindex 08affc3..07e6224 100644--- a/packages/domain/src/send/pageUi.ts+++ b/packages/domain/src/send/pageUi.ts@@ -11,25 +11,25 @@ export interface SendShareStatus {label: stringtone: 'muted' | 'success'}+import type { TFunction } from 'i18next'-export function getSendPageCopy(step: SendStep): SendPageCopy {+export function getSendPageCopy(step: SendStep, t: TFunction<'send'>): SendPageCopy {switch (step) {case 'selecting':return {- title: 'Send files',- description:- 'Choose one or more files and generate a one-time code for a direct encrypted transfer.'+ title: t('steps.selecting.title'),+ description: t('steps.selecting.description')}case 'preparing':return {- title: 'Preparing transfer',- description: 'Preparing the selected files before the share code is revealed.'+ title: t('steps.preparing.title'),+ description: t('steps.preparing.description')}case 'waiting_for_receiver':case 'receiver_connected':return {- title: 'Share the code',- description: 'Send the code or QR to your recipient to start the transfer.'+ title: t('steps.waiting_for_receiver.title'),+ description: t('steps.waiting_for_receiver.description')}default: {const exhaustiveCheck: never = step@@ -38,19 +38,19 @@ export function getSendPageCopy(step: SendStep): SendPageCopy {}}-export function getSendShareStatus(step: SendStep): SendShareStatus | null {+export function getSendShareStatus(step: SendStep, t: TFunction<'send'>): SendShareStatus | null {switch (step) {case 'selecting':case 'preparing':return nullcase 'waiting_for_receiver':return {- label: 'Waiting for peer',+ label: t('status.waiting_for_peer'),tone: 'muted'}case 'receiver_connected':return {- label: 'Peer connected',+ label: t('status.peer_connected'),tone: 'success'}default: {diff --git a/packages/locales/README.md b/packages/locales/README.mdnew file mode 100644index 0000000..b60789d--- /dev/null+++ b/packages/locales/README.md@@ -0,0 +1,67 @@+# @altersend/locales++This package centralizes the internationalization (i18n) infrastructure for the AlterSend application, allowing translations to be shared seamlessly between the React Native (mobile) and Electron (desktop) clients.++## Architecture Guidelines++To maintain a clean separation of concerns and avoid unnecessary dependencies, this package adheres to the following principles:++1. **Shared JSON Dictionaries**: All language strings are stored as JSON files split by context/feature (e.g., `common`, `send`, `receive`). These are located in `src/locales/<code>/`.+2. **Framework-Agnostic Core**: Initialization uses vanilla `i18next` (`src/config.ts`).+3. **Thin React Bindings**: We re-export `useTranslation` from `react-i18next` — the standard, concurrent-safe React binding — rather than maintaining a bespoke hook.+4. **Lean on Intl**: For formatting numbers, dates, and file sizes, we lean on the platform's built-in `Intl` APIs rather than pulling in large formatting libraries (like moment or date-fns).++## Production-ready gating++Each language ships a `src/locales/<code>/meta.json`:++```json+{ "label": "English", "productionReady": true, "dir": "ltr" }+```++`src/languages.ts` aggregates these into a registry. Only **production-ready** languages are surfaced to users:++- `LANGUAGES` — every registered language (ready or not).+- `PICKABLE_LANGUAGES` — production-ready only; this is what the Settings picker renders.++This is how the app stays English-only while the full pipeline is wired: `en` is ready, everything else (`pt-BR`, future RTL languages, …) stays hidden until its `productionReady` flag is flipped. `resolveSupportedLocale()` also resolves only to pickable languages, so system detection or a stale persisted value can never land on a not-yet-ready locale.++## Usage++### In components (reactive)++Scope the hook to the namespace you need; keys are then checked at compile time:++```tsx+import { useTranslation } from '@altersend/locales'++function SendHeader() {+ const { t } = useTranslation('send')+ // `t('steps.nope')` would be a TypeScript error.+ return <h1>{t('steps.selecting.title')}</h1>+}+```++### Outside React++Use the initialized instance directly. Namespaced keys use the `ns:key` form:++```ts+import { i18nextInstance } from '@altersend/locales'++i18nextInstance.t('buttons.cancel') // default `common` namespace+i18nextInstance.t('send:steps.selecting.title') // explicit namespace+```++### Switching language++Locale state lives in the domain settings store (`@altersend/domain`), not here. Call `changeLocale(code)` from the domain package — it normalizes the input, updates the store, and calls `i18next.changeLanguage`.++## Adding a new language++To add a language (e.g., Brazilian Portuguese — `pt-BR`):++1. Create `src/locales/pt-BR/` with a `meta.json` (`productionReady: false` until complete) and a translated copy of each namespace file (`common.json`, `send.json`, …).+2. Register it in the `REGISTRY` in `src/languages.ts` and add its resources to `src/config.ts`.+3. Translate and review the strings.+4. Flip `productionReady` to `true` in its `meta.json` — it now appears in the picker.diff --git a/packages/locales/package.json b/packages/locales/package.jsonnew file mode 100644index 0000000..c2d520d--- /dev/null+++ b/packages/locales/package.json@@ -0,0 +1,40 @@+{+ "name": "@altersend/locales",+ "version": "1.1.0",+ "type": "module",+ "main": "./dist/index.js",+ "types": "./dist/index.d.ts",+ "exports": {+ ".": {+ "types": "./dist/index.d.ts",+ "default": "./dist/index.js"+ }+ },+ "private": true,+ "license": "Apache-2.0",+ "author": "AlterSend",+ "repository": {+ "type": "git",+ "url": "git+https://github.com/denislupookov/altersend.git"+ },+ "scripts": {+ "typecheck": "tsc --noEmit",+ "build": "tsc",+ "clean": "rm -rf dist",+ "test": "vitest run",+ "test:watch": "vitest"+ },+ "dependencies": {+ "i18next": "^26.2.0",+ "react-i18next": "^17.0.8"+ },+ "peerDependencies": {+ "react": "^19.0.0"+ },+ "devDependencies": {+ "@types/react": "^19.0.0",+ "react": "19.2.0",+ "typescript": "^5.9.3",+ "vitest": "^4.1.8"+ }+}diff --git a/packages/locales/src/config.ts b/packages/locales/src/config.tsnew file mode 100644index 0000000..c6ecee6--- /dev/null+++ b/packages/locales/src/config.ts@@ -0,0 +1,32 @@+import i18next from 'i18next'+import { initReactI18next } from 'react-i18next'+import common from './locales/en-US/common.json'+import send from './locales/en-US/send.json'+import { getInitialLocale } from './utils'++const resources = {+ 'en-US': {+ common,+ send+ }+}++// Resources are bundled (no async backend), so v26 initializes synchronously.+// `useSuspense: false` keeps React Native from suspending on a translation read;+// react-i18next re-renders consumers once initialization settles regardless.+void i18next+ .use(initReactI18next)+ .init({+ resources,+ lng: getInitialLocale(),+ fallbackLng: 'en-US',+ ns: ['common', 'send'],+ defaultNS: 'common',+ interpolation: { escapeValue: false },+ react: { useSuspense: false }+ })+ .catch((error) => {+ console.error('i18next initialization failed', error)+ })++export default i18nextdiff --git a/packages/locales/src/i18n-augmentation.ts b/packages/locales/src/i18n-augmentation.tsnew file mode 100644index 0000000..65f00d3--- /dev/null+++ b/packages/locales/src/i18n-augmentation.ts@@ -0,0 +1,24 @@+import common from './locales/en-US/common.json'+import send from './locales/en-US/send.json'++/**+ * Shape of the bundled English resources, used as the source of truth for+ * compile-time key checking of `t(...)`.+ *+ * This lives in a real `.ts` module (not an ambient `.d.ts`) and is re-exported+ * from `index.ts` so the `declare module` augmentation below is emitted to+ * `dist` and actually reaches consumers (`domain`, the apps). An input `.d.ts`+ * is not copied to `dist` by `tsc`, so the augmentation would otherwise apply+ * only inside this package and silently provide no safety downstream.+ */+export interface Resources {+ common: typeof common+ send: typeof send+}++declare module 'i18next' {+ interface CustomTypeOptions {+ defaultNS: 'common'+ resources: Resources+ }+}diff --git a/packages/locales/src/index.ts b/packages/locales/src/index.tsnew file mode 100644index 0000000..023f137--- /dev/null+++ b/packages/locales/src/index.ts@@ -0,0 +1,7 @@+export { default as i18nextInstance } from './config'+export { useTranslation } from 'react-i18next'+export * from './languages'+export * from './utils'+// Re-exported so the `declare module 'i18next'` augmentation in this module is+// emitted to `dist` and applied in consuming packages (typed `t` keys).+export type { Resources } from './i18n-augmentation'diff --git a/packages/locales/src/languages.test.ts b/packages/locales/src/languages.test.tsnew file mode 100644index 0000000..368a20f--- /dev/null+++ b/packages/locales/src/languages.test.ts@@ -0,0 +1,28 @@+import { describe, expect, it } from 'vitest'+import { LANGUAGES, PICKABLE_LANGUAGES, getLanguage, isPickable, isRTL } from './languages'++describe('language registry', () => {+ it('registers English and Brazilian Portuguese', () => {+ expect(LANGUAGES.map((l) => l.code).sort()).toEqual(['en-US', 'pt-BR'])+ })++ it('only offers production-ready languages in the picker', () => {+ expect(PICKABLE_LANGUAGES.map((l) => l.code)).toEqual(['en-US'])+ expect(isPickable('en-US')).toBe(true)+ // pt-BR is registered but not production-ready yet → hidden from the picker.+ expect(isPickable('pt-BR')).toBe(false)+ })++ it('exposes label and direction metadata', () => {+ expect(getLanguage('en-US')).toMatchObject({ label: 'English', dir: 'ltr' })+ expect(getLanguage('pt-BR')).toMatchObject({ dir: 'ltr', productionReady: false })+ expect(getLanguage('xx')).toBeUndefined()+ })++ it('derives RTL from registry metadata', () => {+ expect(isRTL('en-US')).toBe(false)+ expect(isRTL('pt-BR')).toBe(false)+ // Unregistered tags are treated as LTR (they are never selectable anyway).+ expect(isRTL('ar')).toBe(false)+ })+})diff --git a/packages/locales/src/languages.ts b/packages/locales/src/languages.tsnew file mode 100644index 0000000..935adb6--- /dev/null+++ b/packages/locales/src/languages.ts@@ -0,0 +1,81 @@+import enMeta from './locales/en-US/meta.json'+import ptBrMeta from './locales/pt-BR/meta.json'++export type TextDirection = 'ltr' | 'rtl'++export interface LanguageMeta {+ /** Native display name shown in the language picker. */+ label: string+ /**+ * Whether the language is complete enough to be offered to users. Only+ * production-ready languages appear in the picker; everything else (partial+ * translations, untested RTL layouts, …) stays hidden until promoted.+ */+ productionReady: boolean+ /** Writing direction. RTL languages stay hidden until layout support lands. */+ dir: TextDirection+}++export interface Language extends LanguageMeta {+ code: string+}++/**+ * Registry of every known language, keyed by BCP-47 code, including ones that+ * are not yet production-ready. Each entry's metadata lives next to its+ * translations in `locales/<code>/meta.json` so adding a language is a single+ * self-contained folder.+ */+const REGISTRY = {+ 'en-US': enMeta,+ 'pt-BR': ptBrMeta+}++export type SupportedLanguageCode = keyof typeof REGISTRY++export type LocalePreference = 'system' | SupportedLanguageCode++export const DEFAULT_LANGUAGE = 'en-US'++/**+ * Release gate for the language-picker UI. While `false`, the in-app language+ * selection is hidden (desktop Settings + mobile Settings) so the app stays+ * single-language until translations ship; the i18n infrastructure stays wired+ * underneath. Flip to `true` to expose the picker.+ */+export const MULTI_LANG_ENABLED = false++// `dir` widens to `string` when imported from JSON, so it is narrowed here.+function toLanguage(+ code: string,+ meta: { label: string; productionReady: boolean; dir: string }+): Language {+ return {+ code,+ label: meta.label,+ productionReady: meta.productionReady,+ dir: meta.dir === 'rtl' ? 'rtl' : 'ltr'+ }+}++/** All registered languages (ready or not). */+export const LANGUAGES: Language[] = Object.entries(REGISTRY).map(([code, meta]) =>+ toLanguage(code, meta)+)++/** Languages offered in the picker — production-ready only. */+export const PICKABLE_LANGUAGES: Language[] = LANGUAGES.filter((l) => l.productionReady)++export function getLanguage(code: string): Language | undefined {+ return LANGUAGES.find((l) => l.code === code)+}++/** Whether `code` is registered and production-ready (i.e. user-selectable). */+export function isPickable(code: string): boolean {+ return PICKABLE_LANGUAGES.some((l) => l.code === code)+}++/** Right-to-left check driven by the registry (single source of truth). */+export function isRTL(code: string): boolean {+ return getLanguage(code)?.dir === 'rtl'+}diff --git a/packages/locales/src/locales/en-US/common.json b/packages/locales/src/locales/en-US/common.jsonnew file mode 100644index 0000000..c0c69bb--- /dev/null+++ b/packages/locales/src/locales/en-US/common.json@@ -0,0 +1,7 @@+{+ "buttons": {+ "back": "Back",+ "confirm": "Confirm",+ "cancel": "Cancel"+ }+}diff --git a/packages/locales/src/locales/en-US/meta.json b/packages/locales/src/locales/en-US/meta.jsonnew file mode 100644index 0000000..2affd61--- /dev/null+++ b/packages/locales/src/locales/en-US/meta.json@@ -0,0 +1,5 @@+{+ "label": "English",+ "productionReady": true,+ "dir": "ltr"+}diff --git a/packages/locales/src/locales/en-US/send.json b/packages/locales/src/locales/en-US/send.jsonnew file mode 100644index 0000000..7e42a58--- /dev/null+++ b/packages/locales/src/locales/en-US/send.json@@ -0,0 +1,24 @@+{+ "steps": {+ "selecting": {+ "title": "Send files",+ "description": "Choose one or more files and generate a one-time code for a direct encrypted transfer."+ },+ "preparing": {+ "title": "Preparing transfer",+ "description": "Preparing the selected files before the share code is revealed."+ },+ "waiting_for_receiver": {+ "title": "Share the code",+ "description": "Send the code or QR to your recipient to start the transfer."+ },+ "receiver_connected": {+ "title": "Share the code",+ "description": "Send the code or QR to your recipient to start the transfer."+ }+ },+ "status": {+ "waiting_for_peer": "Waiting for peer",+ "peer_connected": "Peer connected"+ }+}diff --git a/packages/locales/src/locales/pt-BR/meta.json b/packages/locales/src/locales/pt-BR/meta.jsonnew file mode 100644index 0000000..6261019--- /dev/null+++ b/packages/locales/src/locales/pt-BR/meta.json@@ -0,0 +1,5 @@+{+ "label": "Português (BR)",+ "productionReady": false,+ "dir": "ltr"+}diff --git a/packages/locales/src/utils.test.ts b/packages/locales/src/utils.test.tsnew file mode 100644index 0000000..6730da6--- /dev/null+++ b/packages/locales/src/utils.test.ts@@ -0,0 +1,38 @@+import { describe, expect, it } from 'vitest'+import { PICKABLE_LANGUAGES } from './languages'+import { getInitialLocale, resolveSupportedLocale } from './utils'++describe('resolveSupportedLocale', () => {+ it('returns an exact production-ready match', () => {+ expect(resolveSupportedLocale('en-US')).toBe('en-US')+ })++ it('matches case-insensitively', () => {+ expect(resolveSupportedLocale('EN-US')).toBe('en-US')+ })++ it('matches a regional tag by its primary subtag', () => {+ expect(resolveSupportedLocale('en')).toBe('en-US')+ expect(resolveSupportedLocale('en-GB')).toBe('en-US')+ })++ it('falls back to English for not-yet-ready languages', () => {+ // pt-BR is registered but not production-ready, so it must not be selected.+ expect(resolveSupportedLocale('pt-BR')).toBe('en-US')+ expect(resolveSupportedLocale('pt-PT')).toBe('en-US')+ })++ it('falls back to English for unsupported or empty input', () => {+ expect(resolveSupportedLocale('de-DE')).toBe('en-US')+ expect(resolveSupportedLocale('')).toBe('en-US')+ expect(resolveSupportedLocale(null)).toBe('en-US')+ expect(resolveSupportedLocale(undefined)).toBe('en-US')+ })+})++describe('getInitialLocale', () => {+ it('always resolves to a production-ready locale', () => {+ const codes = PICKABLE_LANGUAGES.map((l) => l.code)+ expect(codes).toContain(getInitialLocale())+ })+})diff --git a/packages/locales/src/utils.ts b/packages/locales/src/utils.tsnew file mode 100644index 0000000..87f3746--- /dev/null+++ b/packages/locales/src/utils.ts@@ -0,0 +1,65 @@+import { DEFAULT_LANGUAGE, PICKABLE_LANGUAGES, type LocalePreference } from './languages'++/**+ * Best-effort detection of the user's preferred UI language as a raw BCP-47+ * tag. Prefers `navigator.languages` (the ordered UI-language preference on+ * web/Electron) and falls back to the `Intl` resolved locale (a regional+ * formatting locale, and unreliable on Hermes — mobile passes the device tag+ * from `expo-localization` to {@link resolveSupportedLocale} instead).+ */+function getSystemPreferredLocale(): string {+ if (typeof navigator !== 'undefined') {+ const fromNavigator = navigator.languages?.[0] ?? navigator.language+ if (fromNavigator) return fromNavigator+ }+ if (typeof Intl !== 'undefined' && typeof Intl.DateTimeFormat === 'function') {+ const resolved = Intl.DateTimeFormat().resolvedOptions().locale+ if (resolved) return resolved+ }+ return DEFAULT_LANGUAGE+}++/**+ * Maps any BCP-47 tag to the nearest production-ready language code, falling+ * back to {@link DEFAULT_LANGUAGE}. This is the single guard that keeps the+ * store/i18next from ever holding an unsupported or not-yet-ready locale+ * (e.g. `en-US` → `en`, `pt-PT` → `en` while pt-BR is not ready).+ */+export function resolveSupportedLocale(tag: string | null | undefined): string {+ const normalized = tag?.trim().toLowerCase()+ if (!normalized) return DEFAULT_LANGUAGE++ const exact = PICKABLE_LANGUAGES.find((l) => l.code.toLowerCase() === normalized)+ if (exact) return exact.code++ const base = normalized.split('-')[0]+ if (base) {+ const byBase = PICKABLE_LANGUAGES.find((l) => l.code.toLowerCase().split('-')[0] === base)+ if (byBase) return byBase.code+ }++ return DEFAULT_LANGUAGE+}++import i18nextInstance from './config'++/** Production-ready locale to boot with, derived from system preference or user choice. */+export function getInitialLocale(preference: LocalePreference | 'system' = 'system'): string {+ if (preference === 'system') return resolveSupportedLocale(getSystemPreferredLocale())+ return resolveSupportedLocale(preference)+}++/**+ * Switches the active language. The requested tag is normalized to a+ * production-ready code (so a stale/persisted/unsupported value can never put+ * the app in an undefined locale state) and i18next is told to change language.+ */+export const changeLocale = async (locale: string): Promise<void> => {+ const resolved = resolveSupportedLocale(locale)+ try {+ await i18nextInstance.changeLanguage(resolved)+ } catch (error) {+ console.error('Failed to change language:', error)+ throw error+ }+}diff --git a/packages/locales/tsconfig.json b/packages/locales/tsconfig.jsonnew file mode 100644index 0000000..313f67d--- /dev/null+++ b/packages/locales/tsconfig.json@@ -0,0 +1,14 @@+{+ "extends": "../../tsconfig.json",+ "compilerOptions": {+ "target": "ESNext",+ "module": "ESNext",+ "moduleResolution": "Bundler",+ "declaration": true,+ "outDir": "./dist",+ "rootDir": "./src",+ "lib": ["ESNext", "DOM", "DOM.Iterable"],+ "resolveJsonModule": true+ },+ "include": ["src/**/*"]+}diff --git a/packages/locales/vitest.config.ts b/packages/locales/vitest.config.tsnew file mode 100644index 0000000..c7fde7a--- /dev/null+++ b/packages/locales/vitest.config.ts@@ -0,0 +1,7 @@+import { defineConfig } from 'vitest/config'++export default defineConfig({+ test: {+ include: ['src/**/*.test.ts']+ }+})