nitro-ui-localize 0.0.0-stage → 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/LICENSE ADDED
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2026 Jaydeep Agravat
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in all
13
+ copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
+ SOFTWARE.
package/Package.swift ADDED
@@ -0,0 +1,126 @@
1
+ // swift-tools-version: 6.4
2
+
3
+ import Foundation
4
+ import PackageDescription
5
+
6
+ let name = "NitroLocalize"
7
+ let generated = "nitrogen/generated"
8
+ let nitroDependencies: [Target.Dependency] = [
9
+ .product(name: "NitroModules", package: "nitro-core")
10
+ ]
11
+ let cxxSettings: [CXXSetting] = [
12
+ .define("DEBUG", .when(configuration: .debug)),
13
+ .define("NDEBUG", .when(configuration: .release)),
14
+ .disableWarning("nullability-extension"),
15
+ ]
16
+ let swiftSources = ["ios", "\(generated)/apple/swift"]
17
+ let bridgeSources = ["c++", "NitroLocalize-Swift-Cxx-Bridge.cpp", "NitroLocalizeAutolinking.cpp"]
18
+ // Handwritten C++ in cpp/ is shared with Android and compiles with the generated shared C++.
19
+ let userCxxSources = ["cpp"].filter(exists)
20
+ let cxxSources = ["\(generated)/shared/c++"] + userCxxSources
21
+ func userHeaderSearchPaths(relativeTo targetPath: String) -> [CXXSetting] {
22
+ let packageDirectory = URL(fileURLWithPath: Context.packageDirectory)
23
+ let targetComponents = packageDirectory.appendingPathComponent(targetPath).standardizedFileURL.pathComponents
24
+ return userCxxSources.map { source in
25
+ let sourceURL = packageDirectory.appendingPathComponent(source)
26
+ var isDirectory: ObjCBool = false
27
+ FileManager.default.fileExists(atPath: sourceURL.path, isDirectory: &isDirectory)
28
+ let directory = isDirectory.boolValue ? sourceURL : sourceURL.deletingLastPathComponent()
29
+ let headerComponents = directory.standardizedFileURL.pathComponents
30
+ let commonCount = zip(targetComponents, headerComponents).prefix { $0.0 == $0.1 }.count
31
+ let relativeComponents =
32
+ Array(repeating: "..", count: targetComponents.count - commonCount)
33
+ + headerComponents.dropFirst(commonCount)
34
+ return .headerSearchPath(relativeComponents.isEmpty ? "." : relativeComponents.joined(separator: "/"))
35
+ }
36
+ }
37
+
38
+ // Bare-host integration. Nitrogen generates the bindings; this manifest owns the targets.
39
+ let package = Package(
40
+ name: name,
41
+ platforms: [.iOS(.v16), .macOS(.v13)],
42
+ products: [
43
+ .library(name: name, targets: ["\(name)Cxx", name, "\(name)SwiftBridge"])
44
+ ],
45
+ dependencies: [
46
+ .package(path: "../nitro-core")
47
+ ],
48
+ targets: [
49
+ .target(
50
+ name: "\(name)Cxx",
51
+ dependencies: nitroDependencies,
52
+ path: ".",
53
+ exclude: excludes(in: ".", keeping: cxxSources),
54
+ sources: cxxSources,
55
+ publicHeadersPath: "\(generated)/shared/c++/include",
56
+ cxxSettings: cxxSettings + userHeaderSearchPaths(relativeTo: ".")
57
+ ),
58
+ .target(
59
+ name: "\(name)AppleCxx",
60
+ dependencies: [.target(name: "\(name)Cxx")] + nitroDependencies,
61
+ path: "\(generated)/apple/\(name)AppleCxx",
62
+ cxxSettings: cxxSettings
63
+ ),
64
+ .target(
65
+ name: name,
66
+ dependencies: [.target(name: "\(name)AppleCxx")] + nitroDependencies,
67
+ path: ".",
68
+ exclude: excludes(in: ".", keeping: swiftSources),
69
+ sources: swiftSources,
70
+ cxxSettings: cxxSettings,
71
+ swiftSettings: [
72
+ // UIKit implementations run synchronously on the host's main thread.
73
+ .swiftLanguageMode(.v5),
74
+ .unsafeFlags(["-strict-concurrency=minimal"]),
75
+ .enableUpcomingFeature("InternalImportsByDefault"),
76
+ .enableUpcomingFeature("MemberImportVisibility"),
77
+ .interoperabilityMode(.Cxx),
78
+ .unsafeFlags(["-Xfrontend", "-clang-header-expose-decls=has-expose-attr-or-stdlib"]),
79
+ .unsafeFlags([
80
+ "-Xfrontend", "-clang-header-expose-module",
81
+ "-Xfrontend", "NitroModules=NitroModules-Swift.h",
82
+ ]),
83
+ ]
84
+ ),
85
+ .target(
86
+ name: "\(name)SwiftBridge",
87
+ dependencies: [.target(name: name), .target(name: "\(name)AppleCxx")] + nitroDependencies,
88
+ path: "\(generated)/apple",
89
+ exclude: excludes(in: "\(generated)/apple", keeping: bridgeSources) + ["c++/include"],
90
+ sources: bridgeSources,
91
+ publicHeadersPath: "c++/include",
92
+ cxxSettings: cxxSettings + userHeaderSearchPaths(relativeTo: "\(generated)/apple") + [
93
+ .unsafeFlags(["-I${GENERATED_MODULEMAP_DIR}", "-fno-modules"])
94
+ ]
95
+ ),
96
+ ],
97
+ cxxLanguageStandard: .cxx20
98
+ )
99
+
100
+ func exists(_ path: String) -> Bool {
101
+ FileManager.default.fileExists(
102
+ atPath: URL(fileURLWithPath: Context.packageDirectory).appendingPathComponent(path).path
103
+ )
104
+ }
105
+
106
+ func excludes(in path: String, keeping sources: [String]) -> [String] {
107
+ var parents: Set<String> = [""]
108
+ for source in sources {
109
+ var components = source.split(separator: "/").dropLast()
110
+ while !components.isEmpty {
111
+ parents.insert(components.joined(separator: "/"))
112
+ components = components.dropLast()
113
+ }
114
+ }
115
+ let root = URL(fileURLWithPath: Context.packageDirectory).appendingPathComponent(path)
116
+ return parents.sorted().flatMap { parent in
117
+ let entries =
118
+ (try? FileManager.default.contentsOfDirectory(
119
+ atPath: root.appendingPathComponent(parent).path)) ?? []
120
+ return entries.sorted().compactMap { entry in
121
+ let entryPath = parent.isEmpty ? entry : "\(parent)/\(entry)"
122
+ return entry.hasPrefix(".") || sources.contains(entryPath) || parents.contains(entryPath)
123
+ ? nil : entryPath
124
+ }
125
+ }
126
+ }
package/README.md CHANGED
@@ -1,3 +1,191 @@
1
- # Temporary Holding Version
1
+ # nitro-ui-localize
2
2
 
