Skip to content
This repository has been archived by the owner on Nov 7, 2023. It is now read-only.

Commit

Permalink
refactor(translation): better locale parsing
Browse files Browse the repository at this point in the history
  • Loading branch information
zyrouge committed Oct 21, 2021
1 parent 0333949 commit 2eaa2ce
Show file tree
Hide file tree
Showing 13 changed files with 128 additions and 56 deletions.
49 changes: 48 additions & 1 deletion lib/core/models/translations.dart
Original file line number Diff line number Diff line change
@@ -1,7 +1,54 @@
import 'package:flutter/material.dart';
import 'package:utilx/utilities/countries.dart';
import 'package:utilx/utilities/languages.dart';

class TranslationLocale {
TranslationLocale(this.code, [this.country]);

factory TranslationLocale.parse(final String locale) {
final RegExpMatch match = RegExp('([^_]+)(_(.*?))?').firstMatch(locale)!;
final LanguageCodes lang = LanguageUtils.languageCodeMap[match.group(1)!]!;
final LanguageCountries? country = match.groupCount == 3
? LanguageCountryUtils.nameCodeMap[match.group(3)!]
: null;

return TranslationLocale(lang, country);
}

final LanguageCodes code;
final LanguageCountries? country;

int compare(final TranslationLocale locale) {
int threshold = 0;

if (locale.code == code) {
threshold += 1;
}

if (locale.country == country) {
threshold += 2;
}

return threshold;
}

@override
String toString() =>
<String>[code.name, if (country != null) country!.country].join('_');

@override
bool operator ==(final Object other) =>
other is TranslationLocale &&
code == other.code &&
country == other.country;

@override
int get hashCode => Object.hash(code, country);
}

