69 lines
1.8 KiB
Dart
69 lines
1.8 KiB
Dart
|
|
String formatPhoneForDisplay(String? rawPhone) {
|
||
|
|
final normalized = _normalizePhone(rawPhone);
|
||
|
|
if (normalized == null) {
|
||
|
|
return rawPhone?.trim() ?? '';
|
||
|
|
}
|
||
|
|
|
||
|
|
if (normalized.startsWith('+86') && normalized.length == 14) {
|
||
|
|
final local = normalized.substring(3);
|
||
|
|
return '${local.substring(0, 3)}****${local.substring(7)}';
|
||
|
|
}
|
||
|
|
|
||
|
|
if (!normalized.startsWith('+')) {
|
||
|
|
return normalized;
|
||
|
|
}
|
||
|
|
final digits = normalized.substring(1);
|
||
|
|
final countryCode = _detectCountryCode(digits);
|
||
|
|
if (countryCode == null) {
|
||
|
|
return normalized;
|
||
|
|
}
|
||
|
|
final localNumber = digits.substring(countryCode.length);
|
||
|
|
if (localNumber.length <= 4) {
|
||
|
|
return '+$countryCode $localNumber';
|
||
|
|
}
|
||
|
|
final tail = localNumber.substring(localNumber.length - 4);
|
||
|
|
return '+$countryCode ****$tail';
|
||
|
|
}
|
||
|
|
|
||
|
|
String? _normalizePhone(String? rawPhone) {
|
||
|
|
if (rawPhone == null) {
|
||
|
|
return null;
|
||
|
|
}
|
||
|
|
var phone = rawPhone.trim();
|
||
|
|
for (final separator in const [' ', '-', '(', ')']) {
|
||
|
|
phone = phone.replaceAll(separator, '');
|
||
|
|
}
|
||
|
|
if (phone.isEmpty) {
|
||
|
|
return null;
|
||
|
|
}
|
||
|
|
if (phone.startsWith('00') && phone.length > 2) {
|
||
|
|
phone = '+${phone.substring(2)}';
|
||
|
|
}
|
||
|
|
if (!phone.startsWith('+') && RegExp(r'^\d+$').hasMatch(phone)) {
|
||
|
|
phone = '+$phone';
|
||
|
|
}
|
||
|
|
return phone;
|
||
|
|
}
|
||
|
|
|
||
|
|
String? _detectCountryCode(String digits) {
|
||
|
|
const knownCodes = ['86', '1', '44', '81', '65', '33'];
|
||
|
|
for (final code in knownCodes) {
|
||
|
|
if (digits.startsWith(code) && digits.length > code.length + 3) {
|
||
|
|
return code;
|
||
|
|
}
|
||
|
|
}
|
||
|
|
for (int length = 3; length >= 1; length--) {
|
||
|
|
if (length >= digits.length) {
|
||
|
|
continue;
|
||
|
|
}
|
||
|
|
final candidate = digits.substring(0, length);
|
||
|
|
if (candidate.startsWith('0')) {
|
||
|
|
continue;
|
||
|
|
}
|
||
|
|
if (digits.length - length >= 4) {
|
||
|
|
return candidate;
|
||
|
|
}
|
||
|
|
}
|
||
|
|
return null;
|
||
|
|
}
|