Add modular story library and shared-progress translations

This commit is contained in:
Hadrian Burkhardt
2026-11-03 17:15:15 +01:00
parent 5b9a76fb53
commit d45cd0698a
30 changed files with 2694 additions and 495 deletions
+114
View File
@@ -0,0 +1,114 @@
import 'dart:convert';
import 'package:flutter/services.dart';
/// UI messages use their English source as catalogue keys. Numbered slots in
/// dynamic messages are preserved by translators and can be reordered.
class TranslationCatalog {
const TranslationCatalog(this.languages, this.messages);
static const english = TranslationCatalog({'en': 'English'}, {});
final Map<String, String> languages;
final Map<String, Map<String, String>> messages;
static Future<TranslationCatalog> load(AssetBundle bundle) async {
final index = jsonDecode(
await bundle.loadString('assets/locales/catalog.json'),
) as Map;
final messages = <String, Map<String, String>>{};
final languages = <String, String>{};
for (final entry in index.entries) {
languages[entry.key] = entry.value['label'];
messages[entry.key] = Map<String, String>.from(
jsonDecode(await bundle.loadString(entry.value['asset'])),
);
for (final message in messages[entry.key]!.entries) {
Set<String> slots(String text) =>
RegExp(r'\{\d+\}').allMatches(text).map((m) => m[0]!).toSet();
if (slots(message.key).difference(slots(message.value)).isNotEmpty ||
slots(message.value).difference(slots(message.key)).isNotEmpty) {
throw FormatException(
'Translation placeholders differ: ${entry.key}: ${message.key}',
);
}
}
}
return TranslationCatalog(languages, messages);
}
MessageTranslator translator(
String locale, {
Map<String, String> overrides = const {},
}) {
final tag = locale.replaceAll('_', '-').toLowerCase();
return MessageTranslator({
...?messages['en'],
...?messages[tag.split('-').first],
...?messages[tag],
...overrides,
});
}
String text(
String source,
String locale, {
Map<String, String> overrides = const {},
}) => translator(locale, overrides: overrides).text(source);
}
class MessageTranslator {
MessageTranslator(this.messages) {
for (final entry in messages.entries) {
if (entry.key == entry.value) continue;
final slots = _slots.allMatches(entry.key).toList();
if (slots.isEmpty) continue;
var pattern = '^', end = 0;
for (final slot in slots) {
pattern += RegExp.escape(entry.key.substring(end, slot.start));
pattern += r'([\s\S]*?)';
end = slot.end;
}
pattern += '${RegExp.escape(entry.key.substring(end))}\$';
_templates.add(
_Template(
RegExp(pattern),
entry.value,
slots.map((m) => m[1]!).toList(),
entry.key.length - slots.fold(0, (n, m) => n + m[0]!.length),
),
);
}
// "Row {0}, column {1}" must match before the shorter "Row {0}".
_templates.sort((a, b) => b.specificity.compareTo(a.specificity));
}
static final _slots = RegExp(r'\{(\d+)\}');
final Map<String, String> messages;
final List<_Template> _templates = [];
String text(String source) => _text(source, 0);
String _text(String source, int depth) {
final exact = messages[source];
if (exact != null && exact != source) return exact;
if (depth > 4) return source;
for (final template in _templates) {
final match = template.pattern.firstMatch(source);
if (match == null) continue;
final values = <String, String>{
for (var i = 0; i < template.slots.length; i++)
template.slots[i]: _text(match[i + 1]!, depth + 1),
};
return template.value.replaceAllMapped(
_slots,
(m) => values[m[1]] ?? m[0]!,
);
}
return source;
}
}
class _Template {
const _Template(this.pattern, this.value, this.slots, this.specificity);
final RegExp pattern;
final String value;
final List<String> slots;
final int specificity;
}