Localization support for the Website service (#10)
This PR contains the work done to introduce server-side localization support to the **Website** service so the landing and error pages are served in the visitor's negotiated language, backed by a new reusable Localization package. To provide further details about the work: * Created the _Localization_ package — a bundle-bound `Localize` method and a `LanguageList` type. * Language negotiation — `NegotiateLanguage` method picks the best supported language from the request's _Accept-Language_ header (falling back to the default); the `LocalizationMiddleware` middleware resolves it per request and stores it on a new `LocalizedRequestContext` / `WebsiteRequestContext` context. * Localized responses — `LocalizedHTMLCollectionResponse` pre-renders each page once per language and caches the bytes (with `Content-Language` + `Vary: Accept-Language`), reused by the `RootController` controller and `NotFoundMiddleware` middleware. * The `CachedHTMLResponse` response gained custom-header support. * Localized pages — the `IndexPage` and `ErrorPage` pages now resolve their strings via `Localize` method; * Added `Localizable.xcstrings` catalogs. * Wired the `LocalizationMiddleware` middlewaer into the router. Reviewed-on: rock-n-code/loud-amsterdam#10 Co-authored-by: Javier Cicchelli <javier@rock-n-code.com> Co-committed-by: Javier Cicchelli <javier@rock-n-code.com>
This commit is contained in:
@@ -0,0 +1,85 @@
|
||||
import Foundation
|
||||
import Localization
|
||||
|
||||
/// Negotiates the best supported language for a request from its `Accept-Language` header.
|
||||
///
|
||||
/// Bound to the module's catalog languages via ``LanguageList``, an instance is invoked like a
|
||||
/// function — through ``callAsFunction(forAcceptLanguage:)`` — to resolve a header value to a
|
||||
/// supported language identifier, falling back to the default language.
|
||||
struct NegotiateLanguage {
|
||||
|
||||
// MARK: Properties
|
||||
|
||||
/// The supported languages and default language, derived from the module's String Catalog.
|
||||
private let list: LanguageList
|
||||
|
||||
// MARK: Initializers
|
||||
|
||||
/// Creates a language negotiator backed by the module's String Catalog.
|
||||
init() {
|
||||
self.list = .init(bundle: .module)
|
||||
}
|
||||
|
||||
// MARK: Methods
|
||||
|
||||
/// Picks the best supported language for the given `Accept-Language` header value.
|
||||
///
|
||||
/// Invoked by calling the instance directly, for example `negotiate(forAcceptLanguage: header)`.
|
||||
/// The header is split into its language tags (dropping any `q` weights), then matched against
|
||||
/// the supported languages with `Bundle.preferredLocalizations(from:forPreferences:)`. When the
|
||||
/// header is absent or matches nothing, the default language is returned.
|
||||
/// - Parameter acceptLanguage: the raw `Accept-Language` header value, if any.
|
||||
/// - Returns: the identifier of the supported language to serve.
|
||||
func callAsFunction(
|
||||
forAcceptLanguage acceptLanguage: String?
|
||||
) -> String {
|
||||
guard let acceptLanguage else {
|
||||
return list.default
|
||||
}
|
||||
|
||||
let tags = tags(from: acceptLanguage)
|
||||
|
||||
guard !tags.isEmpty else {
|
||||
return list.default
|
||||
}
|
||||
|
||||
let preferred = Bundle.preferredLocalizations(
|
||||
from: list.all,
|
||||
forPreferences: tags
|
||||
)
|
||||
|
||||
return preferred.first
|
||||
?? list.default
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
// MARK: - Helpers
|
||||
|
||||
private extension NegotiateLanguage {
|
||||
|
||||
// MARK: Methods
|
||||
|
||||
/// Extracts the ordered language tags from an `Accept-Language` header value.
|
||||
///
|
||||
/// Each comma-separated entry is reduced to its language tag by dropping the `;q=` weight, and
|
||||
/// blank entries are removed. The original order is kept, which mirrors descending preference
|
||||
/// closely enough for `preferredLocalizations(from:forPreferences:)` to resolve correctly.
|
||||
/// - Parameter acceptLanguage: the raw `Accept-Language` header value.
|
||||
/// - Returns: the ordered, weight-stripped language tags.
|
||||
func tags(
|
||||
from acceptLanguage: String
|
||||
) -> [String] {
|
||||
acceptLanguage
|
||||
.split(separator: ",")
|
||||
.map { entry in
|
||||
entry
|
||||
.split(separator: ";")
|
||||
.first
|
||||
.map(String.init)?
|
||||
.trimmingCharacters(in: .whitespaces) ?? ""
|
||||
}
|
||||
.filter { !$0.isEmpty }
|
||||
}
|
||||
|
||||
}
|
||||
@@ -1,14 +1,39 @@
|
||||
import Elementary
|
||||
import Foundation
|
||||
import Localization
|
||||
|
||||
/// The HTML page rendered for a not-found response.
|
||||
/// The HTML page rendered for a not-found response, with its text localized to a given locale.
|
||||
struct ErrorPage: HTMLDocument, Sendable {
|
||||
|
||||
// MARK: Properties
|
||||
|
||||
/// The locale the page content is localized to.
|
||||
private let locale: Locale
|
||||
|
||||
/// Resolves the page's text from the bundled String Catalog for the page's ``locale``.
|
||||
private let localize: Localize
|
||||
|
||||
// MARK: Initializers
|
||||
|
||||
/// Creates a not-found page localized to the given locale.
|
||||
/// - Parameter locale: the locale the page content is localized to.
|
||||
init(
|
||||
locale: Locale
|
||||
) {
|
||||
self.locale = locale
|
||||
self.localize = .init(bundle: .module)
|
||||
}
|
||||
|
||||
// MARK: Document
|
||||
|
||||
/// The page's content.
|
||||
/// The page's content: a localized heading and explanatory message.
|
||||
var body: some HTML {
|
||||
h1 { "Page Not Found" }
|
||||
p { "Sorry, but the page you were trying to view does not exist." }
|
||||
h1 {
|
||||
localize("error.heading", locale: locale)
|
||||
}
|
||||
p {
|
||||
localize("error.message", locale: locale)
|
||||
}
|
||||
}
|
||||
|
||||
/// The metadata and stylesheet link placed in the document head.
|
||||
@@ -24,10 +49,15 @@ struct ErrorPage: HTMLDocument, Sendable {
|
||||
)
|
||||
}
|
||||
|
||||
/// The document language.
|
||||
var lang: String { "en" }
|
||||
/// The document language, derived from the page's locale and falling back to the default language.
|
||||
var lang: String {
|
||||
locale.language.languageCode?.identifier
|
||||
?? LanguageList(bundle: .module).default
|
||||
}
|
||||
|
||||
/// The document title.
|
||||
var title: String { "Page Not Found" }
|
||||
/// The localized document title.
|
||||
var title: String {
|
||||
localize("error.title", locale: locale)
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
@@ -1,13 +1,36 @@
|
||||
import Elementary
|
||||
import Foundation
|
||||
import Localization
|
||||
|
||||
/// The website's landing page.
|
||||
/// The website's landing page, with its text localized to a given locale.
|
||||
struct IndexPage: HTMLDocument, Sendable {
|
||||
|
||||
// MARK: Properties
|
||||
|
||||
/// The locale the page content is localized to.
|
||||
private let locale: Locale
|
||||
|
||||
/// Resolves the page's text from the bundled String Catalog for the page's ``locale``.
|
||||
private let localize: Localize
|
||||
|
||||
// MARK: Initializers
|
||||
|
||||
/// Creates a landing page localized to the given locale.
|
||||
/// - Parameter locale: the locale the page content is localized to.
|
||||
init(
|
||||
locale: Locale
|
||||
) {
|
||||
self.locale = locale
|
||||
self.localize = .init(bundle: .module)
|
||||
}
|
||||
|
||||
// MARK: Document
|
||||
|
||||
/// The page's content.
|
||||
/// The page's content: a localized greeting followed by the app script.
|
||||
var body: some HTML {
|
||||
p { "Hello world! This is HTML5 Boilerplate." }
|
||||
p {
|
||||
localize("index.greeting", locale: locale)
|
||||
}
|
||||
script(.src("/js/app.js")) {}
|
||||
}
|
||||
|
||||
@@ -52,14 +75,15 @@ struct IndexPage: HTMLDocument, Sendable {
|
||||
)
|
||||
}
|
||||
|
||||
/// The document language.
|
||||
/// The document language, derived from the page's locale and falling back to the default language.
|
||||
var lang: String {
|
||||
"en"
|
||||
locale.language.languageCode?.identifier
|
||||
?? LanguageList(bundle: .module).default
|
||||
}
|
||||
|
||||
/// The document title.
|
||||
/// The localized document title.
|
||||
var title: String {
|
||||
"Index page"
|
||||
localize("index.title", locale: locale)
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
@@ -1,12 +1,16 @@
|
||||
import Elementary
|
||||
import HTTPTypes
|
||||
import Hummingbird
|
||||
import NIOCore
|
||||
|
||||
/// A pre-rendered HTTP response for a fully static HTML page.
|
||||
///
|
||||
/// The document is rendered to bytes once, at initialization, and every ``response()`` reuses those
|
||||
/// bytes instead of re-rendering. This suits pages whose markup never changes between requests — the
|
||||
/// landing page and the not-found page — avoiding a per-request Elementary render on hot paths.
|
||||
/// bytes — along with a fixed status and precomputed headers — instead of re-rendering. This suits
|
||||
/// pages whose markup never changes between requests, such as the landing page and the not-found
|
||||
/// page, avoiding a per-request Elementary render on hot paths.
|
||||
///
|
||||
/// ``LocalizedHTMLResponses`` builds on this type, caching one instance per supported language.
|
||||
///
|
||||
/// The body is written as an unsized stream (no `Content-Length`), mirroring `HTMLResponse`, so the
|
||||
/// response-compression middleware downstream treats it exactly as it would a freshly rendered page.
|
||||
@@ -14,23 +18,37 @@ struct CachedHTMLResponse: Sendable {
|
||||
|
||||
// MARK: Properties
|
||||
|
||||
/// The status applied to every response.
|
||||
private let status: HTTPResponse.Status
|
||||
/// The page rendered to bytes once.
|
||||
private let buffer: ByteBuffer
|
||||
/// The headers applied to every response, precomputed once.
|
||||
private let headers: HTTPFields
|
||||
/// The status applied to every response.
|
||||
private let status: HTTPResponse.Status
|
||||
|
||||
// MARK: Initializers
|
||||
|
||||
/// Renders the given document to bytes once.
|
||||
/// - Parameters:
|
||||
/// - status: the status applied to every response. Defaults to `.ok`.
|
||||
/// - additionalHeaders: extra headers merged onto every response, alongside the content type.
|
||||
/// Used to carry per-language signals such as `Content-Language` and `Vary`.
|
||||
/// - document: the static HTML document to render and cache.
|
||||
init(
|
||||
status: HTTPResponse.Status = .ok,
|
||||
_ document: some HTMLDocument
|
||||
additionalHeaders: HTTPFields = [:],
|
||||
document: some HTMLDocument
|
||||
) {
|
||||
var headers: HTTPFields = [
|
||||
.contentType: "text/html; charset=utf-8"
|
||||
]
|
||||
|
||||
for field in additionalHeaders {
|
||||
headers[field.name] = field.value
|
||||
}
|
||||
|
||||
self.status = status
|
||||
self.buffer = ByteBuffer(string: document.render())
|
||||
self.headers = headers
|
||||
self.buffer = .init(string: document.render())
|
||||
}
|
||||
|
||||
// MARK: Methods
|
||||
@@ -43,7 +61,7 @@ struct CachedHTMLResponse: Sendable {
|
||||
func response() -> Response {
|
||||
Response(
|
||||
status: status,
|
||||
headers: [.contentType: "text/html; charset=utf-8"],
|
||||
headers: headers,
|
||||
body: .init { [buffer] writer in
|
||||
try await writer.write(buffer)
|
||||
try await writer.finish(nil)
|
||||
|
||||
+65
@@ -0,0 +1,65 @@
|
||||
import Elementary
|
||||
import Foundation
|
||||
import HTTPTypes
|
||||
import Hummingbird
|
||||
import Localization
|
||||
|
||||
/// A per-language collection of pre-rendered HTML responses.
|
||||
///
|
||||
/// At initialization it renders the document once for each language the bundle's ``LanguageList``
|
||||
/// reports and caches the bytes, mirroring ``CachedHTMLResponse``'s render-once model but keyed by
|
||||
/// language. Each cached response carries a `Content-Language` header and `Vary: Accept-Language`, so
|
||||
/// shared caches key on the negotiated language instead of serving one language to everyone.
|
||||
struct LocalizedHTMLCollectionResponse: Sendable {
|
||||
|
||||
// MARK: Properties
|
||||
|
||||
/// The supported languages and default language, derived from the module's String Catalog.
|
||||
private let list: LanguageList
|
||||
|
||||
/// The pre-rendered responses, keyed by language identifier.
|
||||
private let responses: [String: CachedHTMLResponse]
|
||||
|
||||
// MARK: Initializers
|
||||
|
||||
/// Renders the document once per supported language.
|
||||
/// - Parameters:
|
||||
/// - status: the status applied to every response. Defaults to `.ok`.
|
||||
/// - document: builds the document to render for a given locale.
|
||||
init<Document: HTMLDocument>(
|
||||
status: HTTPResponse.Status = .ok,
|
||||
document: (Locale) -> Document
|
||||
) {
|
||||
self.list = .init(bundle: .module)
|
||||
self.responses = list.all
|
||||
.reduce(into: [:]) { responses, language in
|
||||
responses[language] = CachedHTMLResponse(
|
||||
status: status,
|
||||
additionalHeaders: [
|
||||
.contentLanguage: language,
|
||||
.vary: "Accept-Language",
|
||||
],
|
||||
document: document(.init(identifier: language))
|
||||
)
|
||||
}
|
||||
}
|
||||
|
||||
// MARK: Methods
|
||||
|
||||
/// Builds the response for the given language, falling back to the default language.
|
||||
/// - Parameter language: the negotiated language identifier.
|
||||
/// - Returns: the cached response for the language, the default language's response when the
|
||||
/// language is unavailable, or a `500 Internal Server Error` if neither is cached.
|
||||
func response(
|
||||
for language: String
|
||||
) -> Response {
|
||||
guard
|
||||
let response = responses[language] ?? responses[list.default]
|
||||
else {
|
||||
return .init(status: .internalServerError)
|
||||
}
|
||||
|
||||
return response.response()
|
||||
}
|
||||
|
||||
}
|
||||
Reference in New Issue
Block a user