mirror of
https://github.com/wger-project/flutter.git
synced 2026-11-29 01:18:35 +01:00
Merge remote-tracking branch 'origin/master' into feature/offline-mode
# Conflicts: # ios/Podfile.lock # lib/l10n/app_en.arb # lib/main.dart # lib/providers/user.dart # lib/widgets/core/settings.dart # pubspec.yaml # test/core/settings_test.dart # test/core/settings_test.mocks.dart # test/user/provider_test.dart
This commit is contained in:
12
.github/workflows/analyze.yml
vendored
12
.github/workflows/analyze.yml
vendored
@@ -5,17 +5,26 @@ on:
|
||||
- '**.dart'
|
||||
- 'pubspec.yaml'
|
||||
- 'analysis_options.yaml'
|
||||
- 'lib/l10n/**'
|
||||
- 'ios/Runner/Info.plist'
|
||||
- 'android/app/src/main/res/xml/locales_config.xml'
|
||||
pull_request:
|
||||
branches: [ master, ]
|
||||
paths:
|
||||
- '**/*.dart'
|
||||
- 'pubspec.yaml'
|
||||
- 'analysis_options.yaml'
|
||||
- 'lib/l10n/**'
|
||||
- 'ios/Runner/Info.plist'
|
||||
- 'android/app/src/main/res/xml/locales_config.xml'
|
||||
- '.github/actions/flutter-common/action.yml'
|
||||
- '.github/workflows/analyze.yml'
|
||||
workflow_call:
|
||||
workflow_dispatch:
|
||||
|
||||
permissions:
|
||||
contents: read
|
||||
|
||||
jobs:
|
||||
analyze:
|
||||
name: Run analyzer
|
||||
@@ -31,3 +40,6 @@ jobs:
|
||||
|
||||
- name: Analyze
|
||||
run: flutter analyze --no-fatal-infos --no-fatal-warnings
|
||||
|
||||
- name: Check locale lists are in sync
|
||||
run: dart run tool/check_locales.dart
|
||||
|
||||
4
.github/workflows/build-android.yml
vendored
4
.github/workflows/build-android.yml
vendored
@@ -16,6 +16,10 @@ on:
|
||||
required: true
|
||||
DECRYPTKEY_PROPERTIES:
|
||||
required: true
|
||||
|
||||
permissions:
|
||||
contents: read
|
||||
|
||||
jobs:
|
||||
build_android_apk:
|
||||
name: APK file
|
||||
|
||||
4
.github/workflows/build-apple.yml
vendored
4
.github/workflows/build-apple.yml
vendored
@@ -11,6 +11,10 @@ on:
|
||||
ref:
|
||||
required: true
|
||||
type: string
|
||||
|
||||
permissions:
|
||||
contents: read
|
||||
|
||||
jobs:
|
||||
build_ios:
|
||||
name: iOS
|
||||
|
||||
4
.github/workflows/build-linux.yml
vendored
4
.github/workflows/build-linux.yml
vendored
@@ -21,6 +21,10 @@ on:
|
||||
secrets:
|
||||
SSH_DEPLOY_KEY:
|
||||
required: true
|
||||
|
||||
permissions:
|
||||
contents: read
|
||||
|
||||
jobs:
|
||||
|
||||
# TODO: note that we currently only build for x64, as arm64 is not supported by
|
||||
|
||||
4
.github/workflows/build-windows.yml
vendored
4
.github/workflows/build-windows.yml
vendored
@@ -11,6 +11,10 @@ on:
|
||||
ref:
|
||||
required: true
|
||||
type: string
|
||||
|
||||
permissions:
|
||||
contents: read
|
||||
|
||||
jobs:
|
||||
# TODO: we currently upload the release folder as a ZIP, which works as a
|
||||
# portable version. For a proper installer (e.g. via Inno Setup or MSIX),
|
||||
|
||||
3
.github/workflows/bump-version.yml
vendored
3
.github/workflows/bump-version.yml
vendored
@@ -6,6 +6,9 @@ on:
|
||||
required: true
|
||||
type: string
|
||||
|
||||
permissions:
|
||||
contents: write
|
||||
|
||||
jobs:
|
||||
determine_version:
|
||||
name: Create tag
|
||||
|
||||
3
.github/workflows/ci.yml
vendored
3
.github/workflows/ci.yml
vendored
@@ -14,6 +14,9 @@ on:
|
||||
workflow_call:
|
||||
workflow_dispatch:
|
||||
|
||||
permissions:
|
||||
contents: read
|
||||
|
||||
jobs:
|
||||
test:
|
||||
name: Run tests
|
||||
|
||||
40
.github/workflows/codeql-analysis.yml
vendored
Normal file
40
.github/workflows/codeql-analysis.yml
vendored
Normal file
@@ -0,0 +1,40 @@
|
||||
name: "CodeQL"
|
||||
|
||||
on:
|
||||
push:
|
||||
branches: [ master ]
|
||||
pull_request:
|
||||
branches: [ master ]
|
||||
schedule:
|
||||
- cron: '44 6 * * 6' # Every Saturday at 6:44 UTC
|
||||
|
||||
jobs:
|
||||
analyze:
|
||||
name: Analyze
|
||||
runs-on: ubuntu-latest
|
||||
permissions:
|
||||
actions: read
|
||||
contents: read
|
||||
security-events: write
|
||||
|
||||
strategy:
|
||||
fail-fast: false
|
||||
matrix:
|
||||
language: [ 'actions' ]
|
||||
# Supported languages https://git.io/codeql-language-support
|
||||
|
||||
steps:
|
||||
- name: Checkout repository
|
||||
uses: actions/checkout@v6
|
||||
|
||||
# Initializes the CodeQL tools for scanning.
|
||||
- name: Initialize CodeQL
|
||||
uses: github/codeql-action/init@v4
|
||||
with:
|
||||
languages: ${{ matrix.language }}
|
||||
|
||||
- name: Autobuild
|
||||
uses: github/codeql-action/autobuild@v4
|
||||
|
||||
- name: Perform CodeQL Analysis
|
||||
uses: github/codeql-action/analyze@v4
|
||||
7
.github/workflows/make-release.yml
vendored
7
.github/workflows/make-release.yml
vendored
@@ -7,6 +7,9 @@ on:
|
||||
required: true
|
||||
type: string
|
||||
|
||||
permissions:
|
||||
contents: read
|
||||
|
||||
jobs:
|
||||
|
||||
ci:
|
||||
@@ -16,6 +19,8 @@ jobs:
|
||||
determine_version:
|
||||
needs: ci
|
||||
name: Prepare
|
||||
permissions:
|
||||
contents: write
|
||||
uses: ./.github/workflows/bump-version.yml
|
||||
with:
|
||||
app_version: ${{ github.event.inputs.version }}
|
||||
@@ -126,6 +131,8 @@ jobs:
|
||||
make_gh_release:
|
||||
name: Make Github Release
|
||||
runs-on: ubuntu-latest
|
||||
permissions:
|
||||
contents: write
|
||||
needs:
|
||||
- upload_play_store
|
||||
- build_linux
|
||||
|
||||
5
.github/workflows/screenshots.yml
vendored
5
.github/workflows/screenshots.yml
vendored
@@ -7,6 +7,9 @@ on:
|
||||
type: boolean
|
||||
default: false
|
||||
|
||||
permissions:
|
||||
contents: read
|
||||
|
||||
jobs:
|
||||
screenshots_apple:
|
||||
name: 'iOS'
|
||||
@@ -125,6 +128,8 @@ jobs:
|
||||
- screenshots_android
|
||||
|
||||
runs-on: ubuntu-latest
|
||||
permissions:
|
||||
contents: write
|
||||
steps:
|
||||
- uses: actions/checkout@v6
|
||||
|
||||
|
||||
@@ -12,6 +12,45 @@
|
||||
<string>$(PRODUCT_BUNDLE_IDENTIFIER)</string>
|
||||
<key>CFBundleInfoDictionaryVersion</key>
|
||||
<string>6.0</string>
|
||||
<key>CFBundleLocalizations</key>
|
||||
<array>
|
||||
<string>am</string>
|
||||
<string>ar</string>
|
||||
<string>ca</string>
|
||||
<string>cs</string>
|
||||
<string>de</string>
|
||||
<string>el</string>
|
||||
<string>en</string>
|
||||
<string>es</string>
|
||||
<string>fa</string>
|
||||
<string>fil</string>
|
||||
<string>fr</string>
|
||||
<string>he</string>
|
||||
<string>hi</string>
|
||||
<string>hr</string>
|
||||
<string>hu</string>
|
||||
<string>id</string>
|
||||
<string>it</string>
|
||||
<string>ja</string>
|
||||
<string>ko</string>
|
||||
<string>mk</string>
|
||||
<string>nb</string>
|
||||
<string>nl</string>
|
||||
<string>pl</string>
|
||||
<string>pt</string>
|
||||
<string>pt-BR</string>
|
||||
<string>pt-PT</string>
|
||||
<string>ro</string>
|
||||
<string>ru</string>
|
||||
<string>sk</string>
|
||||
<string>ta</string>
|
||||
<string>th</string>
|
||||
<string>tr</string>
|
||||
<string>uk</string>
|
||||
<string>ur</string>
|
||||
<string>zh</string>
|
||||
<string>zh-Hant</string>
|
||||
</array>
|
||||
<key>CFBundleName</key>
|
||||
<string>wger</string>
|
||||
<key>CFBundlePackageType</key>
|
||||
|
||||
@@ -56,6 +56,7 @@ const PREFS_INGREDIENTS = 'ingredientData';
|
||||
const PREFS_WORKOUT_UNITS = 'workoutUnits';
|
||||
const PREFS_USER = 'userData';
|
||||
const PREFS_USER_DARK_THEME = 'userDarkMode';
|
||||
const PREFS_USER_LOCALE = 'userLocale';
|
||||
const PREFS_LAST_SERVER = 'lastServer';
|
||||
|
||||
/// True once PowerSync has been reachable for this user at least once
|
||||
|
||||
@@ -34,3 +34,19 @@ Locale? resolveLocale(List<Locale>? locales, Iterable<Locale> supportedLocales)
|
||||
}
|
||||
return null;
|
||||
}
|
||||
|
||||
/// Stable string encoding for a [Locale], matching the keys generated by
|
||||
/// Flutter's AppLocalizations (e.g. `pt_BR`, `zh_Hant`, `pl`). [scriptCode]
|
||||
/// takes precedence over [countryCode] so locales like `zh_Hant` round-trip
|
||||
/// distinctly from plain `zh`.
|
||||
String encodeLocale(Locale locale) {
|
||||
final script = locale.scriptCode;
|
||||
if (script != null && script.isNotEmpty) {
|
||||
return '${locale.languageCode}_$script';
|
||||
}
|
||||
final country = locale.countryCode;
|
||||
if (country != null && country.isNotEmpty) {
|
||||
return '${locale.languageCode}_$country';
|
||||
}
|
||||
return locale.languageCode;
|
||||
}
|
||||
|
||||
@@ -1176,6 +1176,14 @@
|
||||
"networkInfo": "Network information",
|
||||
"youAreOffline": "You are offline",
|
||||
"offlineModeInfo": "Some features are unavailable until you reconnect to the internet (buttons and menus will be disabled). Currently, this mainly affects editing routines and nutrition plans, but logging workouts and meals works offline. The data will be synced automatically once you are back online.",
|
||||
"appLanguage": "App language",
|
||||
"@appLanguage": {
|
||||
"description": "Label for the in-app language selector in settings"
|
||||
},
|
||||
"appLanguageSystem": "System default",
|
||||
"@appLanguageSystem": {
|
||||
"description": "Dropdown entry that follows the device system language"
|
||||
},
|
||||
"productNotFoundOpenFoodFacts": "You can add this product to Open Food Facts to help the community!",
|
||||
"@productNotFoundOpenFoodFacts": {
|
||||
"description": "Label shown when product is not found to encourage users to go on Open Food Facts and add it themselves"
|
||||
|
||||
@@ -833,6 +833,8 @@
|
||||
"darkMode": "Zawsze używaj trybu ciemnego",
|
||||
"lightMode": "Zawsze używaj trybu jasnego",
|
||||
"systemMode": "Ustawienia systemu",
|
||||
"appLanguage": "Język aplikacji",
|
||||
"appLanguageSystem": "Domyślny systemu",
|
||||
"fitInWeek": "Dopasuj w tygodniu",
|
||||
"dayTypeAmrap": "Tak dużo rund jak to możliwe",
|
||||
"trophies": "Trofea",
|
||||
|
||||
57
lib/l10n/language_native_names.dart
Normal file
57
lib/l10n/language_native_names.dart
Normal file
@@ -0,0 +1,57 @@
|
||||
/*
|
||||
* This file is part of wger Workout Manager <https://github.com/wger-project>.
|
||||
* Copyright (c) 2026 - 2026 wger Team
|
||||
*
|
||||
* wger Workout Manager is free software: you can redistribute it and/or modify
|
||||
* it under the terms of the GNU Affero General Public License as published by
|
||||
* the Free Software Foundation, either version 3 of the License, or
|
||||
* (at your option) any later version.
|
||||
*
|
||||
* This program is distributed in the hope that it will be useful,
|
||||
* but WITHOUT ANY WARRANTY; without even the implied warranty of
|
||||
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
|
||||
* GNU Affero General Public License for more details.
|
||||
*
|
||||
* You should have received a copy of the GNU Affero General Public License
|
||||
* along with this program. If not, see <http://www.gnu.org/licenses/>.
|
||||
*/
|
||||
|
||||
/// Native display names for each supported locale, keyed by the locale name
|
||||
const Map<String, String> languageNativeNames = {
|
||||
'am': 'አማርኛ',
|
||||
'ar': 'العربية',
|
||||
'ca': 'Català',
|
||||
'cs': 'Čeština',
|
||||
'de': 'Deutsch',
|
||||
'el': 'Ελληνικά',
|
||||
'en': 'English',
|
||||
'es': 'Español',
|
||||
'fa': 'فارسی',
|
||||
'fil': 'Filipino',
|
||||
'fr': 'Français',
|
||||
'he': 'עברית',
|
||||
'hi': 'हिन्दी',
|
||||
'hr': 'Hrvatski',
|
||||
'hu': 'Magyar',
|
||||
'id': 'Bahasa Indonesia',
|
||||
'it': 'Italiano',
|
||||
'ja': '日本語',
|
||||
'ko': '한국어',
|
||||
'mk': 'Македонски',
|
||||
'nb': 'Norsk bokmål',
|
||||
'nl': 'Nederlands',
|
||||
'pl': 'Polski',
|
||||
'pt': 'Português',
|
||||
'pt_BR': 'Português (Brasil)',
|
||||
'pt_PT': 'Português (Portugal)',
|
||||
'ro': 'Română',
|
||||
'ru': 'Русский',
|
||||
'sk': 'Slovenčina',
|
||||
'ta': 'தமிழ்',
|
||||
'th': 'ไทย',
|
||||
'tr': 'Türkçe',
|
||||
'uk': 'Українська',
|
||||
'ur': 'اردو',
|
||||
'zh': '中文',
|
||||
'zh_Hant': '繁體中文',
|
||||
};
|
||||
@@ -190,6 +190,9 @@ class MainApp extends ConsumerWidget {
|
||||
final themeMode = ref.watch(
|
||||
appSettingsProvider.select((s) => s.value?.themeMode ?? ThemeMode.system),
|
||||
);
|
||||
final userLocale = ref.watch(
|
||||
appSettingsProvider.select((s) => s.value?.userLocale),
|
||||
);
|
||||
|
||||
return MaterialApp(
|
||||
title: 'wger',
|
||||
@@ -199,6 +202,7 @@ class MainApp extends ConsumerWidget {
|
||||
highContrastTheme: wgerLightThemeHc,
|
||||
highContrastDarkTheme: wgerDarkThemeHc,
|
||||
themeMode: themeMode,
|
||||
locale: userLocale,
|
||||
home: _getHomeScreen(authState),
|
||||
routes: {
|
||||
DashboardScreen.routeName: (ctx) => const DashboardScreen(),
|
||||
|
||||
@@ -25,7 +25,9 @@ import 'package:freezed_annotation/freezed_annotation.dart';
|
||||
import 'package:riverpod_annotation/riverpod_annotation.dart';
|
||||
import 'package:shared_preferences/shared_preferences.dart';
|
||||
import 'package:wger/helpers/consts.dart';
|
||||
import 'package:wger/helpers/locale.dart';
|
||||
import 'package:wger/helpers/shared_preferences.dart';
|
||||
import 'package:wger/l10n/generated/app_localizations.dart';
|
||||
|
||||
part 'app_settings_notifier.freezed.dart';
|
||||
part 'app_settings_notifier.g.dart';
|
||||
@@ -75,6 +77,9 @@ sealed class AppSettings with _$AppSettings {
|
||||
const factory AppSettings({
|
||||
@Default(ThemeMode.system) ThemeMode themeMode,
|
||||
@Default([]) List<DashboardItem> dashboardItems,
|
||||
|
||||
/// Locale override. Null means the app follows the system locale.
|
||||
Locale? userLocale,
|
||||
}) = _AppSettings;
|
||||
}
|
||||
|
||||
@@ -91,8 +96,13 @@ class AppSettingsNotifier extends _$AppSettingsNotifier {
|
||||
Future<AppSettings> build() async {
|
||||
_prefs = ref.read(appSettingsPrefsProvider);
|
||||
final themeMode = await _loadThemeMode();
|
||||
final userLocale = await _loadUserLocale();
|
||||
final items = await _loadDashboardItems();
|
||||
return AppSettings(themeMode: themeMode, dashboardItems: items);
|
||||
return AppSettings(
|
||||
themeMode: themeMode,
|
||||
userLocale: userLocale,
|
||||
dashboardItems: items,
|
||||
);
|
||||
}
|
||||
|
||||
//
|
||||
@@ -118,6 +128,52 @@ class AppSettingsNotifier extends _$AppSettingsNotifier {
|
||||
}
|
||||
}
|
||||
|
||||
//
|
||||
// Locale override
|
||||
//
|
||||
|
||||
Future<Locale?> _loadUserLocale() async {
|
||||
final raw = await _prefs.getString(PREFS_USER_LOCALE);
|
||||
return _matchSupportedLocale(raw);
|
||||
}
|
||||
|
||||
/// Match a stored locale tag (`languageCode` or `languageCode_subtag`)
|
||||
/// against [AppLocalizations.supportedLocales]. Returns the exact supported
|
||||
/// instance to keep dropdown identity stable, or null when no match is found.
|
||||
static Locale? _matchSupportedLocale(String? raw) {
|
||||
if (raw == null || raw.isEmpty) {
|
||||
return null;
|
||||
}
|
||||
for (final locale in AppLocalizations.supportedLocales) {
|
||||
if (encodeLocale(locale) == raw) {
|
||||
return locale;
|
||||
}
|
||||
}
|
||||
// Fallback: match by language only (e.g. stored "pl" picks the only pl).
|
||||
final lang = raw.split('_').first;
|
||||
for (final locale in AppLocalizations.supportedLocales) {
|
||||
if (locale.languageCode == lang &&
|
||||
(locale.countryCode == null || locale.countryCode!.isEmpty) &&
|
||||
(locale.scriptCode == null || locale.scriptCode!.isEmpty)) {
|
||||
return locale;
|
||||
}
|
||||
}
|
||||
return null;
|
||||
}
|
||||
|
||||
/// Override the app locale. Passing `null` clears the override and falls
|
||||
/// back to the system locale.
|
||||
Future<void> setUserLocale(Locale? locale) async {
|
||||
final current = state.asData?.value ?? const AppSettings();
|
||||
state = AsyncData(current.copyWith(userLocale: locale));
|
||||
|
||||
if (locale == null) {
|
||||
await _prefs.remove(PREFS_USER_LOCALE);
|
||||
} else {
|
||||
await _prefs.setString(PREFS_USER_LOCALE, encodeLocale(locale));
|
||||
}
|
||||
}
|
||||
|
||||
//
|
||||
// Dashboard config
|
||||
//
|
||||
|
||||
@@ -14,7 +14,8 @@ T _$identity<T>(T value) => value;
|
||||
/// @nodoc
|
||||
mixin _$AppSettings {
|
||||
|
||||
ThemeMode get themeMode; List<DashboardItem> get dashboardItems;
|
||||
ThemeMode get themeMode; List<DashboardItem> get dashboardItems;/// Locale override. Null means the app follows the system locale.
|
||||
Locale? get userLocale;
|
||||
/// Create a copy of AppSettings
|
||||
/// with the given fields replaced by the non-null parameter values.
|
||||
@JsonKey(includeFromJson: false, includeToJson: false)
|
||||
@@ -25,16 +26,16 @@ $AppSettingsCopyWith<AppSettings> get copyWith => _$AppSettingsCopyWithImpl<AppS
|
||||
|
||||
@override
|
||||
bool operator ==(Object other) {
|
||||
return identical(this, other) || (other.runtimeType == runtimeType&&other is AppSettings&&(identical(other.themeMode, themeMode) || other.themeMode == themeMode)&&const DeepCollectionEquality().equals(other.dashboardItems, dashboardItems));
|
||||
return identical(this, other) || (other.runtimeType == runtimeType&&other is AppSettings&&(identical(other.themeMode, themeMode) || other.themeMode == themeMode)&&const DeepCollectionEquality().equals(other.dashboardItems, dashboardItems)&&(identical(other.userLocale, userLocale) || other.userLocale == userLocale));
|
||||
}
|
||||
|
||||
|
||||
@override
|
||||
int get hashCode => Object.hash(runtimeType,themeMode,const DeepCollectionEquality().hash(dashboardItems));
|
||||
int get hashCode => Object.hash(runtimeType,themeMode,const DeepCollectionEquality().hash(dashboardItems),userLocale);
|
||||
|
||||
@override
|
||||
String toString() {
|
||||
return 'AppSettings(themeMode: $themeMode, dashboardItems: $dashboardItems)';
|
||||
return 'AppSettings(themeMode: $themeMode, dashboardItems: $dashboardItems, userLocale: $userLocale)';
|
||||
}
|
||||
|
||||
|
||||
@@ -45,7 +46,7 @@ abstract mixin class $AppSettingsCopyWith<$Res> {
|
||||
factory $AppSettingsCopyWith(AppSettings value, $Res Function(AppSettings) _then) = _$AppSettingsCopyWithImpl;
|
||||
@useResult
|
||||
$Res call({
|
||||
ThemeMode themeMode, List<DashboardItem> dashboardItems
|
||||
ThemeMode themeMode, List<DashboardItem> dashboardItems, Locale? userLocale
|
||||
});
|
||||
|
||||
|
||||
@@ -62,11 +63,12 @@ class _$AppSettingsCopyWithImpl<$Res>
|
||||
|
||||
/// Create a copy of AppSettings
|
||||
/// with the given fields replaced by the non-null parameter values.
|
||||
@pragma('vm:prefer-inline') @override $Res call({Object? themeMode = null,Object? dashboardItems = null,}) {
|
||||
@pragma('vm:prefer-inline') @override $Res call({Object? themeMode = null,Object? dashboardItems = null,Object? userLocale = freezed,}) {
|
||||
return _then(_self.copyWith(
|
||||
themeMode: null == themeMode ? _self.themeMode : themeMode // ignore: cast_nullable_to_non_nullable
|
||||
as ThemeMode,dashboardItems: null == dashboardItems ? _self.dashboardItems : dashboardItems // ignore: cast_nullable_to_non_nullable
|
||||
as List<DashboardItem>,
|
||||
as List<DashboardItem>,userLocale: freezed == userLocale ? _self.userLocale : userLocale // ignore: cast_nullable_to_non_nullable
|
||||
as Locale?,
|
||||
));
|
||||
}
|
||||
|
||||
@@ -148,10 +150,10 @@ return $default(_that);case _:
|
||||
/// }
|
||||
/// ```
|
||||
|
||||
@optionalTypeArgs TResult maybeWhen<TResult extends Object?>(TResult Function( ThemeMode themeMode, List<DashboardItem> dashboardItems)? $default,{required TResult orElse(),}) {final _that = this;
|
||||
@optionalTypeArgs TResult maybeWhen<TResult extends Object?>(TResult Function( ThemeMode themeMode, List<DashboardItem> dashboardItems, Locale? userLocale)? $default,{required TResult orElse(),}) {final _that = this;
|
||||
switch (_that) {
|
||||
case _AppSettings() when $default != null:
|
||||
return $default(_that.themeMode,_that.dashboardItems);case _:
|
||||
return $default(_that.themeMode,_that.dashboardItems,_that.userLocale);case _:
|
||||
return orElse();
|
||||
|
||||
}
|
||||
@@ -169,10 +171,10 @@ return $default(_that.themeMode,_that.dashboardItems);case _:
|
||||
/// }
|
||||
/// ```
|
||||
|
||||
@optionalTypeArgs TResult when<TResult extends Object?>(TResult Function( ThemeMode themeMode, List<DashboardItem> dashboardItems) $default,) {final _that = this;
|
||||
@optionalTypeArgs TResult when<TResult extends Object?>(TResult Function( ThemeMode themeMode, List<DashboardItem> dashboardItems, Locale? userLocale) $default,) {final _that = this;
|
||||
switch (_that) {
|
||||
case _AppSettings():
|
||||
return $default(_that.themeMode,_that.dashboardItems);}
|
||||
return $default(_that.themeMode,_that.dashboardItems,_that.userLocale);}
|
||||
}
|
||||
/// A variant of `when` that fallback to returning `null`
|
||||
///
|
||||
@@ -186,10 +188,10 @@ return $default(_that.themeMode,_that.dashboardItems);}
|
||||
/// }
|
||||
/// ```
|
||||
|
||||
@optionalTypeArgs TResult? whenOrNull<TResult extends Object?>(TResult? Function( ThemeMode themeMode, List<DashboardItem> dashboardItems)? $default,) {final _that = this;
|
||||
@optionalTypeArgs TResult? whenOrNull<TResult extends Object?>(TResult? Function( ThemeMode themeMode, List<DashboardItem> dashboardItems, Locale? userLocale)? $default,) {final _that = this;
|
||||
switch (_that) {
|
||||
case _AppSettings() when $default != null:
|
||||
return $default(_that.themeMode,_that.dashboardItems);case _:
|
||||
return $default(_that.themeMode,_that.dashboardItems,_that.userLocale);case _:
|
||||
return null;
|
||||
|
||||
}
|
||||
@@ -201,7 +203,7 @@ return $default(_that.themeMode,_that.dashboardItems);case _:
|
||||
|
||||
|
||||
class _AppSettings implements AppSettings {
|
||||
const _AppSettings({this.themeMode = ThemeMode.system, final List<DashboardItem> dashboardItems = const []}): _dashboardItems = dashboardItems;
|
||||
const _AppSettings({this.themeMode = ThemeMode.system, final List<DashboardItem> dashboardItems = const [], this.userLocale}): _dashboardItems = dashboardItems;
|
||||
|
||||
|
||||
@override@JsonKey() final ThemeMode themeMode;
|
||||
@@ -212,6 +214,8 @@ class _AppSettings implements AppSettings {
|
||||
return EqualUnmodifiableListView(_dashboardItems);
|
||||
}
|
||||
|
||||
/// Locale override. Null means the app follows the system locale.
|
||||
@override final Locale? userLocale;
|
||||
|
||||
/// Create a copy of AppSettings
|
||||
/// with the given fields replaced by the non-null parameter values.
|
||||
@@ -223,16 +227,16 @@ _$AppSettingsCopyWith<_AppSettings> get copyWith => __$AppSettingsCopyWithImpl<_
|
||||
|
||||
@override
|
||||
bool operator ==(Object other) {
|
||||
return identical(this, other) || (other.runtimeType == runtimeType&&other is _AppSettings&&(identical(other.themeMode, themeMode) || other.themeMode == themeMode)&&const DeepCollectionEquality().equals(other._dashboardItems, _dashboardItems));
|
||||
return identical(this, other) || (other.runtimeType == runtimeType&&other is _AppSettings&&(identical(other.themeMode, themeMode) || other.themeMode == themeMode)&&const DeepCollectionEquality().equals(other._dashboardItems, _dashboardItems)&&(identical(other.userLocale, userLocale) || other.userLocale == userLocale));
|
||||
}
|
||||
|
||||
|
||||
@override
|
||||
int get hashCode => Object.hash(runtimeType,themeMode,const DeepCollectionEquality().hash(_dashboardItems));
|
||||
int get hashCode => Object.hash(runtimeType,themeMode,const DeepCollectionEquality().hash(_dashboardItems),userLocale);
|
||||
|
||||
@override
|
||||
String toString() {
|
||||
return 'AppSettings(themeMode: $themeMode, dashboardItems: $dashboardItems)';
|
||||
return 'AppSettings(themeMode: $themeMode, dashboardItems: $dashboardItems, userLocale: $userLocale)';
|
||||
}
|
||||
|
||||
|
||||
@@ -243,7 +247,7 @@ abstract mixin class _$AppSettingsCopyWith<$Res> implements $AppSettingsCopyWith
|
||||
factory _$AppSettingsCopyWith(_AppSettings value, $Res Function(_AppSettings) _then) = __$AppSettingsCopyWithImpl;
|
||||
@override @useResult
|
||||
$Res call({
|
||||
ThemeMode themeMode, List<DashboardItem> dashboardItems
|
||||
ThemeMode themeMode, List<DashboardItem> dashboardItems, Locale? userLocale
|
||||
});
|
||||
|
||||
|
||||
@@ -260,11 +264,12 @@ class __$AppSettingsCopyWithImpl<$Res>
|
||||
|
||||
/// Create a copy of AppSettings
|
||||
/// with the given fields replaced by the non-null parameter values.
|
||||
@override @pragma('vm:prefer-inline') $Res call({Object? themeMode = null,Object? dashboardItems = null,}) {
|
||||
@override @pragma('vm:prefer-inline') $Res call({Object? themeMode = null,Object? dashboardItems = null,Object? userLocale = freezed,}) {
|
||||
return _then(_AppSettings(
|
||||
themeMode: null == themeMode ? _self.themeMode : themeMode // ignore: cast_nullable_to_non_nullable
|
||||
as ThemeMode,dashboardItems: null == dashboardItems ? _self._dashboardItems : dashboardItems // ignore: cast_nullable_to_non_nullable
|
||||
as List<DashboardItem>,
|
||||
as List<DashboardItem>,userLocale: freezed == userLocale ? _self.userLocale : userLocale // ignore: cast_nullable_to_non_nullable
|
||||
as Locale?,
|
||||
));
|
||||
}
|
||||
|
||||
|
||||
@@ -33,7 +33,7 @@ final class AppSettingsNotifierProvider
|
||||
AppSettingsNotifier create() => AppSettingsNotifier();
|
||||
}
|
||||
|
||||
String _$appSettingsNotifierHash() => r'60f21572cdae5ecba6dfa3f8bb07e76b21812ba3';
|
||||
String _$appSettingsNotifierHash() => r'43dc14cde2fb06bfda226f18a8ac1196461aa27c';
|
||||
|
||||
abstract class _$AppSettingsNotifier extends $AsyncNotifier<AppSettings> {
|
||||
FutureOr<AppSettings> build();
|
||||
|
||||
@@ -21,6 +21,7 @@ import 'package:wger/core/wide_screen_wrapper.dart';
|
||||
import 'package:wger/l10n/generated/app_localizations.dart';
|
||||
import 'package:wger/screens/settings_plates_screen.dart';
|
||||
import 'package:wger/widgets/core/settings/image_cache.dart';
|
||||
import 'package:wger/widgets/core/settings/language.dart';
|
||||
import 'package:wger/widgets/core/settings/theme.dart';
|
||||
|
||||
class SettingsPage extends StatelessWidget {
|
||||
@@ -46,6 +47,7 @@ class SettingsPage extends StatelessWidget {
|
||||
const SettingsImageCache(),
|
||||
ListTile(title: Text(i18n.others, style: Theme.of(context).textTheme.headlineSmall)),
|
||||
const SettingsTheme(),
|
||||
const SettingsLanguage(),
|
||||
ListTile(
|
||||
title: Text(i18n.selectAvailablePlates),
|
||||
onTap: () {
|
||||
|
||||
68
lib/widgets/core/settings/language.dart
Normal file
68
lib/widgets/core/settings/language.dart
Normal file
@@ -0,0 +1,68 @@
|
||||
/*
|
||||
* This file is part of wger Workout Manager <https://github.com/wger-project>.
|
||||
* Copyright (c) 2026 - 2026 wger Team
|
||||
*
|
||||
* wger Workout Manager is free software: you can redistribute it and/or modify
|
||||
* it under the terms of the GNU Affero General Public License as published by
|
||||
* the Free Software Foundation, either version 3 of the License, or
|
||||
* (at your option) any later version.
|
||||
*
|
||||
* This program is distributed in the hope that it will be useful,
|
||||
* but WITHOUT ANY WARRANTY; without even the implied warranty of
|
||||
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
|
||||
* GNU Affero General Public License for more details.
|
||||
*
|
||||
* You should have received a copy of the GNU Affero General Public License
|
||||
* along with this program. If not, see <http://www.gnu.org/licenses/>.
|
||||
*/
|
||||
|
||||
import 'package:flutter/material.dart';
|
||||
import 'package:flutter_riverpod/flutter_riverpod.dart';
|
||||
import 'package:wger/helpers/locale.dart';
|
||||
import 'package:wger/l10n/generated/app_localizations.dart';
|
||||
import 'package:wger/l10n/language_native_names.dart';
|
||||
import 'package:wger/providers/app_settings_notifier.dart';
|
||||
|
||||
String _displayNameFor(Locale locale) {
|
||||
return languageNativeNames[encodeLocale(locale)] ??
|
||||
languageNativeNames[locale.languageCode] ??
|
||||
encodeLocale(locale);
|
||||
}
|
||||
|
||||
class SettingsLanguage extends ConsumerWidget {
|
||||
const SettingsLanguage({super.key});
|
||||
|
||||
@override
|
||||
Widget build(BuildContext context, WidgetRef ref) {
|
||||
final i18n = AppLocalizations.of(context);
|
||||
final userLocale = ref.watch(
|
||||
appSettingsProvider.select((s) => s.value?.userLocale),
|
||||
);
|
||||
|
||||
final supported = [...AppLocalizations.supportedLocales]
|
||||
..sort((a, b) => _displayNameFor(a).compareTo(_displayNameFor(b)));
|
||||
|
||||
return ListTile(
|
||||
title: Text(i18n.appLanguage),
|
||||
trailing: DropdownButton<Locale?>(
|
||||
key: const ValueKey('appLanguageDropdown'),
|
||||
value: userLocale,
|
||||
onChanged: (Locale? newValue) {
|
||||
ref.read(appSettingsProvider.notifier).setUserLocale(newValue);
|
||||
},
|
||||
items: <DropdownMenuItem<Locale?>>[
|
||||
DropdownMenuItem<Locale?>(
|
||||
value: null,
|
||||
child: Text(i18n.appLanguageSystem),
|
||||
),
|
||||
...supported.map(
|
||||
(locale) => DropdownMenuItem<Locale?>(
|
||||
value: locale,
|
||||
child: Text(_displayNameFor(locale)),
|
||||
),
|
||||
),
|
||||
],
|
||||
),
|
||||
);
|
||||
}
|
||||
}
|
||||
10
pubspec.lock
10
pubspec.lock
@@ -540,10 +540,10 @@ packages:
|
||||
dependency: "direct main"
|
||||
description:
|
||||
name: flutter_svg
|
||||
sha256: "1ded017b39c8e15c8948ea855070a5ff8ff8b3d5e83f3446e02d6bb12add7ad9"
|
||||
sha256: "35882981abcbfb8c15b286f0cd690ff25bac12d95eff3e25ee207f37d4c42e7f"
|
||||
url: "https://pub.dev"
|
||||
source: hosted
|
||||
version: "2.2.4"
|
||||
version: "2.3.0"
|
||||
flutter_svg_icons:
|
||||
dependency: "direct main"
|
||||
description:
|
||||
@@ -1565,10 +1565,10 @@ packages:
|
||||
dependency: transitive
|
||||
description:
|
||||
name: vector_graphics
|
||||
sha256: "81da85e9ca8885ade47f9685b953cb098970d11be4821ac765580a6607ea4373"
|
||||
sha256: "6409a25046024f0f8c5d8a59fec314081e81f9d436b66ca4015a8b49772bf445"
|
||||
url: "https://pub.dev"
|
||||
source: hosted
|
||||
version: "1.1.21"
|
||||
version: "1.2.0"
|
||||
vector_graphics_codec:
|
||||
dependency: transitive
|
||||
description:
|
||||
@@ -1722,7 +1722,7 @@ packages:
|
||||
source: hosted
|
||||
version: "1.1.0"
|
||||
xml:
|
||||
dependency: transitive
|
||||
dependency: "direct dev"
|
||||
description:
|
||||
name: xml
|
||||
sha256: "971043b3a0d3da28727e40ed3e0b5d18b742fa5a68665cca88e74b7876d5e025"
|
||||
|
||||
@@ -43,7 +43,7 @@ dependencies:
|
||||
flex_color_scheme: ^8.3.1
|
||||
flutter_html: ^3.0.0
|
||||
flutter_staggered_grid_view: ^0.7.0
|
||||
flutter_svg: ^2.2.4
|
||||
flutter_svg: ^2.3.0
|
||||
flutter_svg_icons: ^0.0.1
|
||||
flutter_typeahead: ^6.0.0
|
||||
flutter_zxing: ^2.2.1
|
||||
@@ -82,6 +82,7 @@ dev_dependencies:
|
||||
# Used to stub the connectivity_plus platform interface
|
||||
connectivity_plus_platform_interface: ^2.1.0
|
||||
drift_dev: ^2.33.0
|
||||
xml: ^6.6.1
|
||||
flutter_lints: ^6.0.0
|
||||
flutter_native_splash: ^2.4.7
|
||||
freezed: ^3.2.0
|
||||
|
||||
@@ -41,6 +41,9 @@ void main() {
|
||||
when(
|
||||
mockSharedPreferences.setBool(any, any),
|
||||
).thenAnswer((_) async {});
|
||||
when(
|
||||
mockSharedPreferences.setString(any, any),
|
||||
).thenAnswer((_) async {});
|
||||
when(
|
||||
mockSharedPreferences.remove(any),
|
||||
).thenAnswer((_) async {});
|
||||
@@ -120,4 +123,78 @@ void main() {
|
||||
verify(mockSharedPreferences.setBool(PREFS_USER_DARK_THEME, false)).called(1);
|
||||
});
|
||||
});
|
||||
|
||||
group('Language switcher', () {
|
||||
testWidgets('shows system option when no override set', (WidgetTester tester) async {
|
||||
await tester.pumpWidget(createSettingsScreen());
|
||||
await tester.pumpAndSettle();
|
||||
|
||||
// The dropdown is built; tap to open it.
|
||||
final dropdown = find.byKey(const ValueKey('appLanguageDropdown'));
|
||||
expect(dropdown, findsOneWidget);
|
||||
|
||||
await tester.ensureVisible(dropdown);
|
||||
await tester.pumpAndSettle();
|
||||
await tester.tap(dropdown);
|
||||
await tester.pumpAndSettle();
|
||||
|
||||
// "System language" option exists in the open menu.
|
||||
expect(find.text('System default'), findsWidgets);
|
||||
});
|
||||
|
||||
testWidgets('selecting a language persists the override', (WidgetTester tester) async {
|
||||
await tester.pumpWidget(createSettingsScreen());
|
||||
await tester.pumpAndSettle();
|
||||
|
||||
final dropdown = find.byKey(const ValueKey('appLanguageDropdown'));
|
||||
await tester.ensureVisible(dropdown);
|
||||
await tester.pumpAndSettle();
|
||||
await tester.tap(dropdown);
|
||||
await tester.pumpAndSettle();
|
||||
|
||||
// German is rendered in its native name ("Deutsch") in the menu.
|
||||
await tester.tap(find.text('Deutsch').last);
|
||||
await tester.pumpAndSettle();
|
||||
|
||||
verify(mockSharedPreferences.setString(PREFS_USER_LOCALE, 'de')).called(1);
|
||||
});
|
||||
|
||||
testWidgets('selecting "System language" clears the override', (WidgetTester tester) async {
|
||||
// Start with a stored override so the dropdown opens on German.
|
||||
when(
|
||||
mockSharedPreferences.getString(PREFS_USER_LOCALE),
|
||||
).thenAnswer((_) async => 'de');
|
||||
|
||||
await tester.pumpWidget(createSettingsScreen());
|
||||
await tester.pumpAndSettle();
|
||||
|
||||
final dropdown = find.byKey(const ValueKey('appLanguageDropdown'));
|
||||
await tester.ensureVisible(dropdown);
|
||||
await tester.pumpAndSettle();
|
||||
await tester.tap(dropdown);
|
||||
await tester.pumpAndSettle();
|
||||
|
||||
await tester.tap(find.text('System default').last);
|
||||
await tester.pumpAndSettle();
|
||||
|
||||
verify(mockSharedPreferences.remove(PREFS_USER_LOCALE)).called(1);
|
||||
});
|
||||
|
||||
testWidgets('renders supported locales in native script', (WidgetTester tester) async {
|
||||
await tester.pumpWidget(createSettingsScreen());
|
||||
await tester.pumpAndSettle();
|
||||
|
||||
final dropdown = find.byKey(const ValueKey('appLanguageDropdown'));
|
||||
await tester.ensureVisible(dropdown);
|
||||
await tester.pumpAndSettle();
|
||||
await tester.tap(dropdown);
|
||||
await tester.pumpAndSettle();
|
||||
|
||||
// Spot-check native names that sort near the top of the menu and are
|
||||
// therefore visible without scrolling the (large) dropdown overlay.
|
||||
expect(find.text('Deutsch'), findsWidgets);
|
||||
expect(find.text('English'), findsWidgets);
|
||||
expect(find.text('Català'), findsWidgets);
|
||||
});
|
||||
});
|
||||
}
|
||||
|
||||
@@ -4019,6 +4019,28 @@ class MockAppLocalizations extends _i1.Mock implements _i2.AppLocalizations {
|
||||
)
|
||||
as String);
|
||||
|
||||
@override
|
||||
String get appLanguage =>
|
||||
(super.noSuchMethod(
|
||||
Invocation.getter(#appLanguage),
|
||||
returnValue: _i3.dummyValue<String>(
|
||||
this,
|
||||
Invocation.getter(#appLanguage),
|
||||
),
|
||||
)
|
||||
as String);
|
||||
|
||||
@override
|
||||
String get appLanguageSystem =>
|
||||
(super.noSuchMethod(
|
||||
Invocation.getter(#appLanguageSystem),
|
||||
returnValue: _i3.dummyValue<String>(
|
||||
this,
|
||||
Invocation.getter(#appLanguageSystem),
|
||||
),
|
||||
)
|
||||
as String);
|
||||
|
||||
@override
|
||||
String get productNotFoundOpenFoodFacts =>
|
||||
(super.noSuchMethod(
|
||||
|
||||
@@ -18,6 +18,7 @@
|
||||
|
||||
import 'dart:convert';
|
||||
|
||||
import 'package:flutter/material.dart';
|
||||
import 'package:flutter_riverpod/flutter_riverpod.dart';
|
||||
import 'package:flutter_test/flutter_test.dart';
|
||||
import 'package:mockito/annotations.dart';
|
||||
@@ -25,6 +26,7 @@ import 'package:mockito/mockito.dart';
|
||||
import 'package:shared_preferences/shared_preferences.dart';
|
||||
import 'package:shared_preferences_platform_interface/in_memory_shared_preferences_async.dart';
|
||||
import 'package:shared_preferences_platform_interface/shared_preferences_async_platform_interface.dart';
|
||||
import 'package:wger/helpers/consts.dart';
|
||||
import 'package:wger/models/user/profile.dart';
|
||||
import 'package:wger/providers/app_settings_notifier.dart';
|
||||
import 'package:wger/providers/user_profile_notifier.dart';
|
||||
@@ -196,4 +198,123 @@ void main() {
|
||||
expect(items.isWidgetVisible(DashboardWidget.trophies), true);
|
||||
});
|
||||
});
|
||||
|
||||
group('user locale', () {
|
||||
/// Rebuilds [container] with an explicit prefs instance so the provider
|
||||
/// under test and the test assertions share the same storage. Returns
|
||||
/// that prefs instance.
|
||||
SharedPreferencesAsync freshContainerWithPrefs() {
|
||||
SharedPreferencesAsyncPlatform.instance = InMemorySharedPreferencesAsync.empty();
|
||||
final prefs = SharedPreferencesAsync();
|
||||
|
||||
container.dispose();
|
||||
container = ProviderContainer(
|
||||
overrides: [
|
||||
userProfileRepositoryProvider.overrideWithValue(mockRepo),
|
||||
appSettingsPrefsProvider.overrideWithValue(prefs),
|
||||
],
|
||||
);
|
||||
return prefs;
|
||||
}
|
||||
|
||||
/// Builds a fresh container whose [appSettingsProvider] loads from a prefs
|
||||
/// instance pre-seeded with [stored] under `PREFS_USER_LOCALE`.
|
||||
Future<AppSettings> loadWithStoredLocale(String stored) async {
|
||||
final prefs = freshContainerWithPrefs();
|
||||
await prefs.setString(PREFS_USER_LOCALE, stored);
|
||||
return container.read(appSettingsProvider.future);
|
||||
}
|
||||
|
||||
test('defaults to null when no override saved', () async {
|
||||
final settings = await container.read(appSettingsProvider.future);
|
||||
|
||||
// null means "follow system locale"
|
||||
expect(settings.userLocale, null);
|
||||
});
|
||||
|
||||
test('setUserLocale persists language-only code to prefs', () async {
|
||||
final prefs = freshContainerWithPrefs();
|
||||
await container.read(appSettingsProvider.future);
|
||||
await container.read(appSettingsProvider.notifier).setUserLocale(const Locale('pl'));
|
||||
|
||||
expect(
|
||||
container.read(appSettingsProvider).requireValue.userLocale,
|
||||
const Locale('pl'),
|
||||
);
|
||||
expect(await prefs.getString(PREFS_USER_LOCALE), 'pl');
|
||||
});
|
||||
|
||||
test('setUserLocale persists country-coded locale (pt_BR)', () async {
|
||||
final prefs = freshContainerWithPrefs();
|
||||
await container.read(appSettingsProvider.future);
|
||||
await container.read(appSettingsProvider.notifier).setUserLocale(const Locale('pt', 'BR'));
|
||||
|
||||
expect(await prefs.getString(PREFS_USER_LOCALE), 'pt_BR');
|
||||
});
|
||||
|
||||
test('setUserLocale persists script-coded locale (zh_Hant)', () async {
|
||||
final prefs = freshContainerWithPrefs();
|
||||
await container.read(appSettingsProvider.future);
|
||||
await container
|
||||
.read(appSettingsProvider.notifier)
|
||||
.setUserLocale(
|
||||
const Locale.fromSubtags(languageCode: 'zh', scriptCode: 'Hant'),
|
||||
);
|
||||
|
||||
expect(await prefs.getString(PREFS_USER_LOCALE), 'zh_Hant');
|
||||
});
|
||||
|
||||
test('setUserLocale(null) clears the stored override', () async {
|
||||
final prefs = freshContainerWithPrefs();
|
||||
await container.read(appSettingsProvider.future);
|
||||
final notifier = container.read(appSettingsProvider.notifier);
|
||||
|
||||
await notifier.setUserLocale(const Locale('de'));
|
||||
expect(await prefs.getString(PREFS_USER_LOCALE), 'de');
|
||||
|
||||
await notifier.setUserLocale(null);
|
||||
|
||||
expect(container.read(appSettingsProvider).requireValue.userLocale, null);
|
||||
expect(await prefs.getString(PREFS_USER_LOCALE), null);
|
||||
});
|
||||
|
||||
test('loads previously stored language-only locale on build', () async {
|
||||
final settings = await loadWithStoredLocale('de');
|
||||
|
||||
expect(settings.userLocale, const Locale('de'));
|
||||
});
|
||||
|
||||
test('loads previously stored country-coded locale (pt_BR)', () async {
|
||||
final settings = await loadWithStoredLocale('pt_BR');
|
||||
|
||||
expect(settings.userLocale?.languageCode, 'pt');
|
||||
expect(settings.userLocale?.countryCode, 'BR');
|
||||
});
|
||||
|
||||
test('loads previously stored script-coded locale (zh_Hant)', () async {
|
||||
final settings = await loadWithStoredLocale('zh_Hant');
|
||||
|
||||
expect(settings.userLocale?.languageCode, 'zh');
|
||||
expect(settings.userLocale?.scriptCode, 'Hant');
|
||||
});
|
||||
|
||||
test('falls back to language-only match for unknown country code', () async {
|
||||
// "pl_XX" is not a supported subtag; should fall back to "pl"
|
||||
final settings = await loadWithStoredLocale('pl_XX');
|
||||
|
||||
expect(settings.userLocale, const Locale('pl'));
|
||||
});
|
||||
|
||||
test('returns null for completely unsupported locale tag', () async {
|
||||
final settings = await loadWithStoredLocale('xx_YY');
|
||||
|
||||
expect(settings.userLocale, null);
|
||||
});
|
||||
|
||||
test('returns null for empty stored value', () async {
|
||||
final settings = await loadWithStoredLocale('');
|
||||
|
||||
expect(settings.userLocale, null);
|
||||
});
|
||||
});
|
||||
}
|
||||
|
||||
231
tool/check_locales.dart
Normal file
231
tool/check_locales.dart
Normal file
@@ -0,0 +1,231 @@
|
||||
/*
|
||||
* This file is part of wger Workout Manager <https://github.com/wger-project>.
|
||||
* Copyright (c) 2026 wger Team
|
||||
*
|
||||
* wger Workout Manager is free software: you can redistribute it and/or modify
|
||||
* it under the terms of the GNU Affero General Public License as published by
|
||||
* the Free Software Foundation, either version 3 of the License, or
|
||||
* (at your option) any later version.
|
||||
*
|
||||
* This program is distributed in the hope that it will be useful,
|
||||
* but WITHOUT ANY WARRANTY; without even the implied warranty of
|
||||
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
|
||||
* GNU Affero General Public License for more details.
|
||||
*
|
||||
* You should have received a copy of the GNU Affero General Public License
|
||||
* along with this program. If not, see <http://www.gnu.org/licenses/>.
|
||||
*/
|
||||
|
||||
library;
|
||||
|
||||
import 'dart:io';
|
||||
|
||||
import 'package:collection/collection.dart';
|
||||
import 'package:wger/l10n/language_native_names.dart';
|
||||
import 'package:xml/xml.dart';
|
||||
|
||||
const _listEq = ListEquality<String>();
|
||||
|
||||
const _arbDir = 'lib/l10n';
|
||||
const _iosPlist = 'ios/Runner/Info.plist';
|
||||
const _androidXml = 'android/app/src/main/res/xml/locales_config.xml';
|
||||
|
||||
/// Verifies that every place which enumerates the app's supported locales
|
||||
/// agrees with the canonical list derived from `lib/l10n/app_*.arb` filenames.
|
||||
///
|
||||
/// Checks:
|
||||
/// - `ios/Runner/Info.plist`
|
||||
/// - `android/app/src/main/res/xml/locales_config.xml`
|
||||
/// - `languageNativeNames` in `lib/l10n/language_native_names.dart`
|
||||
///
|
||||
/// Run `dart run tool/check_locales.dart` to check,
|
||||
/// or `dart run tool/check_locales.dart --fix` to rewrite the iOS/Android lists
|
||||
/// in place. The native-name map stays manual.
|
||||
void main(List<String> args) {
|
||||
final fix = args.contains('--fix');
|
||||
|
||||
final canonical = _readArbLocales();
|
||||
if (canonical.isEmpty) {
|
||||
stderr.writeln('No app_*.arb files found in $_arbDir');
|
||||
exit(2);
|
||||
}
|
||||
|
||||
// Dash form for iOS/Android, underscore form for Dart.
|
||||
final dashForm = canonical.map((c) => c.replaceAll('_', '-')).toList()..sort();
|
||||
final underscoreForm = [...canonical]..sort();
|
||||
|
||||
var drift = false;
|
||||
|
||||
drift |= _checkPlist(dashForm, fix: fix);
|
||||
drift |= _checkAndroidXml(dashForm, fix: fix);
|
||||
drift |= _checkLanguageDartCoverage(underscoreForm);
|
||||
|
||||
if (drift) {
|
||||
if (fix) {
|
||||
stdout.writeln('\nFixed drifted files. Re-run without --fix to verify.');
|
||||
} else {
|
||||
stderr.writeln('\nLocale lists are out of sync. Re-run with --fix to update.');
|
||||
exit(1);
|
||||
}
|
||||
} else {
|
||||
stdout.writeln('\nAll locale lists match (${canonical.length} locales).');
|
||||
}
|
||||
}
|
||||
|
||||
/// Canonical locale list from `app_<tag>.arb` filenames. Returns tags in
|
||||
/// underscore form (e.g. `pt_BR`, `zh_Hant`).
|
||||
List<String> _readArbLocales() {
|
||||
final dir = Directory(_arbDir);
|
||||
if (!dir.existsSync()) {
|
||||
return const [];
|
||||
}
|
||||
final tags = <String>[];
|
||||
for (final entity in dir.listSync()) {
|
||||
if (entity is! File) {
|
||||
continue;
|
||||
}
|
||||
final name = entity.uri.pathSegments.last;
|
||||
final match = RegExp(r'^app_(.+)\.arb$').firstMatch(name);
|
||||
if (match != null) {
|
||||
tags.add(match.group(1)!);
|
||||
}
|
||||
}
|
||||
tags.sort();
|
||||
return tags;
|
||||
}
|
||||
|
||||
bool _checkPlist(List<String> expectedDash, {required bool fix}) {
|
||||
final file = File(_iosPlist);
|
||||
if (!file.existsSync()) {
|
||||
stderr.writeln('[ios] $_iosPlist not found');
|
||||
return false;
|
||||
}
|
||||
final content = file.readAsStringSync();
|
||||
final doc = XmlDocument.parse(content);
|
||||
|
||||
// Plist structure: <plist><dict><key>foo</key><value/>...</dict></plist>.
|
||||
// Find the <key>CFBundleLocalizations</key> and take its following sibling.
|
||||
final dict = doc.rootElement.findElements('dict').firstOrNull;
|
||||
final keyNode = dict
|
||||
?.findElements('key')
|
||||
.firstWhereOrNull(
|
||||
(k) => k.innerText == 'CFBundleLocalizations',
|
||||
);
|
||||
final array = keyNode?.nextElementSibling;
|
||||
if (array == null || array.name.local != 'array') {
|
||||
stderr.writeln('[ios] CFBundleLocalizations <array> not found in $_iosPlist');
|
||||
return true;
|
||||
}
|
||||
|
||||
final actual = array.findElements('string').map((e) => e.innerText).toList()..sort();
|
||||
|
||||
if (_listEq.equals(actual, expectedDash)) {
|
||||
stdout.writeln('[ios] OK (${actual.length} locales)');
|
||||
return false;
|
||||
}
|
||||
|
||||
_reportDiff('ios', actual, expectedDash);
|
||||
|
||||
if (fix) {
|
||||
// Mutate only the <array>'s children
|
||||
array.children.clear();
|
||||
array.children.add(XmlText('\n\t\t\t'));
|
||||
for (final tag in expectedDash) {
|
||||
array.children.add(XmlElement(XmlName('string'), [], [XmlText(tag)]));
|
||||
array.children.add(XmlText('\n\t\t\t'));
|
||||
}
|
||||
// Trim the trailing inter-child indent and replace with the closing one.
|
||||
array.children.removeLast();
|
||||
array.children.add(XmlText('\n\t\t'));
|
||||
file.writeAsStringSync(doc.toXmlString());
|
||||
stdout.writeln('[ios] rewrote $_iosPlist');
|
||||
}
|
||||
return true;
|
||||
}
|
||||
|
||||
bool _checkAndroidXml(List<String> expectedDash, {required bool fix}) {
|
||||
final file = File(_androidXml);
|
||||
if (!file.existsSync()) {
|
||||
stderr.writeln('[android] $_androidXml not found');
|
||||
return false;
|
||||
}
|
||||
final doc = XmlDocument.parse(file.readAsStringSync());
|
||||
|
||||
final actual = doc.rootElement
|
||||
.findElements('locale')
|
||||
.map((e) => e.getAttribute('android:name')!)
|
||||
.toList();
|
||||
|
||||
// Convention: `en` first (matches `preferred-supported-locales: [en]` in
|
||||
// l10n.yaml), then alphabetical.
|
||||
final expectedOrdered = _enFirst(expectedDash);
|
||||
|
||||
if (_listEq.equals(actual, expectedOrdered)) {
|
||||
stdout.writeln('[android] OK (${actual.length} locales)');
|
||||
return false;
|
||||
}
|
||||
|
||||
_reportDiff('android', actual..sort(), expectedOrdered.toList()..sort());
|
||||
|
||||
if (fix) {
|
||||
final builder = XmlBuilder();
|
||||
builder.processing('xml', 'version="1.0" encoding="utf-8"');
|
||||
builder.element(
|
||||
'locale-config',
|
||||
namespaces: {'http://schemas.android.com/apk/res/android': 'android'},
|
||||
nest: () {
|
||||
for (final tag in expectedOrdered) {
|
||||
builder.element('locale', attributes: {'android:name': tag});
|
||||
}
|
||||
},
|
||||
);
|
||||
file.writeAsStringSync(
|
||||
builder.buildDocument().toXmlString(pretty: true, indent: ' '),
|
||||
);
|
||||
stdout.writeln('[android] rewrote $_androidXml');
|
||||
}
|
||||
return true;
|
||||
}
|
||||
|
||||
/// Returns the list with `en` first (if present), the rest alphabetically.
|
||||
List<String> _enFirst(List<String> tags) {
|
||||
final rest = [...tags.where((t) => t != 'en')]..sort();
|
||||
return tags.contains('en') ? ['en', ...rest] : rest;
|
||||
}
|
||||
|
||||
/// The native-name map is hand-curated, since this script doesn't know how
|
||||
/// to spell `Українська`, we can only check coverage, not auto-fix it.
|
||||
bool _checkLanguageDartCoverage(List<String> expectedUnderscore) {
|
||||
final actual = languageNativeNames.keys.toSet();
|
||||
final expected = expectedUnderscore.toSet();
|
||||
|
||||
final missing = expected.difference(actual).toList()..sort();
|
||||
final extra = actual.difference(expected).toList()..sort();
|
||||
|
||||
if (missing.isEmpty && extra.isEmpty) {
|
||||
stdout.writeln('[dart] OK (${actual.length} entries)');
|
||||
return false;
|
||||
}
|
||||
|
||||
if (missing.isNotEmpty) {
|
||||
stderr.writeln('[dart] missing native-name entries: ${missing.join(', ')}');
|
||||
stderr.writeln(' add them by hand to lib/l10n/language_native_names.dart');
|
||||
}
|
||||
if (extra.isNotEmpty) {
|
||||
stderr.writeln('[dart] stale native-name entries (no matching .arb): ${extra.join(', ')}');
|
||||
}
|
||||
return true;
|
||||
}
|
||||
|
||||
void _reportDiff(String label, List<String> actual, List<String> expected) {
|
||||
final actualSet = actual.toSet();
|
||||
final expectedSet = expected.toSet();
|
||||
final missing = expectedSet.difference(actualSet).toList()..sort();
|
||||
final extra = actualSet.difference(expectedSet).toList()..sort();
|
||||
if (missing.isNotEmpty) {
|
||||
stderr.writeln('[$label] missing: ${missing.join(', ')}');
|
||||
}
|
||||
if (extra.isNotEmpty) {
|
||||
stderr.writeln('[$label] extra: ${extra.join(', ')}');
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user