SPB Git

Repository Public

Localization.swift 3.7 KB 90 lines swift

1import Foundation2import Observation34public enum AppLanguage: String, CaseIterable, Sendable, Codable, Identifiable {5    case fr, en6    public var id: String { rawValue }7    /// The language's own name (never translated).8    public var endonym: String { self == .fr ? "Français" : "English" }9    public var locale: Locale { Locale(identifier: self == .fr ? "fr_CA" : "en_CA") }10}1112/// In-app language (French by default, English), switchable at runtime without relaunch.13///14/// Strings live in String Catalogs (`*.xcstrings`) compiled into `<lang>.lproj/*.strings`; every registered bundle15/// (MCCCore's own, then the app's) is merged into one table per language. Views read `tr(...)`, which registers an16/// Observation dependency on `language`, so the interface re-renders when the language changes.17@Observable18public final class Localization: @unchecked Sendable {19    public static let shared = Localization()20    public static let defaultsKey = "mcc.language"2122    @ObservationIgnored private let lock = NSLock()23    @ObservationIgnored private var bundles: [Bundle] = [.module]24    @ObservationIgnored private var tables: [AppLanguage: [String: String]] = [:]25    @ObservationIgnored private var current: AppLanguage2627    public init(language: AppLanguage? = nil, defaults: UserDefaults = .standard) {28        current = language ?? defaults.string(forKey: Self.defaultsKey).flatMap(AppLanguage.init(rawValue:)) ?? .fr29    }3031    public var language: AppLanguage {32        get {33            access(keyPath: \.language)34            return lock.withLock { current }35        }36        set {37            withMutation(keyPath: \.language) { lock.withLock { current = newValue } }38        }39    }4041    public var locale: Locale { language.locale }4243    /// Sets and persists the language.44    public func select(_ language: AppLanguage, defaults: UserDefaults = .standard) {45        defaults.set(language.rawValue, forKey: Self.defaultsKey)46        self.language = language47    }4849    /// Adds a bundle whose catalogs complete (and take precedence over) the ones already registered.50    public func register(bundle: Bundle) {51        lock.withLock {52            guard !bundles.contains(bundle) else { return }53            bundles.append(bundle)54            tables = [:]55        }56    }5758    public func table(for language: AppLanguage) -> [String: String] {59        lock.withLock {60            if let t = tables[language] { return t }61            var merged: [String: String] = [:]62            for bundle in bundles {63                guard let lproj = bundle.url(forResource: language.rawValue, withExtension: "lproj"),64                      let files = try? FileManager.default.contentsOfDirectory(at: lproj, includingPropertiesForKeys: nil) else { continue }65                for file in files where file.pathExtension == "strings" {66                    if let d = NSDictionary(contentsOf: file) as? [String: String] { merged.merge(d) { $1 } }67                }68            }69            tables[language] = merged70            return merged71        }72    }7374    public func string(_ key: String, language: AppLanguage? = nil) -> String {75        let lang = language ?? self.language76        return table(for: lang)[key] ?? key77    }7879    public func has(_ key: String, language: AppLanguage) -> Bool { table(for: language)[key] != nil }80}8182/// Localized string for `key` in the current in-app language. Missing keys return the key itself (and fail the83/// catalog completeness tests).84public func tr(_ key: String) -> String { Localization.shared.string(key) }8586/// Localized format string with arguments (`%@`, `%d`, `%lld`, positional `%1$@`...).87public func tr(_ key: String, _ args: any CVarArg...) -> String {88    String(format: Localization.shared.string(key), locale: Localization.shared.locale, arguments: args)89}90
Files main
Menu

Theme