Files
minhthu/lib/core/utils/text_utils.dart
Phuoc Nguyen c12869b01f asdasdasd
2025-10-29 16:12:37 +07:00

87 lines
2.8 KiB
Dart

/// Utility functions for text processing
class TextUtils {
/// Convert Vietnamese characters to English (non-accented) characters
/// Example: "Tuấn" -> "tuan", "Hồ Chí Minh" -> "ho chi minh"
static String removeVietnameseAccents(String text) {
if (text.isEmpty) return text;
// Convert to lowercase for consistent comparison
String result = text.toLowerCase();
// Map of Vietnamese characters to their non-accented equivalents
const vietnameseMap = {
// a with accents
'á': 'a', 'à': 'a', '': 'a', 'ã': 'a', '': 'a',
'ă': 'a', '': 'a', '': 'a', '': 'a', '': 'a', '': 'a',
'â': 'a', '': 'a', '': 'a', '': 'a', '': 'a', '': 'a',
// e with accents
'é': 'e', 'è': 'e', '': 'e', '': 'e', '': 'e',
'ê': 'e', 'ế': 'e', '': 'e', '': 'e', '': 'e', '': 'e',
// i with accents
'í': 'i', 'ì': 'i', '': 'i', 'ĩ': 'i', '': 'i',
// o with accents
'ó': 'o', 'ò': 'o', '': 'o', 'õ': 'o', '': 'o',
'ô': 'o', '': 'o', '': 'o', '': 'o', '': 'o', '': 'o',
'ơ': 'o', '': 'o', '': 'o', '': 'o', '': 'o', '': 'o',
// u with accents
'ú': 'u', 'ù': 'u', '': 'u', 'ũ': 'u', '': 'u',
'ư': 'u', '': 'u', '': 'u', '': 'u', '': 'u', '': 'u',
// y with accents
'ý': 'y', '': 'y', '': 'y', '': 'y', '': 'y',
// d with stroke
'đ': 'd',
};
// Replace each Vietnamese character with its non-accented equivalent
vietnameseMap.forEach((vietnamese, english) {
result = result.replaceAll(vietnamese, english);
});
return result;
}
/// Normalize text for search (lowercase + remove accents)
static String normalizeForSearch(String text) {
return removeVietnameseAccents(text.toLowerCase().trim());
}
/// Check if a text contains a search term (Vietnamese-aware, case-insensitive)
///
/// Example:
/// ```dart
/// containsVietnameseSearch("Nguyễn Văn Tuấn", "tuan") // returns true
/// containsVietnameseSearch("tuan@example.com", "TUAN") // returns true
/// ```
static bool containsVietnameseSearch(String text, String searchTerm) {
if (searchTerm.isEmpty) return true;
if (text.isEmpty) return false;
final normalizedText = normalizeForSearch(text);
final normalizedSearch = normalizeForSearch(searchTerm);
return normalizedText.contains(normalizedSearch);
}
/// Check if any of the provided texts contains the search term
static bool containsVietnameseSearchInAny(
List<String> texts,
String searchTerm,
) {
if (searchTerm.isEmpty) return true;
for (final text in texts) {
if (containsVietnameseSearch(text, searchTerm)) {
return true;
}
}
return false;
}
}