SPB Git

Repository Public

L10n.swift 2.5 KB 48 lines swift

1// SP Notes Core2// File: Sources/SPNotesFeatures/Support/L10n.swift3// Description: Localisation of the feature screens. French is the source language: the key IS the French text. English4//              lives in `Localization/en/*.json` (one file per area) and `Scripts/build-string-catalog.py` generates5//              `Resources/Localizable.xcstrings` from the `L` / `LF` literals found in the sources.6//7// Author: Simon-Pierre Boucher8// Contact: contact@spboucher.ai9import Foundation1011/// A localised UI string. **Always call it with a plain string literal** (no interpolation): the catalogue generator and12/// the coverage test read the literals.13public func L(_ key: String) -> String {14    if FeatureStrings.forcedLanguage == FeatureStrings.sourceLanguage { return key }   // the key is the French text15    return FeatureStrings.bundle.localizedString(forKey: key, value: key, table: nil)16}1718/// A localised format (`%@`, `%lld`, `%.1f`…), same rule: the first argument is a plain literal.19public func LF(_ key: String, _ arguments: CVarArg...) -> String {20    String(format: L(key), locale: FeatureStrings.locale, arguments: arguments)21}2223public enum FeatureStrings {24    public static let sourceLanguage = "fr"25    /// The language forced for this process: `SPN_FEATURES_LANG` (`fr`, `en`), else French under a test runner (the unit26    /// tests and the hosted renders are written against the source language), else nil = the user's language.27    public static let forcedLanguage: String? = {28        let environment = ProcessInfo.processInfo.environment29        if let language = environment["SPN_FEATURES_LANG"], !language.isEmpty { return language }30        if NSClassFromString("XCTestCase") != nil || Bundle.allBundles.contains(where: { $0.bundlePath.hasSuffix(".xctest") }) { return sourceLanguage }31        return nil32    }()3334    static let bundle: Bundle = forcedLanguage.flatMap(bundle(language:)) ?? .module3536    /// The locale of dates and numbers next to the strings.37    public static let locale: Locale = forcedLanguage.map { Locale(identifier: $0 == "fr" ? "fr_CA" : $0) } ?? .current3839    static func bundle(language: String) -> Bundle? {40        Bundle.module.path(forResource: language, ofType: "lproj").flatMap(Bundle.init(path:))41    }4243    /// The text of a key in a given language (nil when the catalogue was not compiled for it).44    public static func string(_ key: String, language: String) -> String? {45        bundle(language: language)?.localizedString(forKey: key, value: nil, table: nil)46    }47}48
Files main
Menu

Theme