Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

optimize default language parsing #659

Merged
merged 5 commits into from
Sep 17, 2024
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
10 changes: 3 additions & 7 deletions Easydict/Swift/Feature/Localization/I18nHelper.swift
Original file line number Diff line number Diff line change
Expand Up @@ -25,19 +25,15 @@ class I18nHelper: NSObject {
}

var localizeCode: String {
if let code = UserDefaults.standard.string(forKey: languagePreferenceLocalKey) {
if let code = UserDefaults.standard.string(forKey: languagePreferenceLocalKey),
LanguageState.LanguageType(rawValue: code) != nil {
return code
}

if let localLanguageType = LanguageState.LanguageType(rawValue: Locale.current.identifier) {
if let localLanguageType = Locale.current.languageType {
return localLanguageType.rawValue
}

// We should use EZLanguageModel localeIdentifier to rewrite this code.
if Locale.current.identifier == "zh_CN" {
return LanguageState.LanguageType.simplifiedChinese.rawValue
}

return LanguageState.LanguageType.english.rawValue
}

Expand Down
28 changes: 28 additions & 0 deletions Easydict/Swift/Feature/Localization/LanguageState.swift
Original file line number Diff line number Diff line change
Expand Up @@ -48,3 +48,31 @@ class LanguageState: ObservableObject {
}
}
}

// https://developer.apple.com/library/archive/documentation/MacOSX/Conceptual/BPInternational/LanguageandLocaleIDs/LanguageandLocaleIDs.html
extension Locale {
var languageType: LanguageState.LanguageType? {
let languageCode = language.languageCode?.identifier
let script = language.script?.identifier
let region = language.region?.identifier

let languageCodeScriptRegion = [languageCode, script, region].compactMap { $0 }.joined(separator: "-")
let languageCodeScript = [languageCode, script].compactMap { $0 }.joined(separator: "-")
let languageCodeRegion = [languageCode, region].compactMap { $0 }.joined(separator: "-")

if let languageCode, let type = LanguageState.LanguageType(rawValue: languageCode) {
return type
}
if let type = LanguageState.LanguageType(rawValue: languageCodeScriptRegion) {
return type
}
if let type = LanguageState.LanguageType(rawValue: languageCodeScript) {
return type
}
if let type = LanguageState.LanguageType(rawValue: languageCodeRegion) {
return type
}

return nil
}
}