3
- This version is a temporary placeholder for this package. An operational version to replace this has been submitted for review and is awaiting a staged release.
3
+ The user's languages, region, currencies, time zone, 12/24h clock, units and first weekday for [NitroUI](https://nitro-ui.com) apps, read from the operating system, plus a listener for when they change.
4
+
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
+
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
+
9
+ ## Install
10
+
11
+ ```sh
12
+ bun add nitro-ui-localize
13
+ ```
14
+
15
+ `bun install` runs `nitro-ui prepare`, which links the module. Rebuild the app.
16
+
17
+ ## Usage
18
+
19
+ ```ts
20
+ import i18next from 'i18next'
21
+ import { addChangeListener, findBestLanguageTag } from 'nitro-ui-localize'
22
+
23
+ const supported = ['en', 'hi', 'gu', 'de', 'ar']
24
+
25
+ function pickLanguage() {
26
+ const best = findBestLanguageTag(supported)
27
+ return best?.languageTag ?? 'en'
28
+ }
29
+
30
+ i18next.init({ lng: pickLanguage(), resources })
31
+ addChangeListener(() => i18next.changeLanguage(pickLanguage()))
32
+ ```
33
+
34
+ In components, `useLocalize()` returns the same API and re-renders when a setting changes:
35
+
36
+ ```tsx
37
+ import { useLocalize } from 'nitro-ui-localize'
38
+
39
+ function Price({ amount }: { amount: number }) {
40
+ const { getCurrencies } = useLocalize()
41
+ const currency = getCurrencies()[0]
42
+ return <Text>{new Intl.NumberFormat(undefined, { style: 'currency', currency }).format(amount)}</Text>
43
+ }
44
+ ```
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
+
63
+ ## API
64
+
65
+ All getters are synchronous.
66
+
67
+ | Function | Returns | Example |
68
+ |---|---|---|
69
+ | `getLocales()` | The user's preferred languages, most preferred first | `[{ languageTag: 'hi-IN', languageCode: 'hi', countryCode: 'IN', isRTL: false }, …]` |
70
+ | `getCountry()` | Device region | `'IN'` |
71
+ | `getCurrencies()` | Currencies of the region and preferred languages | `['INR', 'USD']` |
72
+ | `getCalendar()` | Calendar | `'gregorian'`, `'buddhist'` |
73
+ | `getNumberFormatSettings()` | Separators | `{ decimalSeparator: '.', groupingSeparator: ',' }` |
74
+ | `getTemperatureUnit()` | Follows the user's temperature preference | `'celsius'` |
75
+ | `getMeasurementSystem()` | | `'metric'`, `'us'`, `'uk'` |
76
+ | `usesMetricSystem()` | `getMeasurementSystem() !== 'us'` | `true` |
77
+ | `getFirstDayOfWeek()` | Follows the user's first-day preference | `'monday'` |
78
+ | `getTimeZone()` | IANA time zone | `'Asia/Kolkata'` |
79
+ | `getTextDirection()` | Direction the app's UI is laid out in | `'ltr'` |
80
+ | `uses24HourClock()` | Follows the user's 24-hour switch | `true` |
81
+ | `usesAutoDateAndTime()` | Android only, `undefined` on iOS | `true` |
82
+ | `usesAutoTimeZone()` | Android only, `undefined` on iOS | `true` |
83
+ | `findBestLanguageTag(tags)` | First of your tags that matches the user's languages, in the user's order | `{ languageTag: 'hi', isRTL: false }` |
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>` |
87
+ | `addChangeListener(fn)` | Calls `fn` when any setting above changes | `{ remove() }` |
88
+ | `useLocalize()` | The API, re-rendering on change | |
89
+
90
+ `getTextDirection()` is the direction your app's UI uses. It can differ from `getLocales()[0].isRTL`, for example when the app does not declare RTL support.
91
+
92
+ ## Why not just `Intl`?
93
+
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:
95
+
96
+ | Need | `Intl` | nitro-ui-localize |
97
+ |---|---|---|
98
+ | The user's language when your translations live in JS | ❌ on iOS, `Intl` only reports languages the app bundle declares: a French user of an English-only bundle gets `en-US` | ✅ `fr-US` |
99
+ | Ordered list of preferred languages | ❌ no `navigator.languages`, one locale only | ✅ |
100
+ | User turned on 24-hour time | ❌ still `h12` / `8 PM` | ✅ `true` |
101
+ | Temperature unit, first weekday preferences | ❌ no `Intl.Locale`, no week info | ✅ |
102
+ | Text direction of the app | ❌ | ✅ |
103
+ | Know when a setting changes | ❌ | ✅ `addChangeListener` |
104
+ | Know that the time zone changed while running | ❌ no event, you would have to poll | ✅ change event with the new zone |
105
+
106
+ `Intl.PluralRules`, `RelativeTimeFormat`, `ListFormat` and `DisplayNames` are also missing on both platforms, so i18next plurals need a polyfill such as `@formatjs/intl-pluralrules`.
107
+
108
+ ## Platform support
109
+
110
+ | | iOS | Android |
111
+ |---|---|---|
112
+ | Getters | ✅ tested on iOS 26.5 | ✅ tested on API 30, 35 and 37 |
113
+ | 24-hour, temperature, first weekday preferences | ✅ (Settings > Language & Region) | ✅ (24-hour switch; `-u-mu-`, `-u-fw-` regional preferences) |
114
+ | `usesAutoDateAndTime`, `usesAutoTimeZone` | `undefined` | ✅ |
115
+ | `openAppLanguageSettings` | Opens the app's Settings page | ✅ (rejects before Android 13) |
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.
120
+
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 |
127
+
128
+ ## Per-app language
129
+
130
+ Both platforms only offer a per-app language when the app declares its languages:
131
+
132
+ - **iOS:** list them in `CFBundleLocalizations` in `Info.plist` (two or more).
133
+ - **Android 13+:** add `res/xml/locales_config.xml` and `android:localeConfig="@xml/locales_config"` on `<application>`.
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
+
153
+ ## What this library does not do
154
+
155
+ | Not doing | Use instead |
156
+ |---|---|
157
+ | Translate strings, plurals | i18next, Lingui, FormatJS |
158
+ | Format dates, numbers, currencies | `Intl` |
159
+ | RTL layout (`start`/`end`, mirroring) | NitroUI core ([#879](https://github.com/margelo/nitro-ui/issues/879)) |
160
+ | Save the chosen language | `nitro-mmkv` |
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 |
162
+
163
+ ## Coming from react-native-localize
164
+
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.
166
+
167
+ ## Development
168
+
169
+ ```sh
170
+ bun install
171
+ bun run typecheck # generates the Nitro bindings, then runs tsc
172
+ bun run test # unit tests for findBestLanguageTag
173
+
174
+ cd example
175
+ bun install
176
+ bun run start # then press i or a
177
+ bun run test:ios # harness tests inside the app on a simulator
178
+ bun run test:android
179
+ ```
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
+
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.
184
+
185
+ ## Credits
186
+
187
+ The API and the language-matching order come from [react-native-localize](https://github.com/zoontek/react-native-localize) by Mathieu Acthernoene (MIT). The package layout follows [nitro-ui-haptics](https://github.com/DewXIT/nitro-ui-haptics).
188
+
189
+ ## License
190
+
191
+ MIT
@@ -0,0 +1,366 @@
1
+ package com.margelo.nitro.nitrouilocalize
2
+
3
+ import android.app.LocaleManager
4
+ import android.content.BroadcastReceiver
5
+ import android.content.Context
6
+ import android.content.Intent
7
+ import android.content.IntentFilter
8
+ import android.database.ContentObserver
9
+ import android.net.Uri
10
+ import android.os.Build
11
+ import android.os.Handler
12
+ import android.os.LocaleList
13
+ import android.os.Looper
14
+ import android.provider.Settings
15
+ import android.text.TextUtils
16
+ import android.text.format.DateFormat
17
+ import android.util.LayoutDirection
18
+ import com.margelo.nitro.core.Callback
19
+ import com.margelo.nitro.core.Promise
20
+ import com.margelo.nitro.core.callAndForget
21
+ import com.margelo.nitroui.runtime.NitroActivity
22
+ import com.margelo.nitroui.runtime.NitroActivityInitializer
23
+ import java.lang.ref.WeakReference
24
+ import java.text.DecimalFormatSymbols
25
+ import java.util.Currency
26
+ import java.util.TimeZone
27
+ import java.util.UUID
28
+ import java.util.concurrent.ConcurrentHashMap
29
+ import java.util.concurrent.CopyOnWriteArrayList
30
+ import java.util.Locale as JavaLocale
31
+
32
+ /**
33
+ * Keeps the application context and the current Activity, and tells listeners when a
34
+ * localization setting changes.
35
+ *
36
+ * Changing the language or layout direction recreates the Activity, which calls [onCreate].
37
+ * Time zone and clock changes arrive as broadcasts, and 12/24h changes through a settings
38
+ * observer, while the Activity keeps running.
39
+ */
40
+ object LocalizeModule : NitroActivityInitializer {
41
+ internal var context: Context? = null
42
+ internal var activity = WeakReference<NitroActivity>(null)
43
+
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>>()
46
+ private val mainHandler = Handler(Looper.getMainLooper())
47
+ private var snapshot: String? = null
48
+ private var emitScheduled = false
49
+ private var receiverRegistered = false
50
+
51
+ override fun onCreate(activity: NitroActivity) {
52
+ context = activity.applicationContext
53
+ this.activity = WeakReference(activity)
54
+ registerReceiver(activity.applicationContext)
55
+ scheduleEmitIfChanged()
56
+ }
57
+
58
+ internal fun register(instance: HybridLocalize) {
59
+ instances.removeAll { it.get() == null }
60
+ instances.add(WeakReference(instance))
61
+ }
62
+
63
+ internal fun listenerAdded() {
64
+ if (snapshot == null) snapshot = currentSnapshot()
65
+ }
66
+
67
+ private fun liveInstances() = instances.mapNotNull { it.get() }.filter { it.hasListeners }
68
+
69
+ private fun registerReceiver(context: Context) {
70
+ if (receiverRegistered) return
71
+ receiverRegistered = true
72
+ val filter = IntentFilter().apply {
73
+ addAction(Intent.ACTION_LOCALE_CHANGED)
74
+ addAction(Intent.ACTION_TIMEZONE_CHANGED)
75
+ addAction(Intent.ACTION_TIME_CHANGED)
76
+ addAction(Intent.ACTION_CONFIGURATION_CHANGED)
77
+ }
78
+ val receiver = object : BroadcastReceiver() {
79
+ override fun onReceive(context: Context, intent: Intent) {
80
+ if (intent.action == Intent.ACTION_TIMEZONE_CHANGED) TimeZone.setDefault(null)
81
+ scheduleEmitIfChanged()
82
+ }
83
+ }
84
+ // System broadcasts only; no other app may send these.
85
+ if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.TIRAMISU) {
86
+ context.registerReceiver(receiver, filter, Context.RECEIVER_NOT_EXPORTED)
87
+ } else {
88
+ context.registerReceiver(receiver, filter)
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
+ }
102
+ }
103
+
104
+ // Several broadcasts can arrive for one change. Compare once per main-loop turn.
105
+ private fun scheduleEmitIfChanged() {
106
+ if (emitScheduled) return
107
+ emitScheduled = true
108
+ mainHandler.post {
109
+ emitScheduled = false
110
+ val targets = liveInstances()
111
+ if (targets.isEmpty()) {
112
+ snapshot = null
113
+ return@post
114
+ }
115
+ val next = currentSnapshot()
116
+ if (next == snapshot) return@post
117
+ snapshot = next
118
+ for (instance in targets) instance.emitChange()
119
+ }
120
+ }
121
+
122
+ private fun currentSnapshot(): String {
123
+ val values = LocalizeValues(context ?: return "")
124
+ return listOf(
125
+ values.locales().joinToString(",") { it.languageTag },
126
+ values.country(),
127
+ values.timeZone(),
128
+ values.uses24HourClock().toString(),
129
+ values.textDirection().name,
130
+ values.calendar(),
131
+ values.temperatureUnit().name,
132
+ values.measurementSystem().name,
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(),
138
+ ).joinToString("|")
139
+ }
140
+ }
141
+
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
+
157
+ private val values: LocalizeValues
158
+ get() = LocalizeValues(
159
+ LocalizeModule.context ?: throw IllegalStateException("nitro-ui-localize is used before the Activity started.")
160
+ )
161
+
162
+ override fun getLocales() = values.locales().toTypedArray()
163
+ override fun getCountry() = values.country()
164
+ override fun getCurrencies() = values.currencies().toTypedArray()
165
+ override fun getCalendar() = values.calendar()
166
+ override fun getNumberFormatSettings() = values.numberFormatSettings()
167
+ override fun getTemperatureUnit() = values.temperatureUnit()
168
+ override fun getMeasurementSystem() = values.measurementSystem()
169
+ override fun getFirstDayOfWeek() = values.firstDayOfWeek()
170
+ override fun getTimeZone() = values.timeZone()
171
+ override fun getTextDirection() = values.textDirection()
172
+ override fun uses24HourClock() = values.uses24HourClock()
173
+ override fun usesAutoDateAndTime(): Boolean? = values.globalSetting(Settings.Global.AUTO_TIME)
174
+ override fun usesAutoTimeZone(): Boolean? = values.globalSetting(Settings.Global.AUTO_TIME_ZONE)
175
+
176
+ override fun addOnChangeListener(listener: Callback<() -> Unit>): LocalizeSubscription {
177
+ val id = UUID.randomUUID()
178
+ listeners[id] = listener
179
+ LocalizeModule.listenerAdded()
180
+ return LocalizeSubscription(
181
+ Callback.native {
182
+ listeners.remove(id)
183
+ Unit
184
+ }
185
+ )
186
+ }
187
+
188
+ override fun openAppLanguageSettings(): Promise<Unit> {
189
+ if (Build.VERSION.SDK_INT < Build.VERSION_CODES.TIRAMISU) {
190
+ return Promise.rejected(UnsupportedOperationException("Per-app language settings need Android 13 or later."))
191
+ }
192
+ val context = LocalizeModule.activity.get() ?: LocalizeModule.context
193
+ ?: return Promise.rejected(IllegalStateException("No Activity to open the settings from."))
194
+ val intent = Intent(Settings.ACTION_APP_LOCALE_SETTINGS, Uri.fromParts("package", context.packageName, null))
195
+ if (context !is NitroActivity) intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK)
196
+ return try {
197
+ context.startActivity(intent)
198
+ Promise.resolved(Unit)
199
+ } catch (error: Exception) {
200
+ Promise.rejected(error)
201
+ }
202
+ }
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
+
235
+ companion object : HybridLocalizeSpec.Companion {
236
+ override fun constructor() = HybridLocalize()
237
+ }
238
+ }
239
+
240
+ /** Reads every value fresh, so a change is visible on the next call. */
241
+ internal class LocalizeValues(private val context: Context) {
242
+ private val configLocales: LocaleList
243
+ get() = context.resources.configuration.locales
244
+
245
+ private val primary: JavaLocale
246
+ get() = configLocales[0] ?: JavaLocale.getDefault()
247
+
248
+ fun locales(): List<Locale> {
249
+ val fallbackCountry = country()
250
+ val seen = mutableSetOf<String>()
251
+ val result = mutableListOf<Locale>()
252
+ // The configuration's list follows the per-app language when one is set.
253
+ for (i in 0 until configLocales.size()) {
254
+ val locale = configLocales[i]
255
+ val language = languageCode(locale)
256
+ val script = locale.script.ifEmpty { null }
257
+ val country = locale.country.ifEmpty { fallbackCountry }
258
+ val tag = listOfNotNull(language, script, country).joinToString("-")
259
+ if (!seen.add(tag)) continue
260
+ val isRTL = TextUtils.getLayoutDirectionFromLocale(locale) == LayoutDirection.RTL
261
+ result.add(Locale(language, script, country, tag, isRTL))
262
+ }
263
+ if (result.isEmpty()) result.add(Locale("en", null, fallbackCountry, "en-$fallbackCountry", false))
264
+ return result
265
+ }
266
+
267
+ fun country(): String = primary.country.ifEmpty { "US" }
268
+
269
+ fun currencies(): List<String> {
270
+ val codes = linkedSetOf<String>()
271
+ for (i in 0 until configLocales.size()) {
272
+ try {
273
+ Currency.getInstance(configLocales[i])?.currencyCode?.let(codes::add)
274
+ } catch (_: IllegalArgumentException) {
275
+ // A locale without a region has no currency.
276
+ }
277
+ }
278
+ if (codes.isEmpty()) codes.add("USD")
279
+ return codes.toList()
280
+ }
281
+
282
+ fun calendar(): String {
283
+ val type = android.icu.util.Calendar.getInstance(android.icu.util.ULocale.forLocale(primary)).type
284
+ // Same names as react-native-localize's Calendar type.
285
+ return when (type) {
286
+ "buddhist", "coptic", "ethiopic", "ethiopic-amete-alem", "hebrew", "indian", "islamic",
287
+ "islamic-civil", "iso8601", "japanese", "persian" -> type
288
+ "islamic-umalqura" -> "islamic-umm-al-qura"
289
+ "islamic-tbla" -> "islamic-tabular"
290
+ else -> "gregorian"
291
+ }
292
+ }
293
+
294
+ fun numberFormatSettings(): NumberFormatSettings {
295
+ val symbols = DecimalFormatSymbols.getInstance(primary)
296
+ return NumberFormatSettings(symbols.decimalSeparator.toString(), symbols.groupingSeparator.toString())
297
+ }
298
+
299
+ fun temperatureUnit(): TemperatureUnit {
300
+ if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.TIRAMISU) {
301
+ // Android 14 regional preferences add "-u-mu-" to the locale; ICU's "weather" usage reads it.
302
+ val unit = android.icu.number.NumberFormatter.withLocale(primary)
303
+ .usage("weather")
304
+ .unit(android.icu.util.MeasureUnit.CELSIUS)
305
+ .format(1)
306
+ .outputUnit
307
+ return if (unit == android.icu.util.MeasureUnit.FAHRENHEIT) TemperatureUnit.FAHRENHEIT else TemperatureUnit.CELSIUS
308
+ }
309
+ return if (country() in FAHRENHEIT_COUNTRIES) TemperatureUnit.FAHRENHEIT else TemperatureUnit.CELSIUS
310
+ }
311
+
312
+ fun measurementSystem(): MeasurementSystem {
313
+ if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.P) {
314
+ return when (android.icu.util.LocaleData.getMeasurementSystem(android.icu.util.ULocale.forLocale(primary))) {
315
+ android.icu.util.LocaleData.MeasurementSystem.US -> MeasurementSystem.US
316
+ android.icu.util.LocaleData.MeasurementSystem.UK -> MeasurementSystem.UK
317
+ else -> MeasurementSystem.METRIC
318
+ }
319
+ }
320
+ return if (country() in US_SYSTEM_COUNTRIES) MeasurementSystem.US else MeasurementSystem.METRIC
321
+ }
322
+
323
+ fun firstDayOfWeek(): Weekday {
324
+ // ICU reads a "-u-fw-" regional preference from the locale when Android 14 adds one.
325
+ val day = android.icu.util.Calendar.getInstance(android.icu.util.ULocale.forLocale(primary)).firstDayOfWeek
326
+ return when (day) {
327
+ android.icu.util.Calendar.MONDAY -> Weekday.MONDAY
328
+ android.icu.util.Calendar.TUESDAY -> Weekday.TUESDAY
329
+ android.icu.util.Calendar.WEDNESDAY -> Weekday.WEDNESDAY
330
+ android.icu.util.Calendar.THURSDAY -> Weekday.THURSDAY
331
+ android.icu.util.Calendar.FRIDAY -> Weekday.FRIDAY
332
+ android.icu.util.Calendar.SATURDAY -> Weekday.SATURDAY
333
+ else -> Weekday.SUNDAY
334
+ }
335
+ }
336
+
337
+ fun timeZone(): String = TimeZone.getDefault().id
338
+
339
+ fun textDirection(): TextDirection {
340
+ val configuration = (LocalizeModule.activity.get() ?: context).resources.configuration
341
+ return if (configuration.layoutDirection == LayoutDirection.RTL) TextDirection.RTL else TextDirection.LTR
342
+ }
343
+
344
+ fun uses24HourClock(): Boolean = DateFormat.is24HourFormat(context)
345
+
346
+ fun globalSetting(name: String): Boolean? =
347
+ try {
348
+ Settings.Global.getInt(context.contentResolver, name) != 0
349
+ } catch (_: Settings.SettingNotFoundException) {
350
+ null
351
+ }
352
+
353
+ private fun languageCode(locale: JavaLocale): String =
354
+ when (val language = locale.language) {
355
+ "iw" -> "he"
356
+ "in" -> "id"
357
+ "ji" -> "yi"
358
+ "" -> "en"
359
+ else -> language
360
+ }
361
+
362
+ private companion object {
363
+ val FAHRENHEIT_COUNTRIES = setOf("BS", "BZ", "KY", "PR", "PW", "US")
364
+ val US_SYSTEM_COUNTRIES = setOf("LR", "MM", "US")
365
+ }
366
+ }
@@ -0,0 +1,287 @@
1
+ internal import Foundation
2
+ internal import NitroModules
3
+ internal import UIKit
4
+
5
+ // The generated struct `Locale` shadows Foundation's, so Foundation's is always written in full.
6
+
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
+
27
+ func getLocales() throws -> [Locale] { LocalizeValues.locales() }
28
+ func getCountry() throws -> String { LocalizeValues.country() }
29
+ func getCurrencies() throws -> [String] { LocalizeValues.currencies() }
30
+ func getCalendar() throws -> String { LocalizeValues.calendar() }
31
+
32
+ func getNumberFormatSettings() throws -> NumberFormatSettings {
33
+ let locale = Foundation.Locale.current
34
+ return NumberFormatSettings(
35
+ decimalSeparator: locale.decimalSeparator ?? ".",
36
+ groupingSeparator: locale.groupingSeparator ?? ","
37
+ )
38
+ }
39
+
40
+ func getTemperatureUnit() throws -> TemperatureUnit { LocalizeValues.temperatureUnit() }
41
+ func getMeasurementSystem() throws -> MeasurementSystem { LocalizeValues.measurementSystem() }
42
+ func getFirstDayOfWeek() throws -> Weekday { LocalizeValues.firstDayOfWeek() }
43
+ func getTimeZone() throws -> String { TimeZone.current.identifier }
44
+ func getTextDirection() throws -> TextDirection { LocalizeValues.textDirection() }
45
+ func uses24HourClock() throws -> Bool { LocalizeValues.uses24HourClock() }
46
+
47
+ // iOS has no public API for these settings.
48
+ func usesAutoDateAndTime() throws -> Bool? { nil }
49
+ func usesAutoTimeZone() throws -> Bool? { nil }
50
+
51
+ func addOnChangeListener(listener: any Callback<(), Void>) throws -> LocalizeSubscription {
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) }
57
+ })
58
+ }
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
+
69
+ func openAppLanguageSettings() throws -> any Promise<Void> {
70
+ // The app's Settings page shows a Language row once the app declares two or more localizations.
71
+ guard let url = URL(string: UIApplication.openSettingsURLString) else {
72
+ throw RuntimeError("The Settings URL is unavailable.")
73
+ }
74
+ let promise: any Promise<Void> = .pending()
75
+ UIApplication.shared.open(url) { opened in
76
+ if opened {
77
+ promise.resolve()
78
+ } else {
79
+ promise.reject(error: RuntimeError("Settings could not be opened."))
80
+ }
81
+ }
82
+ return promise
83
+ }
84
+ }
85
+
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`.
88
+ ///
89
+ /// Changing the device or app language terminates the app, so a relaunch reads fresh values.
90
+ final class LocalizeObserver {
91
+ static let shared = LocalizeObserver()
92
+
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] = []
96
+ private var observers: [any NSObjectProtocol] = []
97
+ private var snapshot: String?
98
+ private var emitScheduled = false
99
+
100
+ private struct WeakInstance {
101
+ weak var value: HybridLocalize?
102
+ }
103
+
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)
113
+ }
114
+
115
+ func start() {
116
+ if !observers.isEmpty { return }
117
+ snapshot = LocalizeValues.snapshot()
118
+ let center = NotificationCenter.default
119
+ let names: [Notification.Name] = [
120
+ NSLocale.currentLocaleDidChangeNotification,
121
+ .NSSystemTimeZoneDidChange,
122
+ // A safety net for anything that changed while the app was suspended.
123
+ UIApplication.willEnterForegroundNotification,
124
+ ]
125
+ observers = names.map { name in
126
+ center.addObserver(forName: name, object: nil, queue: .main) { [weak self] notification in
127
+ if notification.name == .NSSystemTimeZoneDidChange { NSTimeZone.resetSystemTimeZone() }
128
+ self?.scheduleEmitIfChanged()
129
+ }
130
+ }
131
+ }
132
+
133
+ private func stop() {
134
+ for observer in observers { NotificationCenter.default.removeObserver(observer) }
135
+ observers = []
136
+ snapshot = nil
137
+ }
138
+
139
+ private func scheduleEmitIfChanged() {
140
+ if emitScheduled { return }
141
+ emitScheduled = true
142
+ DispatchQueue.main.async { [weak self] in
143
+ guard let self else { return }
144
+ self.emitScheduled = false
145
+ let targets = self.liveInstances()
146
+ if targets.isEmpty {
147
+ self.stop()
148
+ return
149
+ }
150
+ let next = LocalizeValues.snapshot()
151
+ if next == self.snapshot { return }
152
+ self.snapshot = next
153
+ for instance in targets { instance.emitChange() }
154
+ }
155
+ }
156
+ }
157
+
158
+ /// Reads every value fresh from `Locale.current`, so a change is visible on the next call.
159
+ enum LocalizeValues {
160
+ static func locales() -> [Locale] {
161
+ let fallbackCountry = country()
162
+ var seen = Set<String>()
163
+ var result: [Locale] = []
164
+ // Already adjusted for a per-app language.
165
+ for identifier in Foundation.Locale.preferredLanguages {
166
+ let language = Foundation.Locale.Language(identifier: identifier)
167
+ guard let languageCode = language.languageCode?.identifier else { continue }
168
+ // `language.script` fills in the implied script ("Latn" for "en-IN"). Only keep a script
169
+ // the tag spells out, such as "zh-Hant-HK", like react-native-localize.
170
+ let script = NSLocale(localeIdentifier: identifier).object(forKey: .scriptCode) as? String
171
+ var country = language.region?.identifier ?? fallbackCountry
172
+ if country == "419" { country = "UN" }
173
+ let tag = [languageCode, script, country].compactMap { $0 }.joined(separator: "-")
174
+ guard seen.insert(tag).inserted else { continue }
175
+ result.append(Locale(
176
+ languageCode: languageCode,
177
+ scriptCode: script,
178
+ countryCode: country,
179
+ languageTag: tag,
180
+ isRTL: language.characterDirection == .rightToLeft
181
+ ))
182
+ }
183
+ if result.isEmpty {
184
+ result.append(Locale(languageCode: "en", scriptCode: nil, countryCode: fallbackCountry, languageTag: "en-\(fallbackCountry)", isRTL: false))
185
+ }
186
+ return result
187
+ }
188
+
189
+ static func country() -> String {
190
+ // The simulator can report no region.
191
+ Foundation.Locale.current.region?.identifier ?? "US"
192
+ }
193
+
194
+ static func currencies() -> [String] {
195
+ var codes: [String] = []
196
+ func add(_ code: String?) {
197
+ if let code, !codes.contains(code) { codes.append(code) }
198
+ }
199
+ add(Foundation.Locale.current.currency?.identifier)
200
+ for identifier in Foundation.Locale.preferredLanguages {
201
+ add(Foundation.Locale(identifier: identifier).currency?.identifier)
202
+ }
203
+ return codes.isEmpty ? ["USD"] : codes
204
+ }
205
+
206
+ /// Same names as react-native-localize's Calendar type.
207
+ static func calendar() -> String {
208
+ switch Foundation.Locale.current.calendar.identifier {
209
+ case .buddhist: return "buddhist"
210
+ case .coptic: return "coptic"
211
+ case .ethiopicAmeteMihret: return "ethiopic"
212
+ case .ethiopicAmeteAlem: return "ethiopic-amete-alem"
213
+ case .hebrew: return "hebrew"
214
+ case .indian: return "indian"
215
+ case .islamic: return "islamic"
216
+ case .islamicCivil: return "islamic-civil"
217
+ case .islamicTabular: return "islamic-tabular"
218
+ case .islamicUmmAlQura: return "islamic-umm-al-qura"
219
+ case .iso8601: return "iso8601"
220
+ case .japanese: return "japanese"
221
+ case .persian: return "persian"
222
+ default: return "gregorian"
223
+ }
224
+ }
225
+
226
+ static func temperatureUnit() -> TemperatureUnit {
227
+ // Settings > General > Language & Region > Temperature writes this global default.
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.
230
+ switch UserDefaults.standard.string(forKey: "AppleTemperatureUnit") {
231
+ case "Celsius": return .celsius
232
+ case "Fahrenheit": return .fahrenheit
233
+ default: break
234
+ }
235
+ // Not set: the region's default.
236
+ let formatter = MeasurementFormatter()
237
+ formatter.locale = .current
238
+ let text = formatter.string(from: Measurement(value: 0, unit: UnitTemperature.celsius))
239
+ return text.contains("F") ? .fahrenheit : .celsius
240
+ }
241
+
242
+ static func measurementSystem() -> MeasurementSystem {
243
+ switch Foundation.Locale.current.measurementSystem {
244
+ case .us: return .us
245
+ case .uk: return .uk
246
+ default: return .metric
247
+ }
248
+ }
249
+
250
+ static func firstDayOfWeek() -> Weekday {
251
+ switch Foundation.Locale.current.firstDayOfWeek {
252
+ case .monday: return .monday
253
+ case .tuesday: return .tuesday
254
+ case .wednesday: return .wednesday
255
+ case .thursday: return .thursday
256
+ case .friday: return .friday
257
+ case .saturday: return .saturday
258
+ default: return .sunday
259
+ }
260
+ }
261
+
262
+ static func textDirection() -> TextDirection {
263
+ UIApplication.shared.userInterfaceLayoutDirection == .rightToLeft ? .rtl : .ltr
264
+ }
265
+
266
+ static func uses24HourClock() -> Bool {
267
+ // The "j" skeleton resolves to the user's preferred hour symbol, including the 24-Hour Time switch.
268
+ let format = DateFormatter.dateFormat(fromTemplate: "j", options: 0, locale: .current) ?? ""
269
+ return !format.contains("a")
270
+ }
271
+
272
+ static func snapshot() -> String {
273
+ [
274
+ locales().map(\.languageTag).joined(separator: ","),
275
+ country(),
276
+ TimeZone.current.identifier,
277
+ String(uses24HourClock()),
278
+ calendar(),
279
+ String(describing: temperatureUnit()),
280
+ String(describing: measurementSystem()),
281
+ String(describing: firstDayOfWeek()),
282
+ String(describing: textDirection()),
283
+ (Foundation.Locale.current.decimalSeparator ?? "") + (Foundation.Locale.current.groupingSeparator ?? ""),
284
+ currencies().joined(separator: ","),
285
+ ].joined(separator: "|")
286
+ }
287
+ }
package/nitro.json ADDED
@@ -0,0 +1,13 @@
1
+ {
2
+ "$schema": "https://nitro.margelo.com/nitro.schema.json",
3
+ "environment": "bare",
4
+ "cxxNamespace": ["nitrouilocalize"],
5
+ "apple": {
6
+ "moduleName": "NitroLocalize"
7
+ },
8
+ "android": {
9
+ "namespace": ["nitrouilocalize"],
10
+ "cxxLibName": "NitroLocalize"
11
+ },
12
+ "ignorePaths": ["**/node_modules", "**/.build", "**/.swiftpm"]
13
+ }
package/package.json CHANGED
@@ -1,6 +1,67 @@
1
1
  {
2
2
  "name": "nitro-ui-localize",
3
- "version": "0.0.0-stage",
4
- "stub": true,
5
- "description": "Temporary package placeholder for staged publishing"
6
- }
3
+ "version": "0.2.0",
4
+ "description": "The user's languages, region, currencies, time zone, 12/24h, units and first weekday for NitroUI apps, with a change listener.",
5
+ "keywords": [
6
+ "nitro-ui",
7
+ "nitroui",
8
+ "nitro",
9
+ "nitro-modules",
10
+ "localize",
11
+ "localization",
12
+ "i18n",
13
+ "l10n",
14
+ "locale",
15
+ "ios",
16
+ "android"
17
+ ],
18
+ "license": "MIT",
19
+ "author": "Jaydeep Agravat",
20
+ "repository": {
21
+ "type": "git",
22
+ "url": "git+https://github.com/JaydeepAgravat/nitro-ui-localize.git",
23
+ "directory": "package"
24
+ },
25
+ "homepage": "https://github.com/JaydeepAgravat/nitro-ui-localize#readme",
26
+ "bugs": {
27
+ "url": "https://github.com/JaydeepAgravat/nitro-ui-localize/issues"
28
+ },
29
+ "type": "module",
30
+ "module": "src/index.ts",
31
+ "types": "src/index.ts",
32
+ "exports": {
33
+ ".": {
34
+ "types": "./src/index.ts",
35
+ "default": "./src/index.ts"
36
+ },
37
+ "./package.json": "./package.json"
38
+ },
39
+ "imports": {
40
+ "#nitro/*": "./nitrogen/generated/shared/javascript/*.cjs"
41
+ },
42
+ "files": [
43
+ "src",
44
+ "!src/**/*.test.ts",
45
+ "ios",
46
+ "android",
47
+ "nitro.json",
48
+ "Package.swift",
49
+ "README.md",
50
+ "LICENSE"
51
+ ],
52
+ "nitroUI": {
53
+ "android": {
54
+ "activityInitializer": "com.margelo.nitro.nitrouilocalize.LocalizeModule"
55
+ }
56
+ },
57
+ "peerDependencies": {
58
+ "nitro-core": ">=1.0.0-alpha.0 <2.0.0"
59
+ },
60
+ "scripts": {
61
+ "specs": "nitrogen . --out nitrogen/generated",
62
+ "typecheck": "tsc --noEmit"
63
+ },
64
+ "publishConfig": {
65
+ "access": "public"
66
+ }
67
+ }
@@ -0,0 +1,78 @@
1
+ import { Android, iOS, type HybridObject } from 'nitro-core'
2
+
3
+ export * from '#nitro/Localize'
4
+
5
+ /** One of the user's preferred languages, in the order the user set them. */
6
+ export interface Locale {
7
+ /** ISO 639 language code, such as `"en"`. */
8
+ languageCode: string
9
+ /** ISO 15924 script code, such as `"Hans"`, when the language tag has one. */
10
+ scriptCode?: string
11
+ /** ISO 3166 region code, such as `"US"`. Falls back to the device region. */
12
+ countryCode: string
13
+ /** BCP 47 tag, such as `"en-US"` or `"zh-Hans-CN"`. */
14
+ languageTag: string
15
+ /** Whether this language is written right to left. */
16
+ isRTL: boolean
17
+ }
18
+
19
+ export interface NumberFormatSettings {
20
+ decimalSeparator: string
21
+ groupingSeparator: string
22
+ }
23
+
24
+ export type TemperatureUnit = 'celsius' | 'fahrenheit'
25
+ export type MeasurementSystem = 'metric' | 'us' | 'uk'
26
+ export type Weekday = 'sunday' | 'monday' | 'tuesday' | 'wednesday' | 'thursday' | 'friday' | 'saturday'
27
+ export type TextDirection = 'ltr' | 'rtl'
28
+
29
+ export interface LocalizeSubscription {
30
+ remove: () => void
31
+ }
32
+
33
+ /**
34
+ * Reads the user's localization settings from the operating system.
35
+ *
36
+ * iOS reads Foundation's `Locale` and `TimeZone`. Android reads the
37
+ * configuration's `LocaleList`, ICU and the system settings.
38
+ */
39
+ @iOS({ language: 'swift', implementation: { className: 'HybridLocalize' } })
40
+ @Android({ language: 'kotlin', implementation: { className: 'HybridLocalize' } })
41
+ export declare class Localize extends HybridObject {
42
+ public constructor()
43
+
44
+ /** The user's preferred languages, most preferred first. Never empty. */
45
+ getLocales(): Locale[]
46
+ /** The device region as an ISO 3166 code, such as `"IN"`. */
47
+ getCountry(): string
48
+ /** ISO 4217 currency codes for the device region and the preferred languages, de-duplicated. */
49
+ getCurrencies(): string[]
50
+ /** The calendar identifier, such as `"gregorian"` or `"buddhist"`. */
51
+ getCalendar(): string
52
+ getNumberFormatSettings(): NumberFormatSettings
53
+ getTemperatureUnit(): TemperatureUnit
54
+ getMeasurementSystem(): MeasurementSystem
55
+ getFirstDayOfWeek(): Weekday
56
+ /** The IANA time zone, such as `"Asia/Kolkata"`. */
57
+ getTimeZone(): string
58
+ /** The direction the app's interface is laid out in. */
59
+ getTextDirection(): TextDirection
60
+ /** Whether the user's settings show times on a 24-hour clock. */
61
+ uses24HourClock(): boolean
62
+ /** Whether date and time are set automatically. Always undefined on iOS. */
63
+ usesAutoDateAndTime(): boolean | undefined
64
+ /** Whether the time zone is set automatically. Always undefined on iOS. */
65
+ usesAutoTimeZone(): boolean | undefined
66
+
67
+ /**
68
+ * Calls `listener` when any localization setting changes. Read the values again inside it.
69
+ * Remove the returned subscription when observation is no longer needed.
70
+ */
71
+ addOnChangeListener(listener: () => void): LocalizeSubscription
72
+ /** Opens the system page where the user picks this app's language. */
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>
78
+ }
@@ -0,0 +1,33 @@
1
+ // Matching order from react-native-localize by Mathieu Acthernoene (MIT):
2
+ // for each preferred locale in order, try the full tag, language-script,
3
+ // language-country, then the bare language.
4
+
5
+ export interface MatchableLocale {
6
+ languageCode: string
7
+ scriptCode?: string
8
+ countryCode: string
9
+ languageTag: string
10
+ isRTL: boolean
11
+ }
12
+
13
+ export function findBestLanguageTagIn<T extends string>(
14
+ languageTags: readonly T[],
15
+ locales: readonly MatchableLocale[],
16
+ ): { languageTag: T; isRTL: boolean } | undefined {
17
+ const lowered = languageTags.map((tag) => tag.toLowerCase())
18
+
19
+ for (const { languageTag, languageCode, scriptCode, countryCode, isRTL } of locales) {
20
+ const candidates = [
21
+ languageTag,
22
+ scriptCode ? `${languageCode}-${scriptCode}` : undefined,
23
+ `${languageCode}-${countryCode}`,
24
+ languageCode,
25
+ ]
26
+ for (const candidate of candidates) {
27
+ if (!candidate) continue
28
+ const index = lowered.indexOf(candidate.toLowerCase())
29
+ if (index !== -1) return { languageTag: languageTags[index]!, isRTL }
30
+ }
31
+ }
32
+ return undefined
33
+ }
package/src/index.ts ADDED
@@ -0,0 +1,151 @@
1
+ import { useMemo, useSyncExternalStore } from 'react'
2
+ import {
3
+ Localize as NativeLocalize,
4
+ type Locale,
5
+ type LocalizeSubscription,
6
+ type MeasurementSystem,
7
+ type NumberFormatSettings,
8
+ type TemperatureUnit,
9
+ type TextDirection,
10
+ type Weekday,
11
+ } from './Localize.nitro'
12
+ import { findBestLanguageTagIn } from './findBestLanguageTag'
13
+
14
+ export type { Locale, LocalizeSubscription, MeasurementSystem, NumberFormatSettings, TemperatureUnit, TextDirection, Weekday }
15
+
16
+ /** Same names as react-native-localize. */
17
+ export type Calendar =
18
+ | 'gregorian'
19
+ | 'buddhist'
20
+ | 'coptic'
21
+ | 'ethiopic'
22
+ | 'ethiopic-amete-alem'
23
+ | 'hebrew'
24
+ | 'indian'
25
+ | 'islamic'
26
+ | 'islamic-umm-al-qura'
27
+ | 'islamic-civil'
28
+ | 'islamic-tabular'
29
+ | 'iso8601'
30
+ | 'japanese'
31
+ | 'persian'
32
+
33
+ let native: NativeLocalize | undefined
34
+ function getNative(): NativeLocalize {
35
+ native ??= new NativeLocalize()
36
+ return native
37
+ }
38
+
39
+ export const getLocales = (): Locale[] => getNative().getLocales()
40
+ export const getCountry = (): string => getNative().getCountry()
41
+ export const getCurrencies = (): string[] => getNative().getCurrencies()
42
+ export const getCalendar = (): Calendar => getNative().getCalendar() as Calendar
43
+ export const getNumberFormatSettings = (): NumberFormatSettings => getNative().getNumberFormatSettings()
44
+ export const getTemperatureUnit = (): TemperatureUnit => getNative().getTemperatureUnit()
45
+ export const getMeasurementSystem = (): MeasurementSystem => getNative().getMeasurementSystem()
46
+ export const getFirstDayOfWeek = (): Weekday => getNative().getFirstDayOfWeek()
47
+ export const getTimeZone = (): string => getNative().getTimeZone()
48
+ export const getTextDirection = (): TextDirection => getNative().getTextDirection()
49
+ export const uses24HourClock = (): boolean => getNative().uses24HourClock()
50
+ export const usesMetricSystem = (): boolean => getMeasurementSystem() !== 'us'
51
+ export const usesAutoDateAndTime = (): boolean | undefined => getNative().usesAutoDateAndTime() ?? undefined
52
+ export const usesAutoTimeZone = (): boolean | undefined => getNative().usesAutoTimeZone() ?? undefined
53
+
54
+ /** Picks the first of `languageTags` that matches the user's preferred languages, in their order. */
55
+ export const findBestLanguageTag = <T extends string>(
56
+ languageTags: readonly T[],
57
+ ): { languageTag: T; isRTL: boolean } | undefined => findBestLanguageTagIn(languageTags, getLocales())
58
+
59
+ /** Opens the system page where the user picks this app's language. Rejects on Android 12 and earlier. */
60
+ export const openAppLanguageSettings = async (): Promise<void> => {
61
+ await getNative().openAppLanguageSettings()
62
+ }
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
+
79
+ // One native listener shared by every subscriber.
80
+ const subscribers = new Set<() => void>()
81
+ let nativeSubscription: LocalizeSubscription | undefined
82
+ let version = 0
83
+
84
+ /**
85
+ * Calls `listener` when any localization setting changes. Read the values again inside it.
86
+ * Call `remove()` on the result when observation is no longer needed.
87
+ */
88
+ export function addChangeListener(listener: () => void): LocalizeSubscription {
89
+ subscribers.add(listener)
90
+ nativeSubscription ??= getNative().addOnChangeListener(() => {
91
+ version++
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
102
+ })
103
+ let removed = false
104
+ return {
105
+ remove() {
106
+ if (removed) return
107
+ removed = true
108
+ subscribers.delete(listener)
109
+ if (subscribers.size === 0 && nativeSubscription) {
110
+ nativeSubscription.remove()
111
+ nativeSubscription = undefined
112
+ }
113
+ },
114
+ }
115
+ }
116
+
117
+ const api = {
118
+ getLocales,
119
+ getCountry,
120
+ getCurrencies,
121
+ getCalendar,
122
+ getNumberFormatSettings,
123
+ getTemperatureUnit,
124
+ getMeasurementSystem,
125
+ getFirstDayOfWeek,
126
+ getTimeZone,
127
+ getTextDirection,
128
+ uses24HourClock,
129
+ usesMetricSystem,
130
+ usesAutoDateAndTime,
131
+ usesAutoTimeZone,
132
+ findBestLanguageTag,
133
+ openAppLanguageSettings,
134
+ getAppLanguage,
135
+ setAppLanguage,
136
+ }
137
+
138
+ export type LocalizeApi = typeof api & { version: number }
139
+
140
+ const subscribe = (onChange: () => void) => {
141
+ const subscription = addChangeListener(onChange)
142
+ return () => subscription.remove()
143
+ }
144
+ const getVersion = () => version
145
+
146
+ /** The API, re-rendering the component whenever a localization setting changes. */
147
+ export function useLocalize(): LocalizeApi {
148
+ const current = useSyncExternalStore(subscribe, getVersion)
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])
151
+ }