Initial commit.
This commit is contained in:
@@ -0,0 +1,38 @@
|
||||
import Foundation
|
||||
|
||||
/// A backend that resolves localized strings for an explicit locale and reports the languages it serves.
|
||||
///
|
||||
/// This is the seam that decouples ``Localize`` and ``LanguageList`` from *how* localizations are stored and resolved. The shipping implementation,
|
||||
/// ``StringCatalog``, reads a raw `.xcstrings` catalog so it behaves identically on Darwin and Linux. A future backend — for example one built on
|
||||
/// `String(localized:)` for a native Apple app that needs plural and device variations — can conform without changing any caller.
|
||||
///
|
||||
/// Resolution never fails: an implementation returns the key itself when it has no localization for it, mirroring Foundation's `String(localized:)`.
|
||||
/// This is the contract both a dictionary lookup and the native API can honour, since the native API cannot distinguish a missing key from a translation that
|
||||
/// happens to equal the key.
|
||||
protocol CatalogResolving: Sendable {
|
||||
|
||||
// MARK: Properties
|
||||
|
||||
/// The source (development) language, used as the final fallback when a locale has no localization and as the default language a ``LanguageList``
|
||||
/// serves.
|
||||
var sourceLanguage: String { get }
|
||||
|
||||
/// The outcome of reading the backing catalog, for consumers to surface at startup.
|
||||
var state: CatalogState { get }
|
||||
|
||||
/// Every language the backend can resolve strings for, including the source language.
|
||||
var languages: Set<String> { get }
|
||||
|
||||
// MARK: Methods
|
||||
|
||||
/// Resolves a catalog key in the given locale.
|
||||
/// - Parameters:
|
||||
/// - key: the catalog key to look up.
|
||||
/// - locale: the locale to resolve the key in.
|
||||
/// - Returns: the localized string, falling back to the source language, then to the key itself.
|
||||
func string(
|
||||
for key: String,
|
||||
in locale: Locale
|
||||
) -> String
|
||||
|
||||
}
|
||||
@@ -0,0 +1,16 @@
|
||||
/// A single language range parsed from an `Accept-Language` header entry.
|
||||
///
|
||||
/// A range pairs the language tag a client asked for with the `q` weight expressing how much the client prefers it, as RFC 9110 defines them.
|
||||
/// ``Negotiate`` parses each comma-separated header entry into one of these, then orders the ranges by descending weight so the most preferred tag
|
||||
/// is matched first.
|
||||
struct LanguageRange {
|
||||
|
||||
// MARK: Properties
|
||||
|
||||
/// The language tag the client asked for, such as `de` or `de-AT`, or the `*` wildcard.
|
||||
let tag: String
|
||||
|
||||
/// The tag's `q` weight, from 0 ("not acceptable") to 1 (most preferred, the default when an entry names no weight).
|
||||
let quality: Double
|
||||
|
||||
}
|
||||
@@ -0,0 +1,232 @@
|
||||
import Foundation
|
||||
import Synchronization
|
||||
|
||||
/// A decoded `.xcstrings` String Catalog, read directly from a bundle's resources.
|
||||
///
|
||||
/// The catalog is parsed from raw JSON rather than through Foundation's compiled-catalog APIs (`String(localized:)`,
|
||||
/// `Bundle.localizations`, `Bundle.preferredLocalizations`). Those are either unavailable or non-functional on non-Darwin platforms
|
||||
/// (Linux), where the toolchain ships no `xcstringstool` and so copies the raw `.xcstrings` into the resource bundle instead of compiling it.
|
||||
/// Reading the catalog ourselves gives identical behaviour on every platform the service builds for.
|
||||
///
|
||||
/// Only simple `stringUnit` values are decoded; plural and device variations are not represented.
|
||||
struct StringCatalog: Sendable {
|
||||
|
||||
// MARK: Properties
|
||||
|
||||
/// The source language of the catalog, used as the fallback when a key lacks a requested localization.
|
||||
let sourceLanguage: String
|
||||
|
||||
/// The resolved entries, keyed by catalog key then by language code.
|
||||
let entries: [String: [String: String]]
|
||||
|
||||
/// The outcome of reading the catalog from its bundle.
|
||||
let state: CatalogState
|
||||
|
||||
// MARK: Computed
|
||||
|
||||
/// Every language the catalog provides a localization for, including the source language.
|
||||
var languages: Set<String> {
|
||||
var languages = Set(entries.values.flatMap(\.keys))
|
||||
|
||||
languages.insert(sourceLanguage)
|
||||
|
||||
return languages
|
||||
}
|
||||
|
||||
// MARK: Initializers
|
||||
|
||||
/// Reads the catalog named `table` from `bundle`.
|
||||
///
|
||||
/// Falls back to an empty catalog (source language `"en"`, no entries) when the resource is missing or cannot be decoded, so lookups degrade
|
||||
/// to returning the key and the language list to the default.
|
||||
/// - Parameters:
|
||||
/// - bundle: the bundle whose resources contain the String Catalog.
|
||||
/// - table: the name of the String Catalog resource, without the `.xcstrings` extension.
|
||||
init(
|
||||
bundle: Bundle,
|
||||
table: String = "Localizable"
|
||||
) {
|
||||
guard let url = bundle.url(
|
||||
forResource: table,
|
||||
withExtension: .Extension.stringCatalog
|
||||
) else {
|
||||
self.sourceLanguage = .Default.sourceLanguage
|
||||
self.entries = [:]
|
||||
self.state = .missing
|
||||
return
|
||||
}
|
||||
|
||||
do {
|
||||
let decoder = JSONDecoder()
|
||||
let data = try Data(contentsOf: url)
|
||||
let decoded = try decoder.decode(
|
||||
Decoded.self,
|
||||
from: data
|
||||
)
|
||||
|
||||
self.sourceLanguage = decoded.sourceLanguage
|
||||
self.entries = decoded.strings
|
||||
.mapValues { entry in
|
||||
(entry.localizations ?? [:])
|
||||
.compactMapValues { $0.stringUnit?.value }
|
||||
}
|
||||
self.state = .loaded
|
||||
} catch {
|
||||
self.sourceLanguage = .Default.sourceLanguage
|
||||
self.entries = [:]
|
||||
self.state = .undecodable
|
||||
}
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
// MARK: - Cache
|
||||
|
||||
extension StringCatalog {
|
||||
|
||||
/// A cache key identifying a catalog by its bundle location and table name.
|
||||
private struct Key: Hashable, Sendable {
|
||||
let bundle: URL
|
||||
let table: String
|
||||
}
|
||||
|
||||
/// The decoded catalogs, keyed by bundle and table.
|
||||
private static let cache = Mutex<[Key: StringCatalog]>([:])
|
||||
|
||||
/// Returns the catalog for the given bundle and table, decoding it on first access.
|
||||
///
|
||||
/// Catalogs are immutable at runtime, so every ``Localize``, ``Negotiate``, and ``LanguageList`` bound to the same bundle shares one
|
||||
/// decoded catalog instead of re-reading its JSON.
|
||||
/// - Parameters:
|
||||
/// - bundle: the bundle whose resources contain the String Catalog.
|
||||
/// - table: the name of the String Catalog resource, without the `.xcstrings` extension.
|
||||
/// - Returns: the decoded catalog, from the cache when it has been read before.
|
||||
static func cached(
|
||||
bundle: Bundle,
|
||||
table: String = "Localizable"
|
||||
) -> StringCatalog {
|
||||
let key = Key(
|
||||
bundle: bundle.bundleURL,
|
||||
table: table
|
||||
)
|
||||
|
||||
return cache.withLock { cache in
|
||||
if let catalog = cache[key] {
|
||||
return catalog
|
||||
}
|
||||
|
||||
let catalog = StringCatalog(
|
||||
bundle: bundle,
|
||||
table: table
|
||||
)
|
||||
|
||||
cache[key] = catalog
|
||||
|
||||
return catalog
|
||||
}
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
// MARK: - CatalogResolving
|
||||
|
||||
extension StringCatalog: CatalogResolving {
|
||||
|
||||
/// Resolves a key by the most specific language tag first: the locale's full tag (`pt-BR`), then its primary language code (`pt`), then the source
|
||||
/// language, then the key itself. Tags are matched case-insensitively, so a regional catalog entry resolves for the locale ``Negotiate`` picked it for.
|
||||
func string(
|
||||
for key: String,
|
||||
in locale: Locale
|
||||
) -> String {
|
||||
guard let byLanguage = entries[key] else {
|
||||
return key
|
||||
}
|
||||
|
||||
for tag in locale.catalogTags {
|
||||
if let match = byLanguage.first(
|
||||
where: { $0.key.lowercased() == tag }
|
||||
) {
|
||||
return match.value
|
||||
}
|
||||
}
|
||||
|
||||
return byLanguage[sourceLanguage] ?? key
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
// MARK: - Locale+Extensions
|
||||
|
||||
private extension Locale {
|
||||
|
||||
/// The language tags to resolve a catalog entry against, most specific first.
|
||||
///
|
||||
/// The locale's full identifier comes first, as a hyphenated, lowercased tag (`pt_BR` becomes `pt-br`), followed by its primary language code when
|
||||
/// the two differ.
|
||||
var catalogTags: [String] {
|
||||
var tags: [String] = []
|
||||
let identifier = identifier
|
||||
.replacingOccurrences(
|
||||
of: String.Separator.underscore,
|
||||
with: String.Separator.dash
|
||||
)
|
||||
.lowercased()
|
||||
|
||||
if !identifier.isEmpty {
|
||||
tags.append(identifier)
|
||||
}
|
||||
|
||||
if let code = language.languageCode?.identifier.lowercased(),
|
||||
code != identifier {
|
||||
tags.append(code)
|
||||
}
|
||||
|
||||
return tags
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
// MARK: - Decoding Types
|
||||
|
||||
private extension StringCatalog {
|
||||
|
||||
/// The subset of the `.xcstrings` format needed to resolve simple string entries.
|
||||
struct Decoded: Decodable {
|
||||
|
||||
let sourceLanguage: String
|
||||
let strings: [String: Entry]
|
||||
|
||||
struct Entry: Decodable {
|
||||
let localizations: [String: Localization]?
|
||||
}
|
||||
|
||||
struct Localization: Decodable {
|
||||
let stringUnit: StringUnit?
|
||||
}
|
||||
|
||||
struct StringUnit: Decodable {
|
||||
let value: String
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
// MARK: - String+Constants
|
||||
|
||||
private extension String {
|
||||
/// The source language assumed when a catalog is missing or cannot be decoded, matching the
|
||||
/// package's default localization.
|
||||
enum Default {
|
||||
static let sourceLanguage = "en"
|
||||
}
|
||||
|
||||
enum Extension {
|
||||
static let stringCatalog = "xcstrings"
|
||||
}
|
||||
|
||||
enum Separator {
|
||||
static let dash = "-"
|
||||
static let underscore = "_"
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user