diff --git a/README.md b/README.md index ee55679..bc9abd1 100644 --- a/README.md +++ b/README.md @@ -46,7 +46,7 @@ ReRune includes My library, Discover with genre filters, Saved stories, and thre Reading settings contains the Main/`vip` edition switch, an SDK staging-mode switch, a fixed date interpolation example, and cardinal plurals under the logical key `plural_sample`. Staging mode previews enabled draft translations when project staging is enabled and keeps its cache separate from published content. Refresh from the library, reader, or settings. Angular's adapter diagnostics remain available through `?tools=1`. -Bookmarks, progress, filters, tabs, and scroll stay in the app session through language and live-text changes. Only SDK translation data and the edition selection are cached persistently. The date in settings is a fixed example, not a synchronization timestamp. Refresh feedback distinguishes changed, unchanged, partially updated, and failed checks; partial results name the updated locales. +Bookmarks, progress, filters, tabs, and scroll stay in the app session through language and live-text changes. SDK translation data and the edition selection are cached persistently. Each app also remembers the language picked in its language picker, System default included, under `rerune-example-language` (browser `localStorage`, or AsyncStorage in Expo) and starts in it next time; the app does this, not the SDK. With nothing saved, or when storage fails, an app starts in English. The date in settings is a fixed example, not a synchronization timestamp. Refresh feedback distinguishes changed, unchanged, partially updated, and failed checks; partial results name the updated locales. SDK **1.8.0** serves OTA from `https://cdn.rerune.io/api/ota//manifest.json`, with the publish ID in the URL path and no identity header. It applies a locale version only when every remote value is compatible with the placeholders, plurals, and formats the app ships; otherwise the previous copy stays in use. Staging previews and hosted cardinal plurals with an omitted offset or explicit numeric `offset: 0` are unchanged. The examples consume the published packages and unchanged OTA payloads. diff --git a/examples/angular-ngx-translate/README.md b/examples/angular-ngx-translate/README.md index 7df56f1..57e9e91 100644 --- a/examples/angular-ngx-translate/README.md +++ b/examples/angular-ngx-translate/README.md @@ -103,7 +103,7 @@ If the native root engine is already registered elsewhere, attach ReRune by omit 1. Explore My library, Discover's genre filters, and the empty Saved shelf. Bookmark stories, read both chapters of each story, finish, and restart. 2. Switch between English, German, Spanish, Italian, and Portuguese while reading. Additional SDK locales appear alongside bundled languages. Chapter progress, bookmarks, filters, tabs, and scroll remain in this session. 3. Open Reading settings for the Main/`vip` edition switch, staging-mode switch, fixed `14.07.2026` interpolation sample, and `plural_sample` cardinal plural. Turn staging on to preview enabled drafts and off to restore published content. A banner stays visible while staging is active. Refresh from the library, reader, or settings. -4. Configure your own publishable OTA ID. Publish a root translation or a distinct `vip` value, then refresh. Edition choice and SDK translation caches persist across reloads; reading state does not. +4. Configure your own publishable OTA ID. Publish a root translation or a distinct `vip` value, then refresh. Edition choice, the picked language, and SDK translation caches persist across reloads; reading state does not. A remembered bundled language is the start language in the provider configuration; a remembered dashboard-only language is applied once `ReRuneService.ready()` resolves, like a picker change, so English stays visible while it downloads. 5. Block the OTA service or one locale request and refresh again. Partial results identify updated languages; failures retain existing text. Repeated taps start one check at a time. The date in settings is a fixed interpolation example. Refresh feedback describes the last manual check and remains visible until the next one. diff --git a/examples/angular-ngx-translate/src/app.html b/examples/angular-ngx-translate/src/app.html index badb6ee..c485b6f 100644 --- a/examples/angular-ngx-translate/src/app.html +++ b/examples/angular-ngx-translate/src/app.html @@ -8,9 +8,9 @@ {{ story().title | translate }} } @else { ReRune } @if (!reader()) { } diff --git a/examples/angular-ngx-translate/src/app.ts b/examples/angular-ngx-translate/src/app.ts index 61e81e0..3acdabe 100644 --- a/examples/angular-ngx-translate/src/app.ts +++ b/examples/angular-ngx-translate/src/app.ts @@ -4,7 +4,7 @@ import { of, delay } from 'rxjs' import { TranslateLoader, TranslatePipe, TranslateService, TranslateCompiler } from '@ngx-translate/core' import { TranslateMessageFormatCompiler } from 'ngx-translate-messageformat-compiler' import { ReRune, ReRuneService } from '@rerune/angular/ngx-translate' -import { messages, publishId, staging } from '../../angular-shared/messages' +import { initialLanguage, messages, publishId, staging } from '../../angular-shared/messages' import { ChapterPage } from '../../angular-shared/presentation' import { ChapterIcon, ChapterCover } from '../../angular-shared/artwork' @@ -40,7 +40,7 @@ export const appConfig = { logLevel: 'off', updatePolicy: { checkOnStart: true, periodicIntervalInHours: 24 }, }, { - lang: 'en', fallbackLang: 'en', + lang: initialLanguage, fallbackLang: 'en', loader: { provide: TranslateLoader, useClass: DemoLoader }, compiler: { provide: TranslateCompiler, useClass: TranslateMessageFormatCompiler }, }), diff --git a/examples/angular-shared/messages.ts b/examples/angular-shared/messages.ts index 441b3f2..de9da9e 100644 --- a/examples/angular-shared/messages.ts +++ b/examples/angular-shared/messages.ts @@ -27,3 +27,21 @@ export const publishId = typeof window === 'undefined' ? defaultPublishId : new URLSearchParams(window.location.search).get('publishId')?.trim() || defaultPublishId export const staging = typeof window !== 'undefined' && new URLSearchParams(window.location.search).get('staging') === 'true' + +// The app remembers the picker choice, not the SDK. A storage failure keeps the English start. +const languageKey = 'rerune-example-language' +export const savedLanguage = (() => { + try { return localStorage.getItem(languageKey) } catch { return null } +})() +export function saveLanguage(value: string) { + try { localStorage.setItem(languageKey, value) } catch { /* The choice lasts for this session only. */ } +} +export function systemLanguage() { + return navigator.languages.map(value => value.split('-')[0] ?? '').find(value => value in messages) ?? 'en' +} +// Both examples start in a bundled language through their provider +// configuration. A saved dashboard-only language is applied once ReRune is +// ready, like a picker change, so the page keeps English while it downloads. +// An earlier switch would reach the engine first: Transloco then shows raw keys. +export const restoredLanguage = savedLanguage === 'system' ? systemLanguage() : savedLanguage || 'en' +export const initialLanguage = restoredLanguage in messages ? restoredLanguage : 'en' diff --git a/examples/angular-shared/presentation.ts b/examples/angular-shared/presentation.ts index 4655e0d..57bea80 100644 --- a/examples/angular-shared/presentation.ts +++ b/examples/angular-shared/presentation.ts @@ -1,16 +1,17 @@ import { classifyCheck, refreshText, type RefreshPhase } from '../shared/refresh' import { Directive, HostListener, ViewChild, computed, signal } from '@angular/core' -import type { AfterViewChecked, ElementRef, Signal } from '@angular/core' +import type { AfterViewChecked, ElementRef, OnInit, Signal } from '@angular/core' import type { ReRuneSetVariantOptions, ReRuneState, ReRuneUpdateResult } from '@rerune/core' import { initialReadingState, readingReducer, stories, storyIds } from '../shared/stories' import type { LibraryTab, StoryId } from '../shared/stories' -import { messages, publishId } from './messages' +import { initialLanguage, messages, publishId, restoredLanguage, saveLanguage, savedLanguage, systemLanguage } from './messages' // Both examples keep their own native translation service and pipe. @Directive() -export abstract class ChapterPage implements AfterViewChecked { +export abstract class ChapterPage implements AfterViewChecked, OnInit { abstract readonly rerune: { state: Signal + ready(): Promise checkForUpdates(): Promise setVariant(value: string | ReRuneSetVariantOptions): Promise setStaging(staging: boolean): Promise @@ -42,7 +43,7 @@ export abstract class ChapterPage implements AfterViewChecked { readonly variantError = signal(false) readonly requestedStaging = signal(null) readonly stagingError = signal(false) - readonly systemLocale = signal(false) + readonly systemLocale = signal(savedLanguage === 'system') readonly availableLocales = computed(() => [...new Set([...Object.keys(messages), ...this.rerune.state().availableLocales])]) readonly nativeNames: Record = { en: 'English', de: 'Deutsch', es: 'Español', it: 'Italiano', pt: 'Português' } readonly showTools = new URLSearchParams(window.location.search).get('tools') === '1' @@ -100,16 +101,21 @@ export abstract class ChapterPage implements AfterViewChecked { const number = new Intl.NumberFormat(this.locale()) return { current: number.format(Math.min(this.completed() + 1, 2)), total: number.format(2) } } + ngOnInit() { + if (restoredLanguage === initialLanguage) return + const restore = () => { if (this.locale() === initialLanguage) this.setLocale(restoredLanguage) } + void this.rerune.ready().then(restore, restore) + } language(event: Event) { const value = (event.target as HTMLSelectElement).value + saveLanguage(value) this.systemLocale.set(value === 'system') if (value === 'system') this.systemLanguageChanged() else this.setLocale(value) } @HostListener('window:languagechange') systemLanguageChanged() { - if (this.systemLocale()) this.setLocale(navigator.languages.map(value => value.split('-')[0] ?? '') - .find(value => value in messages) ?? 'en') + if (this.systemLocale()) this.setLocale(systemLanguage()) } async refresh() { if (this.refreshing()) return diff --git a/examples/angular-transloco/README.md b/examples/angular-transloco/README.md index 6a66f3a..44139c2 100644 --- a/examples/angular-transloco/README.md +++ b/examples/angular-transloco/README.md @@ -101,7 +101,7 @@ If the native root engine is already registered elsewhere, attach ReRune by omit 1. Explore My library, Discover's genre filters, and the empty Saved shelf. Bookmark stories, read both chapters of each story, finish, and restart. 2. Switch between English, German, Spanish, Italian, and Portuguese while reading. Additional SDK locales appear alongside bundled languages. Chapter progress, bookmarks, filters, tabs, and scroll remain in this session. 3. Open Reading settings for the Main/`vip` edition switch, staging-mode switch, fixed `14.07.2026` interpolation sample, and `plural_sample` cardinal plural. Turn staging on to preview enabled drafts and off to restore published content. A banner stays visible while staging is active. Refresh from the library, reader, or settings. -4. Configure your own publishable OTA ID. Publish a root translation or a distinct `vip` value, then refresh. Edition choice and SDK translation caches persist across reloads; reading state does not. +4. Configure your own publishable OTA ID. Publish a root translation or a distinct `vip` value, then refresh. Edition choice, the picked language, and SDK translation caches persist across reloads; reading state does not. A remembered bundled language is the start language in the provider configuration; a remembered dashboard-only language is applied once `ReRuneService.ready()` resolves, like a picker change, so English stays visible while it downloads. 5. Block the OTA service or one locale request and refresh again. Partial results identify updated languages; failures retain existing text. Repeated taps start one check at a time. The date in settings is a fixed interpolation example. Refresh feedback describes the last manual check and remains visible until the next one. diff --git a/examples/angular-transloco/src/app.html b/examples/angular-transloco/src/app.html index a528416..c32fd29 100644 --- a/examples/angular-transloco/src/app.html +++ b/examples/angular-transloco/src/app.html @@ -8,9 +8,9 @@ {{ story().title | transloco }} } @else { ReRune } @if (!reader()) { } diff --git a/examples/angular-transloco/src/app.ts b/examples/angular-transloco/src/app.ts index 2003e7b..b9486a9 100644 --- a/examples/angular-transloco/src/app.ts +++ b/examples/angular-transloco/src/app.ts @@ -4,7 +4,7 @@ import { of, delay } from 'rxjs' import { TranslocoPipe, TranslocoService } from '@jsverse/transloco' import { provideTranslocoMessageformat } from '@jsverse/transloco-messageformat' import { ReRune, ReRuneService } from '@rerune/angular/transloco' -import { messages, publishId, staging } from '../../angular-shared/messages' +import { initialLanguage, messages, publishId, staging } from '../../angular-shared/messages' import { ChapterPage } from '../../angular-shared/presentation' import { ChapterIcon, ChapterCover } from '../../angular-shared/artwork' @@ -39,7 +39,7 @@ export const appConfig = { logLevel: 'off', updatePolicy: { checkOnStart: true, periodicIntervalInHours: 24 }, }, { - config: { availableLangs: Object.keys(messages), defaultLang: 'en', fallbackLang: 'en', reRenderOnLangChange: true }, + config: { availableLangs: Object.keys(messages), defaultLang: initialLanguage, fallbackLang: 'en', reRenderOnLangChange: true }, loader: DemoLoader, }), provideTranslocoMessageformat(), diff --git a/examples/react-native-expo/App.tsx b/examples/react-native-expo/App.tsx index 1567f9b..344c289 100644 --- a/examples/react-native-expo/App.tsx +++ b/examples/react-native-expo/App.tsx @@ -3,10 +3,11 @@ import { ActivityIndicator, Platform, StatusBar, Text, View } from 'react-native import { initialWindowMetrics, SafeAreaProvider, SafeAreaView } from 'react-native-safe-area-context' import * as NavigationBar from 'expo-navigation-bar' import { useFonts } from 'expo-font' +import AsyncStorage from '@react-native-async-storage/async-storage' import { ReRune, ReRuneProvider } from '@rerune/react-native' import type { ReRuneI18nextClient } from '@rerune/react-native' import { startup } from './src/i18n' -import { ChapterExperience } from './src/Chapter' +import { ChapterExperience, LANGUAGE_KEY, systemLanguage } from './src/Chapter' import { COLORS, styles } from './src/theme' import instrumentSans from '../shared/fonts/InstrumentSans-Regular.ttf' import instrumentSansBold from '../shared/fonts/InstrumentSans-Bold.ttf' @@ -18,6 +19,7 @@ const TEST_VARIANT = configuredTestVariant && configuredTestVariant !== ReRune.M export default function App() { const [client, setClient] = useState(null) const [startupError, setStartupError] = useState(null) + const [savedSystem, setSavedSystem] = useState(false) const [fontsReady, fontError] = useFonts({ InstrumentSans: instrumentSans, InstrumentSansBold: instrumentSansBold, @@ -26,8 +28,15 @@ export default function App() { useEffect(() => { if (Platform.OS === 'android') NavigationBar.setStyle('dark') }, []) useEffect(() => { let mounted = true - void startup.then(result => { + // The app, not the SDK, remembers the picked language. It is read during + // startup and applied before the first screen; a failed read starts in English. + const saved = Promise.resolve().then(() => AsyncStorage.getItem(LANGUAGE_KEY)).catch(() => null) + void Promise.all([startup, saved]).then(([result, language]) => { if (!mounted) return + if (language && result.client) { + if (language === 'system') setSavedSystem(true) + void result.client.i18n.changeLanguage(language === 'system' ? systemLanguage() : language) + } setClient(result.client) setStartupError(result.error) }) @@ -37,7 +46,7 @@ export default function App() { {startupError || fontError ? {fontError ? 'Could not load reading fonts.' : 'Could not initialize translations.'} - : client && fontsReady ? + : client && fontsReady ? : } diff --git a/examples/react-native-expo/README.md b/examples/react-native-expo/README.md index 9b67761..31c955d 100644 --- a/examples/react-native-expo/README.md +++ b/examples/react-native-expo/README.md @@ -15,7 +15,7 @@ pnpm dev:expo The app uses Expo **54.0.37**, React Native **0.81.5**, React **19.1.0**, and Hermes. Open it in an Expo SDK 54-compatible client or a development build that includes AsyncStorage. -Tap the current locale to open the language dropdown, then choose a language. The selected locale has a checkmark. Tap the selector again or press Android Back to dismiss the menu. Pull down in the library or reader to refresh, or use the refresh control in the library, reader, or Reading settings. +Tap the current locale to open the language dropdown, then choose a language. The selected locale has a checkmark. The app saves the choice, System default included, in AsyncStorage (`@react-native-async-storage/async-storage`, declared by the app) and restores it during startup, before the first screen. Tap the selector again or press Android Back to dismiss the menu. Pull down in the library or reader to refresh, or use the refresh control in the library, reader, or Reading settings. The background fills the screen edge-to-edge. `react-native-safe-area-context` keeps library, reader, sheets, loading, and error content clear of status bars, display cutouts, Android navigation bars, and the iOS home indicator, including in landscape. Status-bar icons are light; `expo-navigation-bar` and the Android app configuration keep three-button navigation legible on the dark background. See Expo's [safe-area guide](https://docs.expo.dev/versions/v54.0.0/sdk/safe-area-context/) and [navigation-bar API](https://docs.expo.dev/versions/v54.0.0/sdk/navigation-bar/). diff --git a/examples/react-native-expo/package.json b/examples/react-native-expo/package.json index ae4ef5d..ddd7fbc 100644 --- a/examples/react-native-expo/package.json +++ b/examples/react-native-expo/package.json @@ -9,15 +9,16 @@ "lint": "eslint App.tsx index.ts src --ext .ts,.tsx" }, "dependencies": { + "@react-native-async-storage/async-storage": "2.2.0", "@rerune/react-native": "1.8.0", "expo": "54.0.37", + "expo-font": "14.0.12", "expo-navigation-bar": "~5.0.10", "i18next": "^25.0.0", "react": "19.1.0", "react-i18next": "^15.0.0", "react-native": "0.81.5", "react-native-safe-area-context": "~5.6.0", - "expo-font": "14.0.12", "react-native-svg": "15.12.1" } } diff --git a/examples/react-native-expo/src/Chapter.tsx b/examples/react-native-expo/src/Chapter.tsx index 321b772..a6ed9e4 100644 --- a/examples/react-native-expo/src/Chapter.tsx +++ b/examples/react-native-expo/src/Chapter.tsx @@ -2,6 +2,7 @@ import { classifyCheck, refreshText, type RefreshPhase } from '../../shared/refr import { useEffect, useLayoutEffect, useReducer, useRef, useState } from 'react' import { AppState, BackHandler, Image, Modal, Pressable, RefreshControl, ScrollView, Switch, Text, View, useWindowDimensions } from 'react-native' import { SafeAreaView } from 'react-native-safe-area-context' +import AsyncStorage from '@react-native-async-storage/async-storage' import { useTranslation } from 'react-i18next' import { ReRune, useReRune } from '@rerune/react-native' import { initialReadingState, readingReducer, stories, storyIds, type LibraryTab, type StoryId } from '../../shared/stories' @@ -11,14 +12,20 @@ import { COLORS, styles } from './theme' import reruneLogo from '../../shared/assets/rerune-logo.png' const bundledLocales = ['en', 'de', 'es', 'it', 'pt'] -export function ChapterExperience({ testVariant }: { testVariant: string }) { +// The app, not the SDK, remembers the picked language: a code or 'system'. +export const LANGUAGE_KEY = 'rerune-example-language' +export function systemLanguage() { + const locale = Intl.DateTimeFormat().resolvedOptions().locale.split('-')[0] ?? 'en' + return bundledLocales.includes(locale) ? locale : 'en' +} +export function ChapterExperience({ testVariant, savedSystem = false }: { testVariant: string; savedSystem?: boolean }) { const { t, i18n } = useTranslation() const { client, state: sdk, checkForUpdates } = useReRune() const { width } = useWindowDimensions() const [book, dispatch] = useReducer(readingReducer, initialReadingState) const [reader, setReader] = useState(null) const [settings, setSettings] = useState(false) - const [systemLocale, setSystemLocale] = useState(false) + const [systemLocale, setSystemLocale] = useState(savedSystem) const [refreshing, setRefreshing] = useState(false) const [feedback, setFeedback] = useState(null) const [savingVariant, setSavingVariant] = useState(false) @@ -51,10 +58,7 @@ export function ChapterExperience({ testVariant }: { testVariant: string }) { }, [reader, settings]) useEffect(() => { if (!systemLocale) return - const update = () => { - const locale = Intl.DateTimeFormat().resolvedOptions().locale.split('-')[0] ?? 'en' - void i18n.changeLanguage(bundledLocales.includes(locale) ? locale : 'en') - } + const update = () => { void i18n.changeLanguage(systemLanguage()) } update() const subscription = AppState.addEventListener('change', state => { if (state === 'active') update() }) return () => subscription.remove() @@ -142,7 +146,11 @@ export function ChapterExperience({ testVariant }: { testVariant: string }) { {t(story.title)} : ReRune} { setSystemLocale(locale === 'system'); if (locale !== 'system') void i18n.changeLanguage(locale) }} /> + onSelect={locale => { + setSystemLocale(locale === 'system'); if (locale !== 'system') void i18n.changeLanguage(locale) + // A failed save keeps the choice for this run only. + Promise.resolve().then(() => AsyncStorage.setItem(LANGUAGE_KEY, locale)).catch(() => undefined) + }} /> {!reader && setSettings(true)} style={({ pressed }) => [styles.iconButton, styles.settingsButton, pressed && styles.pressed]}>} {reader ? <> diff --git a/examples/react-web-vite/README.md b/examples/react-web-vite/README.md index a4057b9..ae4e9c5 100644 --- a/examples/react-web-vite/README.md +++ b/examples/react-web-vite/README.md @@ -143,7 +143,7 @@ If your app owns `.use(...)` plugins or depends on a global instance, keep that 1. Explore My library, Discover's genre filters, and the empty Saved shelf. Bookmark stories, read both chapters of each story, finish, and restart. 2. Switch between English, German, Spanish, Italian, and Portuguese while reading. Additional SDK locales appear alongside bundled languages. Chapter progress, bookmarks, filters, tabs, and scroll remain in this session. 3. Open Reading settings for the Main/`vip` edition switch, staging-mode switch, fixed `14.07.2026` interpolation sample, and `plural_sample` cardinal plural. Turn staging on to preview enabled drafts and off to restore published content. A banner stays visible while staging is active. Refresh from the library, reader, or settings. -4. Configure your own publishable OTA ID. Publish a root translation or a distinct `vip` value, then refresh. Edition choice and SDK translation caches persist across reloads; reading state does not. +4. Configure your own publishable OTA ID. Publish a root translation or a distinct `vip` value, then refresh. Edition choice, the picked language, and SDK translation caches persist across reloads; reading state does not. `src/i18n.ts` reads the remembered language before `ReRune.setup(...)`, so the first render is already in it. 5. Block the OTA service or one locale request and refresh again. Partial results identify updated languages; failures retain existing text. Repeated taps start one check at a time. The date in settings is a fixed interpolation example. Refresh feedback describes the last manual check and remains visible until the next one. diff --git a/examples/react-web-vite/src/App.tsx b/examples/react-web-vite/src/App.tsx index 252ea38..9db6458 100644 --- a/examples/react-web-vite/src/App.tsx +++ b/examples/react-web-vite/src/App.tsx @@ -3,6 +3,7 @@ import { useEffect, useLayoutEffect, useReducer, useRef, useState } from 'react' import { useTranslation } from 'react-i18next' import { ReRune, ReRuneProvider, useReRune, type ReRuneI18nextClient } from '@rerune/react' import { StoryCover } from './StoryCover' +import { saveLanguage, savedLanguage, systemLanguage } from './i18n' import { initialReadingState, readingReducer, stories, storyIds, type LibraryTab, type StoryId } from '../../shared/stories' import '../../shared/reading.css' @@ -24,14 +25,14 @@ function Icon({ name }: { name: IconName }) { function LanguagePicker() { const { t, i18n } = useTranslation() const { state } = useReRune() - const [system, setSystem] = useState(false) + const [system, setSystem] = useState(savedLanguage === 'system') const locales = [...new Set(['en', 'de', 'es', 'it', 'pt', ...state.availableLocales])] const nativeNames: Record = { en: 'English', de: 'Deutsch', es: 'Español', it: 'Italiano', pt: 'Português' } useEffect(() => { if (!system) return const update = () => { - const locale = navigator.languages.map(value => value.split('-')[0] ?? '').find(value => ['en', 'de', 'es', 'it', 'pt'].includes(value)) ?? 'en' - void i18n.changeLanguage(locale) + const locale = systemLanguage() + if (locale !== i18n.language) void i18n.changeLanguage(locale) } update() window.addEventListener('languagechange', update) @@ -41,6 +42,7 @@ function LanguagePicker() {