nitro-ui-localize 0.1.0 → 0.2.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/README.md CHANGED
@@ -4,7 +4,7 @@ The user's languages, region, currencies, time zone, 12/24h clock, units and fir
4
4
 
5
5
  Function names follow [`react-native-localize`](https://github.com/zoontek/react-native-localize), so an i18next or Lingui setup moves over by changing the import.
6
6
 
7
- > **Status: 0.x.** Tested on NitroUI 0.3.0 with an iOS 26.5 simulator and Android 15 and 17 emulators.
7
+ > **Status: 0.x.** Tested on NitroUI 0.3.0 with an iOS 26.5 simulator and Android 11, 15 and 17 emulators. Not yet on physical devices.
8
8
 
9
9
  ## Install
10
10
 
@@ -43,6 +43,23 @@ function Price({ amount }: { amount: number }) {
43
43
  }
44
44
  ```
45
45
 
46
+ ## With i18next
47
+
48
+ NitroUI's Hermes has no `Intl.PluralRules`, which i18next needs for plurals. Load the FormatJS polyfill and the plural data for your languages before `i18next.init`:
49
+
50
+ ```ts
51
+ import '@formatjs/intl-pluralrules/polyfill-force.js'
52
+ import '@formatjs/intl-pluralrules/locale-data/en.js'
53
+ import '@formatjs/intl-pluralrules/locale-data/ar.js'
54
+ import i18next from 'i18next'
55
+ import { findBestLanguageTag } from 'nitro-ui-localize'
56
+
57
+ await i18next.init({ lng: findBestLanguageTag(['en', 'ar'])?.languageTag ?? 'en', resources })
58
+ i18next.t('items', { count: 3 }) // Arabic "few" form
59
+ ```
60
+
61
+ The example app's `__tests__/i18next.harness.ts` runs this recipe on both platforms, and fails once NitroUI ships `Intl.PluralRules`.
62
+
46
63
  ## API
47
64
 
48
65
  All getters are synchronous.
@@ -65,6 +82,8 @@ All getters are synchronous.
65
82
  | `usesAutoTimeZone()` | Android only, `undefined` on iOS | `true` |
66
83
  | `findBestLanguageTag(tags)` | First of your tags that matches the user's languages, in the user's order | `{ languageTag: 'hi', isRTL: false }` |
67
84
  | `openAppLanguageSettings()` | Opens the system page for this app's language | `Promise<void>` |
85
+ | `getAppLanguage()` | The language set for this app only, `undefined` when it follows the system. Android 13+ | `'de-DE'` |
86
+ | `setAppLanguage(tag)` | Sets this app's language, `undefined` to follow the system. Android 13+, rejects elsewhere | `Promise<void>` |
68
87
  | `addChangeListener(fn)` | Calls `fn` when any setting above changes | `{ remove() }` |
69
88
  | `useLocalize()` | The API, re-rendering on change | |
70
89
 
@@ -72,7 +91,7 @@ All getters are synchronous.
72
91
 
73
92
  ## Why not just `Intl`?
74
93
 
75
- NitroUI's Hermes build ships `Intl`, and you should keep using it to **format** dates, numbers and currencies. It can't tell you the user's **settings**. Measured on iOS 26.5 and Android 15 with NitroUI 0.3.0:
94
+ NitroUI's Hermes build ships `Intl`, and you should keep using it to **format** dates, numbers and currencies. It can't tell you the user's **settings**. Measured on an iOS 26.5 **simulator** and an Android 15 emulator with NitroUI 0.3.0. The iOS rows are not yet confirmed on a physical iPhone:
76
95
 
77
96
  | Need | `Intl` | nitro-ui-localize |
78
97
  |---|---|---|
@@ -82,7 +101,7 @@ NitroUI's Hermes build ships `Intl`, and you should keep using it to **format**
82
101
  | Temperature unit, first weekday preferences | ❌ no `Intl.Locale`, no week info | ✅ |
83
102
  | Text direction of the app | ❌ | ✅ |
84
103
  | Know when a setting changes | ❌ | ✅ `addChangeListener` |
85
- | Time zone changed while running | ⚠️ zone name updates, but `Date` keeps the old offset until relaunch | ✅ change event with the new zone |
104
+ | Know that the time zone changed while running | ❌ no event, you would have to poll | ✅ change event with the new zone |
86
105
 
87
106
  `Intl.PluralRules`, `RelativeTimeFormat`, `ListFormat` and `DisplayNames` are also missing on both platforms, so i18next plurals need a polyfill such as `@formatjs/intl-pluralrules`.
88
107
 
@@ -90,13 +109,21 @@ NitroUI's Hermes build ships `Intl`, and you should keep using it to **format**
90
109
 
91
110
  | | iOS | Android |
92
111
  |---|---|---|
93
- | Getters | ✅ tested on iOS 26.5 | ✅ tested on API 35 and 37 |
112
+ | Getters | ✅ tested on iOS 26.5 | ✅ tested on API 30, 35 and 37 |
94
113
  | 24-hour, temperature, first weekday preferences | ✅ (Settings > Language & Region) | ✅ (24-hour switch; `-u-mu-`, `-u-fw-` regional preferences) |
95
114
  | `usesAutoDateAndTime`, `usesAutoTimeZone` | `undefined` | ✅ |
96
115
  | `openAppLanguageSettings` | Opens the app's Settings page | ✅ (rejects before Android 13) |
97
- | Change listener | ✅ region and unit changes while running. Changing the language restarts an iOS app | ✅ time zone, 24h, language, per-app language |
116
+ | `setAppLanguage`, `getAppLanguage` | Rejects, `undefined` | ✅ Android 13+, live. Rejects before 13 |
117
+ | Change listener | ✅ checked by hand on the simulator: Settings > Temperature changed while the app ran. Changing the language restarts an iOS app | ✅ time zone, 24h, per-app language, tested automatically |
118
+
119
+ Minimum iOS 16, Android 8. Not yet tested: physical devices, iOS 16–18, Android 8–10, 12–14 and 16.
98
120
 
99
- Minimum iOS 16. Not yet tested: physical devices, iOS 16–18, Android 8–14 and 16.
121
+ ### Tested versions
122
+
123
+ | nitro-ui-localize | NitroUI | nitro-core | iOS (simulator) | Android (emulator) | Date |
124
+ |---|---|---|---|---|---|
125
+ | 0.2.0 | 0.3.0 | 1.0.0-alpha.nightly.137 | 26.5 | 11, 15, 17 | 2026-12-03 |
126
+ | 0.1.0 | 0.3.0 | 1.0.0-alpha.nightly.137 | 26.5 | 15, 17 | 2026-12-02 |
100
127
 
101
128
  ## Per-app language
102
129
 
@@ -105,6 +132,24 @@ Both platforms only offer a per-app language when the app declares its languages
105
132
  - **iOS:** list them in `CFBundleLocalizations` in `Info.plist` (two or more).
106
133
  - **Android 13+:** add `res/xml/locales_config.xml` and `android:localeConfig="@xml/locales_config"` on `<application>`.
107
134
 
135
+ To offer an in-app language picker:
136
+
137
+ ```ts
138
+ import { getAppLanguage, openAppLanguageSettings, setAppLanguage } from 'nitro-ui-localize'
139
+
140
+ async function chooseLanguage(tag: string | undefined) {
141
+ try {
142
+ await setAppLanguage(tag) // Android 13+: live, the system's per-app page shows the same value
143
+ } catch {
144
+ await openAppLanguageSettings() // iOS and older Android: the user picks it in system settings
145
+ }
146
+ }
147
+ ```
148
+
149
+ On Android the change event for a language change comes from the Activity being recreated. If your app declares `android:configChanges` with `locale` or `layoutDirection`, the Activity is not recreated and no event fires: read the values again yourself after `setAppLanguage` resolves.
150
+
151
+ `setAppLanguage` works without `localeConfig` (tested on Android 15 and 17), but the system page only lists the app when it has one. iOS has no API to set an app's language, so it always rejects. Keep your own choice in JS too (for example with `nitro-mmkv`) if you also need it on those platforms.
152
+
108
153
  ## What this library does not do
109
154
 
110
155
  | Not doing | Use instead |
@@ -113,11 +158,11 @@ Both platforms only offer a per-app language when the app declares its languages
113
158
  | Format dates, numbers, currencies | `Intl` |
114
159
  | RTL layout (`start`/`end`, mirroring) | NitroUI core ([#879](https://github.com/margelo/nitro-ui/issues/879)) |
115
160
  | Save the chosen language | `nitro-mmkv` |
116
- | Change the app language from code | Not yet. `openAppLanguageSettings()` sends the user to the system page |
161
+ | Change the app language from code on iOS or Android 12 and earlier | No OS API. `openAppLanguageSettings()` sends the user to the system page |
117
162
 
118
163
  ## Coming from react-native-localize
119
164
 
120
- Same names and return shapes for `getLocales`, `getCountry`, `getCurrencies`, `getCalendar`, `getNumberFormatSettings`, `getTemperatureUnit`, `getTimeZone`, `uses24HourClock`, `usesMetricSystem`, `usesAutoDateAndTime`, `usesAutoTimeZone`, `findBestLanguageTag` and `openAppLanguageSettings`. New here: `getMeasurementSystem`, `getFirstDayOfWeek`, `getTextDirection`, `addChangeListener`, and a `useLocalize()` that re-renders on change.
165
+ Same names and return shapes for `getLocales`, `getCountry`, `getCurrencies`, `getCalendar`, `getNumberFormatSettings`, `getTemperatureUnit`, `getTimeZone`, `uses24HourClock`, `usesMetricSystem`, `usesAutoDateAndTime`, `usesAutoTimeZone`, `findBestLanguageTag` and `openAppLanguageSettings`. New here: `getMeasurementSystem`, `getFirstDayOfWeek`, `getTextDirection`, `getAppLanguage`, `setAppLanguage`, `addChangeListener`, and a `useLocalize()` that re-renders on change.
121
166
 
122
167
  ## Development
123
168
 
@@ -133,6 +178,8 @@ bun run test:ios # harness tests inside the app on a simulator
133
178
  bun run test:android
134
179
  ```
135
180
 
181
+ On Android, `__tests__/settings.android.harness.ts` changes real device settings (24-hour clock, time zone, per-app languages) through `adb`, via the host server in `example/test-server/settings.ts`, and resets them afterwards. With several devices connected, set `ANDROID_SERIAL` to the one passed to `--device`. iOS settings are checked by hand.
182
+
136
183
  The example app shows every value and re-renders when a setting changes. It installs the package with `file:`, which copies it, so run `bun install --force` in `example/` after changing the package.
137
184
 
138
185
  ## Credits
@@ -1,9 +1,11 @@
1
1
  package com.margelo.nitro.nitrouilocalize
2
2
 
3
+ import android.app.LocaleManager
3
4
  import android.content.BroadcastReceiver
4
5
  import android.content.Context
5
6
  import android.content.Intent
6
7
  import android.content.IntentFilter
8
+ import android.database.ContentObserver
7
9
  import android.net.Uri
8
10
  import android.os.Build
9
11
  import android.os.Handler
@@ -23,6 +25,8 @@ import java.text.DecimalFormatSymbols
23
25
  import java.util.Currency
24
26
  import java.util.TimeZone
25
27
  import java.util.UUID
28
+ import java.util.concurrent.ConcurrentHashMap
29
+ import java.util.concurrent.CopyOnWriteArrayList
26
30
  import java.util.Locale as JavaLocale
27
31
 
28
32
  /**
@@ -30,13 +34,15 @@ import java.util.Locale as JavaLocale
30
34
  * localization setting changes.
31
35
  *
32
36
  * Changing the language or layout direction recreates the Activity, which calls [onCreate].
33
- * Time zone, clock and 12/24h changes arrive as broadcasts while the Activity keeps running.
37
+ * Time zone and clock changes arrive as broadcasts, and 12/24h changes through a settings
38
+ * observer, while the Activity keeps running.
34
39
  */
35
40
  object LocalizeModule : NitroActivityInitializer {
36
41
  internal var context: Context? = null
37
42
  internal var activity = WeakReference<NitroActivity>(null)
38
43
 
39
- private val listeners = linkedMapOf<UUID, Callback<() -> Unit>>()
44
+ // One HybridLocalize per JS runtime. Weak, so a reloaded runtime's object and its listeners go away.
45
+ private val instances = CopyOnWriteArrayList<WeakReference<HybridLocalize>>()
40
46
  private val mainHandler = Handler(Looper.getMainLooper())
41
47
  private var snapshot: String? = null
42
48
  private var emitScheduled = false
@@ -49,17 +55,17 @@ object LocalizeModule : NitroActivityInitializer {
49
55
  scheduleEmitIfChanged()
50
56
  }
51
57
 
52
- internal fun addListener(listener: Callback<() -> Unit>): UUID {
53
- val id = UUID.randomUUID()
54
- listeners[id] = listener
55
- if (snapshot == null) snapshot = currentSnapshot()
56
- return id
58
+ internal fun register(instance: HybridLocalize) {
59
+ instances.removeAll { it.get() == null }
60
+ instances.add(WeakReference(instance))
57
61
  }
58
62
 
59
- internal fun removeListener(id: UUID) {
60
- listeners.remove(id)
63
+ internal fun listenerAdded() {
64
+ if (snapshot == null) snapshot = currentSnapshot()
61
65
  }
62
66
 
67
+ private fun liveInstances() = instances.mapNotNull { it.get() }.filter { it.hasListeners }
68
+
63
69
  private fun registerReceiver(context: Context) {
64
70
  if (receiverRegistered) return
65
71
  receiverRegistered = true
@@ -81,6 +87,18 @@ object LocalizeModule : NitroActivityInitializer {
81
87
  } else {
82
88
  context.registerReceiver(receiver, filter)
83
89
  }
90
+ // The Settings app broadcasts a 12/24h change, but other writers of the setting do not, and
91
+ // nothing is broadcast for the automatic date and time switches. Watching the settings catches all.
92
+ val observer = object : ContentObserver(mainHandler) {
93
+ override fun onChange(selfChange: Boolean) = scheduleEmitIfChanged()
94
+ }
95
+ for (uri in listOf(
96
+ Settings.System.getUriFor(Settings.System.TIME_12_24),
97
+ Settings.Global.getUriFor(Settings.Global.AUTO_TIME),
98
+ Settings.Global.getUriFor(Settings.Global.AUTO_TIME_ZONE),
99
+ )) {
100
+ context.contentResolver.registerContentObserver(uri, false, observer)
101
+ }
84
102
  }
85
103
 
86
104
  // Several broadcasts can arrive for one change. Compare once per main-loop turn.
@@ -89,14 +107,15 @@ object LocalizeModule : NitroActivityInitializer {
89
107
  emitScheduled = true
90
108
  mainHandler.post {
91
109
  emitScheduled = false
92
- if (listeners.isEmpty()) {
110
+ val targets = liveInstances()
111
+ if (targets.isEmpty()) {
93
112
  snapshot = null
94
113
  return@post
95
114
  }
96
115
  val next = currentSnapshot()
97
116
  if (next == snapshot) return@post
98
117
  snapshot = next
99
- for (listener in listeners.values.toList()) listener.callAndForget()
118
+ for (instance in targets) instance.emitChange()
100
119
  }
101
120
  }
102
121
 
@@ -112,11 +131,29 @@ object LocalizeModule : NitroActivityInitializer {
112
131
  values.temperatureUnit().name,
113
132
  values.measurementSystem().name,
114
133
  values.firstDayOfWeek().name,
134
+ values.numberFormatSettings().let { "${it.decimalSeparator}${it.groupingSeparator}" },
135
+ values.currencies().joinToString(","),
136
+ values.globalSetting(Settings.Global.AUTO_TIME).toString(),
137
+ values.globalSetting(Settings.Global.AUTO_TIME_ZONE).toString(),
115
138
  ).joinToString("|")
116
139
  }
117
140
  }
118
141
 
119
142
  class HybridLocalize : HybridLocalizeSpec() {
143
+ // NitroUI runs JS on the main thread today. A concurrent map keeps this safe if that changes.
144
+ private val listeners = ConcurrentHashMap<UUID, Callback<() -> Unit>>()
145
+
146
+ init {
147
+ LocalizeModule.register(this)
148
+ }
149
+
150
+ internal val hasListeners: Boolean
151
+ get() = listeners.isNotEmpty()
152
+
153
+ internal fun emitChange() {
154
+ for (listener in listeners.values.toList()) listener.callAndForget()
155
+ }
156
+
120
157
  private val values: LocalizeValues
121
158
  get() = LocalizeValues(
122
159
  LocalizeModule.context ?: throw IllegalStateException("nitro-ui-localize is used before the Activity started.")
@@ -137,10 +174,12 @@ class HybridLocalize : HybridLocalizeSpec() {
137
174
  override fun usesAutoTimeZone(): Boolean? = values.globalSetting(Settings.Global.AUTO_TIME_ZONE)
138
175
 
139
176
  override fun addOnChangeListener(listener: Callback<() -> Unit>): LocalizeSubscription {
140
- val id = LocalizeModule.addListener(listener)
177
+ val id = UUID.randomUUID()
178
+ listeners[id] = listener
179
+ LocalizeModule.listenerAdded()
141
180
  return LocalizeSubscription(
142
181
  Callback.native {
143
- LocalizeModule.removeListener(id)
182
+ listeners.remove(id)
144
183
  Unit
145
184
  }
146
185
  )
@@ -162,6 +201,37 @@ class HybridLocalize : HybridLocalizeSpec() {
162
201
  }
163
202
  }
164
203
 
204
+ override fun getAppLanguage(): String? {
205
+ if (Build.VERSION.SDK_INT < Build.VERSION_CODES.TIRAMISU) return null
206
+ val context = LocalizeModule.context ?: return null
207
+ val locales = context.getSystemService(LocaleManager::class.java).applicationLocales
208
+ return if (locales.isEmpty) null else locales[0].toLanguageTag()
209
+ }
210
+
211
+ override fun setAppLanguage(languageTag: String?): Promise<Unit> {
212
+ if (Build.VERSION.SDK_INT < Build.VERSION_CODES.TIRAMISU) {
213
+ return Promise.rejected(UnsupportedOperationException("Setting the app language needs Android 13 or later. Use openAppLanguageSettings() instead."))
214
+ }
215
+ val context = LocalizeModule.context
216
+ ?: return Promise.rejected(IllegalStateException("nitro-ui-localize is used before the Activity started."))
217
+ val locales = if (languageTag == null) {
218
+ LocaleList.getEmptyLocaleList()
219
+ } else {
220
+ // forLanguageTag drops what it cannot parse ("en-US-x!" becomes "en-US"), so compare the round trip.
221
+ if (!JavaLocale.forLanguageTag(languageTag).toLanguageTag().equals(languageTag, ignoreCase = true)) {
222
+ return Promise.rejected(IllegalArgumentException("\"$languageTag\" is not a BCP 47 language tag."))
223
+ }
224
+ LocaleList.forLanguageTags(languageTag)
225
+ }
226
+ return try {
227
+ // The system recreates the Activity with the new configuration, which fires a change event.
228
+ context.getSystemService(LocaleManager::class.java).applicationLocales = locales
229
+ Promise.resolved(Unit)
230
+ } catch (error: Exception) {
231
+ Promise.rejected(error)
232
+ }
233
+ }
234
+
165
235
  companion object : HybridLocalizeSpec.Companion {
166
236
  override fun constructor() = HybridLocalize()
167
237
  }
@@ -5,6 +5,25 @@ internal import UIKit
5
5
  // The generated struct `Locale` shadows Foundation's, so Foundation's is always written in full.
6
6
 
7
7
  final class HybridLocalize: HybridLocalizeSpec {
8
+ // NitroUI runs JS on the main thread today. The lock keeps this safe if that changes.
9
+ private let lock = NSLock()
10
+ private var listeners: [UUID: any Callback<(), Void>] = [:]
11
+
12
+ override init() throws {
13
+ try super.init()
14
+ LocalizeObserver.shared.register(self)
15
+ }
16
+
17
+ var hasListeners: Bool {
18
+ lock.withLock { !listeners.isEmpty }
19
+ }
20
+
21
+ func emitChange() {
22
+ let current = lock.withLock { Array(listeners.values) }
23
+ // Like Android: an exception in a listener reaches the JS error handler.
24
+ for listener in current { listener.callAndForget() }
25
+ }
26
+
8
27
  func getLocales() throws -> [Locale] { LocalizeValues.locales() }
9
28
  func getCountry() throws -> String { LocalizeValues.country() }
10
29
  func getCurrencies() throws -> [String] { LocalizeValues.currencies() }
@@ -30,14 +49,23 @@ final class HybridLocalize: HybridLocalizeSpec {
30
49
  func usesAutoTimeZone() throws -> Bool? { nil }
31
50
 
32
51
  func addOnChangeListener(listener: any Callback<(), Void>) throws -> LocalizeSubscription {
33
- let id = LocalizeObserver.shared.add {
34
- try? listener.callSync()
35
- }
36
- return LocalizeSubscription(remove: .native {
37
- LocalizeObserver.shared.remove(id)
52
+ let id = UUID()
53
+ lock.withLock { listeners[id] = listener }
54
+ DispatchQueue.main.async { LocalizeObserver.shared.start() }
55
+ return LocalizeSubscription(remove: .native { [weak self] in
56
+ self?.lock.withLock { _ = self?.listeners.removeValue(forKey: id) }
38
57
  })
39
58
  }
40
59
 
60
+ // iOS has no API to set an app's language. The user picks it in the app's Settings page.
61
+ func getAppLanguage() throws -> String? { nil }
62
+
63
+ func setAppLanguage(languageTag: String?) throws -> any Promise<Void> {
64
+ let promise: any Promise<Void> = .pending()
65
+ promise.reject(error: RuntimeError("iOS has no API to set the app language. Use openAppLanguageSettings() instead."))
66
+ return promise
67
+ }
68
+
41
69
  func openAppLanguageSettings() throws -> any Promise<Void> {
42
70
  // The app's Settings page shows a Language row once the app declares two or more localizations.
43
71
  guard let url = URL(string: UIApplication.openSettingsURLString) else {
@@ -56,29 +84,36 @@ final class HybridLocalize: HybridLocalizeSpec {
56
84
  }
57
85
 
58
86
  /// Tells listeners when a localization setting changes, at most once per run-loop turn.
87
+ /// Used on the main thread only, apart from `register`.
59
88
  ///
60
89
  /// Changing the device or app language terminates the app, so a relaunch reads fresh values.
61
90
  final class LocalizeObserver {
62
91
  static let shared = LocalizeObserver()
63
92
 
64
- private var listeners: [UUID: () -> Void] = [:]
93
+ // One HybridLocalize per JS runtime. Weak, so a reloaded runtime's object and its listeners go away.
94
+ private let lock = NSLock()
95
+ private var instances: [WeakInstance] = []
65
96
  private var observers: [any NSObjectProtocol] = []
66
97
  private var snapshot: String?
67
98
  private var emitScheduled = false
68
99
 
69
- func add(_ listener: @escaping () -> Void) -> UUID {
70
- let id = UUID()
71
- listeners[id] = listener
72
- if observers.isEmpty { start() }
73
- return id
100
+ private struct WeakInstance {
101
+ weak var value: HybridLocalize?
74
102
  }
75
103
 
76
- func remove(_ id: UUID) {
77
- listeners.removeValue(forKey: id)
78
- if listeners.isEmpty { stop() }
104
+ func register(_ instance: HybridLocalize) {
105
+ lock.withLock {
106
+ instances.removeAll { $0.value == nil }
107
+ instances.append(WeakInstance(value: instance))
108
+ }
109
+ }
110
+
111
+ private func liveInstances() -> [HybridLocalize] {
112
+ lock.withLock { instances.compactMap(\.value) }.filter(\.hasListeners)
79
113
  }
80
114
 
81
- private func start() {
115
+ func start() {
116
+ if !observers.isEmpty { return }
82
117
  snapshot = LocalizeValues.snapshot()
83
118
  let center = NotificationCenter.default
84
119
  let names: [Notification.Name] = [
@@ -107,10 +142,15 @@ final class LocalizeObserver {
107
142
  DispatchQueue.main.async { [weak self] in
108
143
  guard let self else { return }
109
144
  self.emitScheduled = false
145
+ let targets = self.liveInstances()
146
+ if targets.isEmpty {
147
+ self.stop()
148
+ return
149
+ }
110
150
  let next = LocalizeValues.snapshot()
111
151
  if next == self.snapshot { return }
112
152
  self.snapshot = next
113
- for listener in Array(self.listeners.values) { listener() }
153
+ for instance in targets { instance.emitChange() }
114
154
  }
115
155
  }
116
156
  }
@@ -185,7 +225,8 @@ enum LocalizeValues {
185
225
 
186
226
  static func temperatureUnit() -> TemperatureUnit {
187
227
  // Settings > General > Language & Region > Temperature writes this global default.
188
- // Neither Locale.current nor MeasurementFormatter applies it (tested on iOS 26.5).
228
+ // On a real iPhone MeasurementFormatter follows it too. The simulator does not,
229
+ // so the default is read first to keep both the same.
189
230
  switch UserDefaults.standard.string(forKey: "AppleTemperatureUnit") {
190
231
  case "Celsius": return .celsius
191
232
  case "Fahrenheit": return .fahrenheit
@@ -238,6 +279,9 @@ enum LocalizeValues {
238
279
  String(describing: temperatureUnit()),
239
280
  String(describing: measurementSystem()),
240
281
  String(describing: firstDayOfWeek()),
282
+ String(describing: textDirection()),
283
+ (Foundation.Locale.current.decimalSeparator ?? "") + (Foundation.Locale.current.groupingSeparator ?? ""),
284
+ currencies().joined(separator: ","),
241
285
  ].joined(separator: "|")
242
286
  }
243
287
  }
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "nitro-ui-localize",
3
- "version": "0.1.0",
3
+ "version": "0.2.0",
4
4
  "description": "The user's languages, region, currencies, time zone, 12/24h, units and first weekday for NitroUI apps, with a change listener.",
5
5
  "keywords": [
6
6
  "nitro-ui",
@@ -71,4 +71,8 @@ export declare class Localize extends HybridObject {
71
71
  addOnChangeListener(listener: () => void): LocalizeSubscription
72
72
  /** Opens the system page where the user picks this app's language. */
73
73
  openAppLanguageSettings(): Promise<void>
74
+ /** The language set for this app only, or undefined when the app follows the system. Android 13+, always undefined elsewhere. */
75
+ getAppLanguage(): string | undefined
76
+ /** Sets this app's language. Pass undefined to follow the system again. Android 13+, rejects elsewhere. */
77
+ setAppLanguage(languageTag: string | undefined): Promise<void>
74
78
  }
package/src/index.ts CHANGED
@@ -1,4 +1,4 @@
1
- import { useSyncExternalStore } from 'react'
1
+ import { useMemo, useSyncExternalStore } from 'react'
2
2
  import {
3
3
  Localize as NativeLocalize,
4
4
  type Locale,
@@ -61,6 +61,21 @@ export const openAppLanguageSettings = async (): Promise<void> => {
61
61
  await getNative().openAppLanguageSettings()
62
62
  }
63
63
 
64
+ /**
65
+ * The language set for this app only, as a BCP 47 tag, or `undefined` when the app follows the
66
+ * system languages. Android 13+. Always `undefined` on iOS and older Android.
67
+ */
68
+ export const getAppLanguage = (): string | undefined => getNative().getAppLanguage() ?? undefined
69
+
70
+ /**
71
+ * Sets this app's language on Android 13+, the same setting as the system's per-app language page.
72
+ * The Activity is recreated and a change event fires. Pass `undefined` to follow the system again.
73
+ * Rejects on iOS and on Android 12 and earlier: use `openAppLanguageSettings()` there.
74
+ */
75
+ export const setAppLanguage = async (languageTag: string | undefined): Promise<void> => {
76
+ await getNative().setAppLanguage(languageTag)
77
+ }
78
+
64
79
  // One native listener shared by every subscriber.
65
80
  const subscribers = new Set<() => void>()
66
81
  let nativeSubscription: LocalizeSubscription | undefined
@@ -74,7 +89,16 @@ export function addChangeListener(listener: () => void): LocalizeSubscription {
74
89
  subscribers.add(listener)
75
90
  nativeSubscription ??= getNative().addOnChangeListener(() => {
76
91
  version++
77
- for (const subscriber of [...subscribers]) subscriber()
92
+ // One throwing subscriber must not stop the others. The first error is rethrown afterwards.
93
+ let failure: { error: unknown } | undefined
94
+ for (const subscriber of [...subscribers]) {
95
+ try {
96
+ subscriber()
97
+ } catch (error) {
98
+ failure ??= { error }
99
+ }
100
+ }
101
+ if (failure) throw failure.error
78
102
  })
79
103
  let removed = false
80
104
  return {
@@ -107,6 +131,8 @@ const api = {
107
131
  usesAutoTimeZone,
108
132
  findBestLanguageTag,
109
133
  openAppLanguageSettings,
134
+ getAppLanguage,
135
+ setAppLanguage,
110
136
  }
111
137
 
112
138
  export type LocalizeApi = typeof api & { version: number }
@@ -120,5 +146,6 @@ const getVersion = () => version
120
146
  /** The API, re-rendering the component whenever a localization setting changes. */
121
147
  export function useLocalize(): LocalizeApi {
122
148
  const current = useSyncExternalStore(subscribe, getVersion)
123
- return { ...api, version: current }
149
+ // A new object only when a setting changed, so it can be a dependency of other hooks.
150
+ return useMemo(() => ({ ...api, version: current }), [current])
124
151
  }