feat(frontend): improve i18n

This commit is contained in:
Andrey Antukh 2019-06-19 16:44:54 +02:00
parent bd11b5864b
commit c98e89278f
11 changed files with 70 additions and 52 deletions

View file

@ -2,16 +2,32 @@
;; License, v. 2.0. If a copy of the MPL was not distributed with this
;; file, You can obtain one at http://mozilla.org/MPL/2.0/.
;;
;; Copyright (c) 2015-2016 Andrey Antukh <niwi@niwi.nz>
;; Copyright (c) 2015-2016 Juan de la Cruz <delacruzgarciajuan@gmail.com>
;; Copyright (c) 2015-2019 Andrey Antukh <niwi@niwi.nz>
(ns uxbox.util.i18n
"A i18n foundation."
(:require [cuerdas.core :as str]
[uxbox.util.storage :refer (storage)]))
(defonce locales (volatile! {}))
(defonce locale (get storage ::locale :en))
(defonce state (atom {:current-locale (get storage ::locale :en)}))
(defn update-locales!
[callback]
(swap! state callback))
(defn set-current-locale!
[locale]
(swap! storage assoc ::locale locale)
(swap! state assoc :current-locale locale))
(defn on-locale-change!
[callback]
(add-watch state ::main (fn [_ _ old new]
(let [old-locale (:current-locale old)
new-locale (:current-locale new)]
(when (not= old-locale new-locale)
(callback new-locale old-locale))))))
;; A marker type that is used just for mark
;; a parameter that reprsentes the counter.
@ -34,12 +50,14 @@
"Translate the string."
([t]
(let [default (name t)
value (get-in @locales [locale t] default)]
locale (get @state :current-locale)
value (get-in @state [locale t] default)]
(if (vector? value)
(or (second value) default)
value)))
([t & args]
(let [value (get-in @locales [locale t] (name t))
(let [locale (get @state :current-locale)
value (get-in @state [locale t] (name t))
plural (first (filter c? args))
args (mapv #(if (c? %) @% %) args)
value (cond