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 languages; final Map> messages; static Future load(AssetBundle bundle) async { final index = jsonDecode( await bundle.loadString('assets/locales/catalog.json'), ) as Map; final messages = >{}; final languages = {}; for (final entry in index.entries) { languages[entry.key] = entry.value['label']; messages[entry.key] = Map.from( jsonDecode(await bundle.loadString(entry.value['asset'])), ); for (final message in messages[entry.key]!.entries) { Set 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 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 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 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 = { 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 slots; final int specificity; }