-
Notifications
You must be signed in to change notification settings - Fork 3.9k
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
feat(ui): generate labels from .arb (#9340)
- Loading branch information
Showing
52 changed files
with
14,649 additions
and
0 deletions.
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,30 @@ | ||
# Miscellaneous | ||
*.class | ||
*.log | ||
*.pyc | ||
*.swp | ||
.DS_Store | ||
.atom/ | ||
.buildlog/ | ||
.history | ||
.svn/ | ||
migrate_working_dir/ | ||
|
||
# IntelliJ related | ||
*.iml | ||
*.ipr | ||
*.iws | ||
.idea/ | ||
|
||
# The .vscode folder contains launch configuration and tasks you configure in | ||
# VS Code which you may wish to be included in version control, so this line | ||
# is commented out by default. | ||
#.vscode/ | ||
|
||
# Flutter/Dart/Pub related | ||
# Libraries should not include pubspec.lock, per https://dart.dev/guides/libraries/private-files#pubspeclock. | ||
/pubspec.lock | ||
**/doc/api/ | ||
.dart_tool/ | ||
.packages | ||
build/ |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,10 @@ | ||
# This file tracks properties of this Flutter project. | ||
# Used by Flutter tool to assess capabilities and perform upgrades etc. | ||
# | ||
# This file should be version controlled and should not be manually edited. | ||
|
||
version: | ||
revision: f1875d570e39de09040c8f79aa13cc56baab8db1 | ||
channel: stable | ||
|
||
project_type: package |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,7 @@ | ||
## 1.0.0-dev.0 | ||
|
||
- Bump "firebase_ui_localizations" to `1.0.0-dev.0`. | ||
|
||
## 0.0.1 | ||
|
||
* TODO: Describe initial release. |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,26 @@ | ||
Copyright 2017, the Chromium project authors. All rights reserved. | ||
Redistribution and use in source and binary forms, with or without | ||
modification, are permitted provided that the following conditions are | ||
met: | ||
|
||
* Redistributions of source code must retain the above copyright | ||
notice, this list of conditions and the following disclaimer. | ||
* Redistributions in binary form must reproduce the above | ||
copyright notice, this list of conditions and the following | ||
disclaimer in the documentation and/or other materials provided | ||
with the distribution. | ||
* Neither the name of Google Inc. nor the names of its | ||
contributors may be used to endorse or promote products derived | ||
from this software without specific prior written permission. | ||
|
||
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS | ||
"AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT | ||
LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR | ||
A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT | ||
OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, | ||
SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT | ||
LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, | ||
DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY | ||
THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT | ||
(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE | ||
OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,61 @@ | ||
# Localization | ||
|
||
Firebase UI for Flutter supports localization, so every single label can be customized. | ||
|
||
## Installation | ||
|
||
```yaml | ||
dependencies: | ||
flutter_localizations: | ||
sdk: flutter | ||
firebase_ui_localizations: ^1.0.0 | ||
``` | ||
|
||
## Usage | ||
|
||
If your app supports only a single language, and you want to override labels – you will need to provide a custom class that implements [`DefaultLocalizations`](https://pub.dev/documentation/firebase_ui_localizations/latest/DefaultLocalizations-class.html), | ||
for example: | ||
|
||
```dart | ||
import 'package:flutter_localizations/flutter_localizations.dart'; | ||
import 'package:firebase_ui_localizations/firebase_ui_localizations.dart'; | ||
class LabelOverrides extends DefaultLocalizations { | ||
const LabelOverrides(); | ||
@override | ||
String get emailInputLabel => 'Enter your email'; | ||
@override | ||
String get passwordInputLabel => 'Enter your password'; | ||
} | ||
``` | ||
|
||
Once created, pass the instance of `LabelOverrides` to the `localizationsDelegates` list in your `MaterialApp`/`CupertinoApp`: | ||
|
||
```dart | ||
class MyApp extends StatelessWidget { | ||
@override | ||
Widget build(BuildContext context) { | ||
return MaterialApp( | ||
localizationsDelegates: [ | ||
// Creates an instance of FirebaseUILocalizationDelegate with overridden labels | ||
FirebaseUILocalizations.withDefaultOverrides(const LabelOverrides()), | ||
// Delegates below take care of built-in flutter widgets | ||
GlobalMaterialLocalizations.delegate, | ||
GlobalWidgetsLocalizations.delegate, | ||
// This delegate is required to provide the labels that are not overridden by LabelOverrides | ||
FirebaseUILocalizations.delegate, | ||
], | ||
// ... | ||
); | ||
} | ||
} | ||
``` | ||
|
||
If you need to support multiple languages – follow the [official Flutter localization guide](https://docs.flutter.dev/development/accessibility-and-localization/internationalization#an-alternative-class-for-the-apps-localized-resources) | ||
and make sure that your custom delegate extends `LocalizationsDelegate<FirebaseUILocalizations>`. | ||
|
||
> Note: check out [API reference](https://pub.dev/documentation/firebase_ui_localizations/latest/FlutterFireUILocalizationLabels-class.html) to learn what labels are used by specific widgets |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,4 @@ | ||
include: package:flutter_lints/flutter.yaml | ||
|
||
# Additional information about this file can be found at | ||
# https://dart.dev/guides/language/analysis-options |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,194 @@ | ||
import 'dart:convert'; | ||
import 'dart:io'; | ||
import 'package:path/path.dart' as path; | ||
|
||
late String cwd; | ||
late Directory outDir; | ||
|
||
void main() async { | ||
cwd = Directory.current.path; | ||
final l10nSrc = Directory(path.join(cwd, 'lib', 'l10n')); | ||
outDir = Directory(path.join(cwd, 'lib', 'src')); | ||
|
||
if (!outDir.existsSync()) { | ||
outDir.createSync(recursive: true); | ||
} | ||
|
||
final readFutures = await l10nSrc.list().map((event) { | ||
final file = File(event.path); | ||
return file.openRead().transform(const Utf8Decoder()).toList(); | ||
}).toList(); | ||
|
||
final sources = await Future.wait(readFutures); | ||
|
||
final labelsByLocale = sources.fold<Map<String, dynamic>>({}, (acc, lines) { | ||
final fullSrc = lines.join(); | ||
final arbJson = jsonDecode(fullSrc); | ||
final localeString = arbJson['@@locale']; | ||
|
||
final parsed = localeString.split('_'); | ||
|
||
return { | ||
...acc, | ||
parsed[0]: { | ||
...(acc[parsed[0]] ?? {}), | ||
if (parsed.length > 1) parsed[1]: arbJson else 'default': arbJson, | ||
} | ||
}; | ||
}); | ||
|
||
final genOps = labelsByLocale.entries.map((entry) { | ||
if (entry.value.length == 1) { | ||
return [ | ||
generateLocalizationsClass( | ||
locale: entry.key, | ||
arb: entry.value['default'], | ||
) | ||
]; | ||
} | ||
|
||
return [ | ||
generateLocalizationsClass( | ||
locale: entry.key, | ||
arb: entry.value['default'], | ||
), | ||
...entry.value.entries | ||
.where((element) => element.key != 'default') | ||
.map((e) { | ||
return generateLocalizationsClass( | ||
locale: entry.key, | ||
countryCode: e.key, | ||
arb: e.value, | ||
); | ||
}).toList(), | ||
]; | ||
}).expand((element) => element); | ||
|
||
await Future.wait([...genOps.cast<Future>()]); | ||
await generateLanguagesList(labelsByLocale); | ||
Process.runSync('dart', ['format', outDir.path]); | ||
} | ||
|
||
bool isLabelEntry(MapEntry<String, dynamic> entry) { | ||
return !entry.key.startsWith('@'); | ||
} | ||
|
||
String dartFilename(String locale, [String? countryCode]) { | ||
return '$locale' | ||
'${countryCode != null ? '_${countryCode.toLowerCase()}' : ''}' | ||
'.dart'; | ||
} | ||
|
||
String dartClassName(String locale, [String? countryCode]) { | ||
return '${locale.capitalize()}' | ||
'${countryCode?.capitalize() ?? ''}Localizations'; | ||
} | ||
|
||
Future<void> generateLocalizationsClass({ | ||
required String locale, | ||
required Map<String, dynamic> arb, | ||
String? countryCode, | ||
}) async { | ||
final filename = dartFilename(locale, countryCode); | ||
final outFile = File(path.join(outDir.path, 'lang', filename)); | ||
|
||
if (!outFile.existsSync()) { | ||
outFile.createSync(recursive: true); | ||
} | ||
|
||
final out = outFile.openWrite(); | ||
|
||
out.writeln("import '../default_localizations.dart';"); | ||
|
||
final labels = arb.entries.where(isLabelEntry).map((e) { | ||
final meta = arb['@${e.key}'] ?? {}; | ||
|
||
return Label( | ||
key: e.key, | ||
translation: e.value, | ||
description: meta['description'], | ||
); | ||
}).toList(); | ||
|
||
out.writeln(); | ||
|
||
final className = dartClassName(locale, countryCode); | ||
|
||
out.writeln('class $className extends FirebaseUILocalizationLabels {'); | ||
out.writeln(' const $className();'); | ||
|
||
for (var label in labels) { | ||
final escapedTranslation = jsonEncode(label.translation); | ||
|
||
out.writeln(); | ||
out.writeln(' @override'); | ||
out.writeln(' String get ${label.key} => $escapedTranslation;'); | ||
} | ||
|
||
out.writeln('}'); | ||
|
||
await out.flush(); | ||
await out.close(); | ||
} | ||
|
||
Future<void> generateLanguagesList(Map<String, dynamic> arb) async { | ||
final outFile = File(path.join(outDir.path, 'all_languages.dart')); | ||
|
||
if (!outFile.existsSync()) { | ||
outFile.createSync(recursive: true); | ||
} | ||
|
||
final out = outFile.openWrite(); | ||
out.writeln('import "./default_localizations.dart";'); | ||
out.writeln(); | ||
|
||
for (var entry in arb.entries) { | ||
final locale = entry.key; | ||
final countryCodes = entry.value.keys.where((e) => e != 'default').toList(); | ||
|
||
final filename = dartFilename(locale); | ||
out.writeln("import 'lang/$filename';"); | ||
|
||
for (var countryCode in countryCodes) { | ||
out.writeln("import 'lang/${dartFilename(locale, countryCode)}';"); | ||
} | ||
} | ||
|
||
out.writeln(); | ||
out.writeln('final localizations = <String, FirebaseUILocalizationLabels>{'); | ||
|
||
for (var entry in arb.entries) { | ||
final locale = entry.key; | ||
final countryCodes = entry.value.keys.where((e) => e != 'default').toList(); | ||
|
||
out.writeln(" '$locale': const ${dartClassName(locale)}(),"); | ||
|
||
for (var countryCode in countryCodes) { | ||
final key = '${locale}_${countryCode.toLowerCase()}'; | ||
out.writeln(" '$key': const ${dartClassName(locale, countryCode)}(),"); | ||
} | ||
} | ||
|
||
out.writeln('};'); | ||
|
||
await out.flush(); | ||
await out.close(); | ||
} | ||
|
||
extension StringExtension on String { | ||
String capitalize() { | ||
return "${this[0].toUpperCase()}${substring(1)}"; | ||
} | ||
} | ||
|
||
class Label { | ||
final String key; | ||
final String translation; | ||
final String? description; | ||
|
||
Label({ | ||
required this.key, | ||
required this.translation, | ||
this.description, | ||
}); | ||
} |
5 changes: 5 additions & 0 deletions
5
packages/firebase_ui_localizations/lib/firebase_ui_localizations.dart
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,5 @@ | ||
export 'src/l10n.dart' | ||
show FirebaseUILocalizations, FirebaseUILocalizationDelegate; | ||
|
||
export 'src/default_localizations.dart' | ||
show DefaultLocalizations, FirebaseUILocalizationLabels; |
Oops, something went wrong.