abstract class TranslationSentences {
LanguageCodes get code;
TranslationLocale get locale;
TextDirection get textDirection => TextDirection.ltr;

String home();
String search();
Expand Down
6 changes: 0 additions & 6 deletions lib/main.dart
Original file line number Diff line number Diff line change
@@ -1,13 +1,11 @@
import 'package:flutter/material.dart';
import 'package:utilx/utilities/languages.dart' show LanguageName;
import './plugins/app_lifecycle.dart';
import './plugins/database/database.dart';
import './plugins/database/schemas/settings/settings.dart' as settings_schema;
import './plugins/helpers/logger.dart';
import './plugins/helpers/ui.dart';
import './plugins/router.dart';
import './plugins/state.dart';
import './plugins/translator/translator.dart';

Future<void> main(final List<String> args) async {
try {
Expand Down Expand Up @@ -59,10 +57,6 @@ class _MainAppState extends State<MainApp> {
useSystemPreferredTheme = current.useSystemPreferredTheme;
useDarkMode = current.useDarkMode;
});

if (current.locale != null && current.locale != Translator.t.code.code) {
Translator.setLanguage(current.locale!);
}
}

@override
Expand Down
6 changes: 3 additions & 3 deletions lib/pages/anime_page/anime_page.dart
Original file line number Diff line number Diff line change
Expand Up @@ -126,7 +126,7 @@ class _PageState extends State<Page>

info = await extractor.getInfo(
args.src,
locale?.code ?? extractor.defaultLocale,
locale?.name ?? extractor.defaultLocale,
);

await DataBox.cache.put(
Expand Down Expand Up @@ -279,11 +279,11 @@ class _PageState extends State<Page>
...info!.availableLocales.map(
(final String x) {
final LanguageCodes groupVal =
LanguageUtils.codeLangaugeMap[info!.locale] ??
LanguageUtils.languageCodeMap[info!.locale] ??
LanguageCodes.en;

final LanguageCodes lang =
LanguageUtils.codeLangaugeMap[x] ?? LanguageCodes.en;
LanguageUtils.languageCodeMap[x] ?? LanguageCodes.en;

return Material(
type: MaterialType.transparency,
Expand Down
6 changes: 3 additions & 3 deletions lib/pages/manga_page/manga_page.dart
Original file line number Diff line number Diff line change
Expand Up @@ -163,7 +163,7 @@ class _PageState extends State<Page>

info = await extractor.getInfo(
args.src,
locale?.code ?? extractor.defaultLocale,
locale?.name ?? extractor.defaultLocale,
);

await DataBox.cache.put(
Expand Down Expand Up @@ -366,11 +366,11 @@ class _PageState extends State<Page>
...info!.availableLocales.map(
(final String x) {
final LanguageCodes groupVal =
LanguageUtils.codeLangaugeMap[info!.locale] ??
LanguageUtils.languageCodeMap[info!.locale] ??
LanguageCodes.en;

final LanguageCodes lang =
LanguageUtils.codeLangaugeMap[x] ?? LanguageCodes.en;
LanguageUtils.languageCodeMap[x] ?? LanguageCodes.en;

return Material(
type: MaterialType.transparency,
Expand Down
3 changes: 1 addition & 2 deletions lib/pages/search_page/search_page.dart
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,6 @@ import 'package:animations/animations.dart';
import 'package:collection/collection.dart';
import 'package:extensions/extensions.dart' as extensions;
import 'package:flutter/material.dart';
import 'package:utilx/utilities/languages.dart';
import '../../components/network_image_fallback.dart';
import '../../core/extensions.dart';
import '../../core/models/page_args/anime_page.dart' as anime_page;
Expand Down Expand Up @@ -184,7 +183,7 @@ class _PageState extends State<Page> with DidLoadStater {
final List<extensions.SearchInfo> searches =
await currentPlugin!.plugin.search(
textController.text,
Translator.t.code.code,
Translator.t.locale.code.name,
);

if (mounted) {
Expand Down
7 changes: 3 additions & 4 deletions lib/pages/settings_page/setting_labels/preference.dart
Original file line number Diff line number Diff line change
Expand Up @@ -15,11 +15,10 @@ List<Widget> getPreference(
title: Translator.t.language(),
dialogTitle: Translator.t.chooseLanguage(),
icon: Icons.language,
value: settings.locale ?? Translator.t.code.code,
value: settings.locale ?? Translator.t.locale.code.name,
labels: <String, String>{
for (final TranslationSentences lang
in Translator.translations.values)
lang.code.code: lang.code.language,
for (final TranslationSentences lang in Translator.translations)
lang.locale.code.name: lang.locale.code.language,
},
onChanged: (final String val) async {
settings.locale = val;
Expand Down
19 changes: 11 additions & 8 deletions lib/plugins/app_lifecycle.dart
Original file line number Diff line number Diff line change
Expand Up @@ -12,6 +12,7 @@ import './translator/translator.dart';
import './video_player/video_player.dart';
import '../config.dart';
import '../core/extensions.dart';
import '../core/models/translations.dart';
import '../core/trackers/trackers.dart';

// TODO: Pending at https://github.com/flutter/flutter/issues/30735
Expand Down Expand Up @@ -103,14 +104,16 @@ abstract class AppLifecycle {
);
}

Translator.setLanguage(
DataStore.settings.locale != null &&
Translator.isSupportedLocale(
DataStore.settings.locale!,
)
? DataStore.settings.locale!
: Translator.getSupportedLocale(),
);
final TranslationSentences? settingsLocale =
DataStore.settings.locale != null
? Translator.tryGetTranslation(DataStore.settings.locale!)
: null;
if (settingsLocale == null) {
DataStore.settings.locale = null;
await DataStore.settings.save();
}

Translator.t = settingsLocale ?? Translator.getSupportedTranslation();

Deeplink.link = ProtocolHandler.fromArgs(args);
preready = true;
Expand Down
2 changes: 1 addition & 1 deletion lib/plugins/translator/translations/en.dart
Original file line number Diff line number Diff line change
Expand Up @@ -3,7 +3,7 @@ import '../../../core/models/translations.dart';

class Sentences extends TranslationSentences {
@override
LanguageCodes get code => LanguageCodes.en;
TranslationLocale get locale => TranslationLocale(LanguageCodes.en);

@override
String home() => 'Home';
Expand Down
5 changes: 4 additions & 1 deletion lib/plugins/translator/translations/pt_br.dart
Original file line number Diff line number Diff line change
@@ -1,9 +1,12 @@
import 'package:utilx/utilities/countries.dart';
import 'package:utilx/utilities/languages.dart';
import '../../../core/models/translations.dart';
import 'en.dart' as en;

class Sentences extends en.Sentences {
@override
LanguageCodes get code => LanguageCodes.pt;
TranslationLocale get locale =>
TranslationLocale(LanguageCodes.pt, LanguageCountries.br);

@override
String home() => 'Menu';
Expand Down
40 changes: 21 additions & 19 deletions lib/plugins/translator/translator.dart
Original file line number Diff line number Diff line change
Expand Up @@ -5,34 +5,36 @@ import './translations/pt_br.dart' as pt_br;
import '../../core/models/translations.dart';

abstract class Translator {
static final List<TranslationSentences> _availableTranslations =
<TranslationSentences>[
static final List<TranslationSentences> translations = <TranslationSentences>[
en.Sentences(),
pt_br.Sentences(),
];

static Map<String, TranslationSentences> translations =
<String, TranslationSentences>{
for (final TranslationSentences lang in _availableTranslations)
lang.code.code: lang,
};

static late TranslationSentences t;

static void setLanguage(final String language) {
final TranslationSentences? lang = translations[language];
if (lang == null) {
throw ArgumentError('Unknown language: $language');
static TranslationSentences? tryGetTranslation(final String _locale) {
final TranslationLocale locale = TranslationLocale.parse(_locale);

TranslationSentences? translation;
int threshold = 0;

for (final TranslationSentences x in translations) {
final int nThresh = x.locale.compare(locale);
if (nThresh > threshold) {
translation = x;
threshold = nThresh;
}
}

t = lang;
return translation;
}

static bool isSupportedLocale(final String locale) =>
translations[locale] != null;
static TranslationSentences getDefaultTranslation() =>
translations.firstWhere(
(final TranslationSentences x) =>
x.locale == TranslationLocale(LanguageCodes.en),
);

static String getSupportedLocale() {
final String sysLang = Platform.localeName.split('_')[0];
return isSupportedLocale(sysLang) ? sysLang : LanguageCodes.en.code;
}
static TranslationSentences getSupportedTranslation() =>
tryGetTranslation(Platform.localeName) ?? getDefaultTranslation();
}
2 changes: 1 addition & 1 deletion packages/extensions/lib/hetu/helpers/languages.dart
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
import 'package:utilx/utilities/languages.dart';

final List<String> _languages = LanguageUtils.codeLangaugeMap.keys.toList();
final List<String> _languages = LanguageUtils.languageCodeMap.keys.toList();

bool isValidLanguages(final String language) => _languages.contains(language);

Expand Down
27 changes: 27 additions & 0 deletions packages/utilx/lib/utilities/countries.dart
Original file line number Diff line number Diff line change
@@ -0,0 +1,27 @@
enum LanguageCountries {
br,
}

extension LanguageCountriesUtils on LanguageCountries {
String get name => name.toUpperCase();
String get country => LanguageCountryUtils.codeNameMap[this]!;
}

abstract class LanguageCountryUtils {
static Map<LanguageCountries, String> codeNameMap =
<LanguageCountries, String>{
LanguageCountries.br: 'Brazil',
};

static final Map<String, LanguageCountries> nameCodeMap =
LanguageCountries.values
.asMap()
.map(
(final int k, final LanguageCountries v) =>
MapEntry<String, LanguageCountries>(
v.name,
v,
),
)
.cast<String, LanguageCountries>();
}
12 changes: 5 additions & 7 deletions packages/utilx/lib/utilities/languages.dart
Original file line number Diff line number Diff line change
Expand Up @@ -184,14 +184,12 @@ enum LanguageCodes {
zu,
}

extension LanguageName on LanguageCodes {
String get code => toString().split('.').last;
String get language => LanguageUtils.languageNameMap[this]!;
extension LanguageCodeUtils on LanguageCodes {
String get language => LanguageUtils.codeNameMap[this]!;
}

abstract class LanguageUtils {
static const Map<LanguageCodes, String> languageNameMap =
<LanguageCodes, String>{
static const Map<LanguageCodes, String> codeNameMap = <LanguageCodes, String>{
LanguageCodes.aa: 'Afar',
LanguageCodes.ab: 'Abkhazian',
LanguageCodes.af: 'Afrikaans',
Expand Down Expand Up @@ -379,11 +377,11 @@ abstract class LanguageUtils {
LanguageCodes.zu: 'Zulu'
};

static final Map<String, LanguageCodes> codeLangaugeMap = LanguageCodes.values
static final Map<String, LanguageCodes> languageCodeMap = LanguageCodes.values
.asMap()
.map(
(final int k, final LanguageCodes v) => MapEntry<String, LanguageCodes>(
v.code,
v.name,
v,
),
)
Expand Down

0 comments on commit 2eaa2ce

Please sign in to comment.