nitro-ui-localize 0.0.0-stage → 0.1.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 +21 -0
- package/Package.swift +126 -0
- package/README.md +143 -2
- package/android/src/main/java/com/margelo/nitro/nitrouilocalize/HybridLocalize.kt +296 -0
- package/ios/HybridLocalize.swift +243 -0
- package/nitro.json +13 -0
- package/package.json +65 -4
- package/src/Localize.nitro.ts +74 -0
- package/src/findBestLanguageTag.ts +33 -0
- package/src/index.ts +124 -0
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,144 @@
|
|
|
1
|
-
#
|
|
1
|
+
# nitro-ui-localize
|
|
2
2
|
|
|
3
|
-
|
|
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 15 and 17 emulators.
|
|
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
|
+
## API
|
|
47
|
+
|
|
48
|
+
All getters are synchronous.
|
|
49
|
+
|
|
50
|
+
| Function | Returns | Example |
|
|
51
|
+
|---|---|---|
|
|
52
|
+
| `getLocales()` | The user's preferred languages, most preferred first | `[{ languageTag: 'hi-IN', languageCode: 'hi', countryCode: 'IN', isRTL: false }, …]` |
|
|
53
|
+
| `getCountry()` | Device region | `'IN'` |
|
|
54
|
+
| `getCurrencies()` | Currencies of the region and preferred languages | `['INR', 'USD']` |
|
|
55
|
+
| `getCalendar()` | Calendar | `'gregorian'`, `'buddhist'` |
|
|
56
|
+
| `getNumberFormatSettings()` | Separators | `{ decimalSeparator: '.', groupingSeparator: ',' }` |
|
|
57
|
+
| `getTemperatureUnit()` | Follows the user's temperature preference | `'celsius'` |
|
|
58
|
+
| `getMeasurementSystem()` | | `'metric'`, `'us'`, `'uk'` |
|
|
59
|
+
| `usesMetricSystem()` | `getMeasurementSystem() !== 'us'` | `true` |
|
|
60
|
+
| `getFirstDayOfWeek()` | Follows the user's first-day preference | `'monday'` |
|
|
61
|
+
| `getTimeZone()` | IANA time zone | `'Asia/Kolkata'` |
|
|
62
|
+
| `getTextDirection()` | Direction the app's UI is laid out in | `'ltr'` |
|
|
63
|
+
| `uses24HourClock()` | Follows the user's 24-hour switch | `true` |
|
|
64
|
+
| `usesAutoDateAndTime()` | Android only, `undefined` on iOS | `true` |
|
|
65
|
+
| `usesAutoTimeZone()` | Android only, `undefined` on iOS | `true` |
|
|
66
|
+
| `findBestLanguageTag(tags)` | First of your tags that matches the user's languages, in the user's order | `{ languageTag: 'hi', isRTL: false }` |
|
|
67
|
+
| `openAppLanguageSettings()` | Opens the system page for this app's language | `Promise<void>` |
|
|
68
|
+
| `addChangeListener(fn)` | Calls `fn` when any setting above changes | `{ remove() }` |
|
|
69
|
+
| `useLocalize()` | The API, re-rendering on change | |
|
|
70
|
+
|
|
71
|
+
`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.
|
|
72
|
+
|
|
73
|
+
## Why not just `Intl`?
|
|
74
|
+
|
|
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:
|
|
76
|
+
|
|
77
|
+
| Need | `Intl` | nitro-ui-localize |
|
|
78
|
+
|---|---|---|
|
|
79
|
+
| 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` |
|
|
80
|
+
| Ordered list of preferred languages | ❌ no `navigator.languages`, one locale only | ✅ |
|
|
81
|
+
| User turned on 24-hour time | ❌ still `h12` / `8 PM` | ✅ `true` |
|
|
82
|
+
| Temperature unit, first weekday preferences | ❌ no `Intl.Locale`, no week info | ✅ |
|
|
83
|
+
| Text direction of the app | ❌ | ✅ |
|
|
84
|
+
| 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 |
|
|
86
|
+
|
|
87
|
+
`Intl.PluralRules`, `RelativeTimeFormat`, `ListFormat` and `DisplayNames` are also missing on both platforms, so i18next plurals need a polyfill such as `@formatjs/intl-pluralrules`.
|
|
88
|
+
|
|
89
|
+
## Platform support
|
|
90
|
+
|
|
91
|
+
| | iOS | Android |
|
|
92
|
+
|---|---|---|
|
|
93
|
+
| Getters | ✅ tested on iOS 26.5 | ✅ tested on API 35 and 37 |
|
|
94
|
+
| 24-hour, temperature, first weekday preferences | ✅ (Settings > Language & Region) | ✅ (24-hour switch; `-u-mu-`, `-u-fw-` regional preferences) |
|
|
95
|
+
| `usesAutoDateAndTime`, `usesAutoTimeZone` | `undefined` | ✅ |
|
|
96
|
+
| `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 |
|
|
98
|
+
|
|
99
|
+
Minimum iOS 16. Not yet tested: physical devices, iOS 16–18, Android 8–14 and 16.
|
|
100
|
+
|
|
101
|
+
## Per-app language
|
|
102
|
+
|
|
103
|
+
Both platforms only offer a per-app language when the app declares its languages:
|
|
104
|
+
|
|
105
|
+
- **iOS:** list them in `CFBundleLocalizations` in `Info.plist` (two or more).
|
|
106
|
+
- **Android 13+:** add `res/xml/locales_config.xml` and `android:localeConfig="@xml/locales_config"` on `<application>`.
|
|
107
|
+
|
|
108
|
+
## What this library does not do
|
|
109
|
+
|
|
110
|
+
| Not doing | Use instead |
|
|
111
|
+
|---|---|
|
|
112
|
+
| Translate strings, plurals | i18next, Lingui, FormatJS |
|
|
113
|
+
| Format dates, numbers, currencies | `Intl` |
|
|
114
|
+
| RTL layout (`start`/`end`, mirroring) | NitroUI core ([#879](https://github.com/margelo/nitro-ui/issues/879)) |
|
|
115
|
+
| Save the chosen language | `nitro-mmkv` |
|
|
116
|
+
| Change the app language from code | Not yet. `openAppLanguageSettings()` sends the user to the system page |
|
|
117
|
+
|
|
118
|
+
## Coming from react-native-localize
|
|
119
|
+
|
|
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.
|
|
121
|
+
|
|
122
|
+
## Development
|
|
123
|
+
|
|
124
|
+
```sh
|
|
125
|
+
bun install
|
|
126
|
+
bun run typecheck # generates the Nitro bindings, then runs tsc
|
|
127
|
+
bun run test # unit tests for findBestLanguageTag
|
|
128
|
+
|
|
129
|
+
cd example
|
|
130
|
+
bun install
|
|
131
|
+
bun run start # then press i or a
|
|
132
|
+
bun run test:ios # harness tests inside the app on a simulator
|
|
133
|
+
bun run test:android
|
|
134
|
+
```
|
|
135
|
+
|
|
136
|
+
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
|
+
|
|
138
|
+
## Credits
|
|
139
|
+
|
|
140
|
+
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).
|
|
141
|
+
|
|
142
|
+
## License
|
|
143
|
+
|
|
144
|
+
MIT
|
|
@@ -0,0 +1,296 @@
|
|
|
1
|
+
package com.margelo.nitro.nitrouilocalize
|
|
2
|
+
|
|
3
|
+
import android.content.BroadcastReceiver
|
|
4
|
+
import android.content.Context
|
|
5
|
+
import android.content.Intent
|
|
6
|
+
import android.content.IntentFilter
|
|
7
|
+
import android.net.Uri
|
|
8
|
+
import android.os.Build
|
|
9
|
+
import android.os.Handler
|
|
10
|
+
import android.os.LocaleList
|
|
11
|
+
import android.os.Looper
|
|
12
|
+
import android.provider.Settings
|
|
13
|
+
import android.text.TextUtils
|
|
14
|
+
import android.text.format.DateFormat
|
|
15
|
+
import android.util.LayoutDirection
|
|
16
|
+
import com.margelo.nitro.core.Callback
|
|
17
|
+
import com.margelo.nitro.core.Promise
|
|
18
|
+
import com.margelo.nitro.core.callAndForget
|
|
19
|
+
import com.margelo.nitroui.runtime.NitroActivity
|
|
20
|
+
import com.margelo.nitroui.runtime.NitroActivityInitializer
|
|
21
|
+
import java.lang.ref.WeakReference
|
|
22
|
+
import java.text.DecimalFormatSymbols
|
|
23
|
+
import java.util.Currency
|
|
24
|
+
import java.util.TimeZone
|
|
25
|
+
import java.util.UUID
|
|
26
|
+
import java.util.Locale as JavaLocale
|
|
27
|
+
|
|
28
|
+
/**
|
|
29
|
+
* Keeps the application context and the current Activity, and tells listeners when a
|
|
30
|
+
* localization setting changes.
|
|
31
|
+
*
|
|
32
|
+
* 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.
|
|
34
|
+
*/
|
|
35
|
+
object LocalizeModule : NitroActivityInitializer {
|
|
36
|
+
internal var context: Context? = null
|
|
37
|
+
internal var activity = WeakReference<NitroActivity>(null)
|
|
38
|
+
|
|
39
|
+
private val listeners = linkedMapOf<UUID, Callback<() -> Unit>>()
|
|
40
|
+
private val mainHandler = Handler(Looper.getMainLooper())
|
|
41
|
+
private var snapshot: String? = null
|
|
42
|
+
private var emitScheduled = false
|
|
43
|
+
private var receiverRegistered = false
|
|
44
|
+
|
|
45
|
+
override fun onCreate(activity: NitroActivity) {
|
|
46
|
+
context = activity.applicationContext
|
|
47
|
+
this.activity = WeakReference(activity)
|
|
48
|
+
registerReceiver(activity.applicationContext)
|
|
49
|
+
scheduleEmitIfChanged()
|
|
50
|
+
}
|
|
51
|
+
|
|
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
|
|
57
|
+
}
|
|
58
|
+
|
|
59
|
+
internal fun removeListener(id: UUID) {
|
|
60
|
+
listeners.remove(id)
|
|
61
|
+
}
|
|
62
|
+
|
|
63
|
+
private fun registerReceiver(context: Context) {
|
|
64
|
+
if (receiverRegistered) return
|
|
65
|
+
receiverRegistered = true
|
|
66
|
+
val filter = IntentFilter().apply {
|
|
67
|
+
addAction(Intent.ACTION_LOCALE_CHANGED)
|
|
68
|
+
addAction(Intent.ACTION_TIMEZONE_CHANGED)
|
|
69
|
+
addAction(Intent.ACTION_TIME_CHANGED)
|
|
70
|
+
addAction(Intent.ACTION_CONFIGURATION_CHANGED)
|
|
71
|
+
}
|
|
72
|
+
val receiver = object : BroadcastReceiver() {
|
|
73
|
+
override fun onReceive(context: Context, intent: Intent) {
|
|
74
|
+
if (intent.action == Intent.ACTION_TIMEZONE_CHANGED) TimeZone.setDefault(null)
|
|
75
|
+
scheduleEmitIfChanged()
|
|
76
|
+
}
|
|
77
|
+
}
|
|
78
|
+
// System broadcasts only; no other app may send these.
|
|
79
|
+
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.TIRAMISU) {
|
|
80
|
+
context.registerReceiver(receiver, filter, Context.RECEIVER_NOT_EXPORTED)
|
|
81
|
+
} else {
|
|
82
|
+
context.registerReceiver(receiver, filter)
|
|
83
|
+
}
|
|
84
|
+
}
|
|
85
|
+
|
|
86
|
+
// Several broadcasts can arrive for one change. Compare once per main-loop turn.
|
|
87
|
+
private fun scheduleEmitIfChanged() {
|
|
88
|
+
if (emitScheduled) return
|
|
89
|
+
emitScheduled = true
|
|
90
|
+
mainHandler.post {
|
|
91
|
+
emitScheduled = false
|
|
92
|
+
if (listeners.isEmpty()) {
|
|
93
|
+
snapshot = null
|
|
94
|
+
return@post
|
|
95
|
+
}
|
|
96
|
+
val next = currentSnapshot()
|
|
97
|
+
if (next == snapshot) return@post
|
|
98
|
+
snapshot = next
|
|
99
|
+
for (listener in listeners.values.toList()) listener.callAndForget()
|
|
100
|
+
}
|
|
101
|
+
}
|
|
102
|
+
|
|
103
|
+
private fun currentSnapshot(): String {
|
|
104
|
+
val values = LocalizeValues(context ?: return "")
|
|
105
|
+
return listOf(
|
|
106
|
+
values.locales().joinToString(",") { it.languageTag },
|
|
107
|
+
values.country(),
|
|
108
|
+
values.timeZone(),
|
|
109
|
+
values.uses24HourClock().toString(),
|
|
110
|
+
values.textDirection().name,
|
|
111
|
+
values.calendar(),
|
|
112
|
+
values.temperatureUnit().name,
|
|
113
|
+
values.measurementSystem().name,
|
|
114
|
+
values.firstDayOfWeek().name,
|
|
115
|
+
).joinToString("|")
|
|
116
|
+
}
|
|
117
|
+
}
|
|
118
|
+
|
|
119
|
+
class HybridLocalize : HybridLocalizeSpec() {
|
|
120
|
+
private val values: LocalizeValues
|
|
121
|
+
get() = LocalizeValues(
|
|
122
|
+
LocalizeModule.context ?: throw IllegalStateException("nitro-ui-localize is used before the Activity started.")
|
|
123
|
+
)
|
|
124
|
+
|
|
125
|
+
override fun getLocales() = values.locales().toTypedArray()
|
|
126
|
+
override fun getCountry() = values.country()
|
|
127
|
+
override fun getCurrencies() = values.currencies().toTypedArray()
|
|
128
|
+
override fun getCalendar() = values.calendar()
|
|
129
|
+
override fun getNumberFormatSettings() = values.numberFormatSettings()
|
|
130
|
+
override fun getTemperatureUnit() = values.temperatureUnit()
|
|
131
|
+
override fun getMeasurementSystem() = values.measurementSystem()
|
|
132
|
+
override fun getFirstDayOfWeek() = values.firstDayOfWeek()
|
|
133
|
+
override fun getTimeZone() = values.timeZone()
|
|
134
|
+
override fun getTextDirection() = values.textDirection()
|
|
135
|
+
override fun uses24HourClock() = values.uses24HourClock()
|
|
136
|
+
override fun usesAutoDateAndTime(): Boolean? = values.globalSetting(Settings.Global.AUTO_TIME)
|
|
137
|
+
override fun usesAutoTimeZone(): Boolean? = values.globalSetting(Settings.Global.AUTO_TIME_ZONE)
|
|
138
|
+
|
|
139
|
+
override fun addOnChangeListener(listener: Callback<() -> Unit>): LocalizeSubscription {
|
|
140
|
+
val id = LocalizeModule.addListener(listener)
|
|
141
|
+
return LocalizeSubscription(
|
|
142
|
+
Callback.native {
|
|
143
|
+
LocalizeModule.removeListener(id)
|
|
144
|
+
Unit
|
|
145
|
+
}
|
|
146
|
+
)
|
|
147
|
+
}
|
|
148
|
+
|
|
149
|
+
override fun openAppLanguageSettings(): Promise<Unit> {
|
|
150
|
+
if (Build.VERSION.SDK_INT < Build.VERSION_CODES.TIRAMISU) {
|
|
151
|
+
return Promise.rejected(UnsupportedOperationException("Per-app language settings need Android 13 or later."))
|
|
152
|
+
}
|
|
153
|
+
val context = LocalizeModule.activity.get() ?: LocalizeModule.context
|
|
154
|
+
?: return Promise.rejected(IllegalStateException("No Activity to open the settings from."))
|
|
155
|
+
val intent = Intent(Settings.ACTION_APP_LOCALE_SETTINGS, Uri.fromParts("package", context.packageName, null))
|
|
156
|
+
if (context !is NitroActivity) intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK)
|
|
157
|
+
return try {
|
|
158
|
+
context.startActivity(intent)
|
|
159
|
+
Promise.resolved(Unit)
|
|
160
|
+
} catch (error: Exception) {
|
|
161
|
+
Promise.rejected(error)
|
|
162
|
+
}
|
|
163
|
+
}
|
|
164
|
+
|
|
165
|
+
companion object : HybridLocalizeSpec.Companion {
|
|
166
|
+
override fun constructor() = HybridLocalize()
|
|
167
|
+
}
|
|
168
|
+
}
|
|
169
|
+
|
|
170
|
+
/** Reads every value fresh, so a change is visible on the next call. */
|
|
171
|
+
internal class LocalizeValues(private val context: Context) {
|
|
172
|
+
private val configLocales: LocaleList
|
|
173
|
+
get() = context.resources.configuration.locales
|
|
174
|
+
|
|
175
|
+
private val primary: JavaLocale
|
|
176
|
+
get() = configLocales[0] ?: JavaLocale.getDefault()
|
|
177
|
+
|
|
178
|
+
fun locales(): List<Locale> {
|
|
179
|
+
val fallbackCountry = country()
|
|
180
|
+
val seen = mutableSetOf<String>()
|
|
181
|
+
val result = mutableListOf<Locale>()
|
|
182
|
+
// The configuration's list follows the per-app language when one is set.
|
|
183
|
+
for (i in 0 until configLocales.size()) {
|
|
184
|
+
val locale = configLocales[i]
|
|
185
|
+
val language = languageCode(locale)
|
|
186
|
+
val script = locale.script.ifEmpty { null }
|
|
187
|
+
val country = locale.country.ifEmpty { fallbackCountry }
|
|
188
|
+
val tag = listOfNotNull(language, script, country).joinToString("-")
|
|
189
|
+
if (!seen.add(tag)) continue
|
|
190
|
+
val isRTL = TextUtils.getLayoutDirectionFromLocale(locale) == LayoutDirection.RTL
|
|
191
|
+
result.add(Locale(language, script, country, tag, isRTL))
|
|
192
|
+
}
|
|
193
|
+
if (result.isEmpty()) result.add(Locale("en", null, fallbackCountry, "en-$fallbackCountry", false))
|
|
194
|
+
return result
|
|
195
|
+
}
|
|
196
|
+
|
|
197
|
+
fun country(): String = primary.country.ifEmpty { "US" }
|
|
198
|
+
|
|
199
|
+
fun currencies(): List<String> {
|
|
200
|
+
val codes = linkedSetOf<String>()
|
|
201
|
+
for (i in 0 until configLocales.size()) {
|
|
202
|
+
try {
|
|
203
|
+
Currency.getInstance(configLocales[i])?.currencyCode?.let(codes::add)
|
|
204
|
+
} catch (_: IllegalArgumentException) {
|
|
205
|
+
// A locale without a region has no currency.
|
|
206
|
+
}
|
|
207
|
+
}
|
|
208
|
+
if (codes.isEmpty()) codes.add("USD")
|
|
209
|
+
return codes.toList()
|
|
210
|
+
}
|
|
211
|
+
|
|
212
|
+
fun calendar(): String {
|
|
213
|
+
val type = android.icu.util.Calendar.getInstance(android.icu.util.ULocale.forLocale(primary)).type
|
|
214
|
+
// Same names as react-native-localize's Calendar type.
|
|
215
|
+
return when (type) {
|
|
216
|
+
"buddhist", "coptic", "ethiopic", "ethiopic-amete-alem", "hebrew", "indian", "islamic",
|
|
217
|
+
"islamic-civil", "iso8601", "japanese", "persian" -> type
|
|
218
|
+
"islamic-umalqura" -> "islamic-umm-al-qura"
|
|
219
|
+
"islamic-tbla" -> "islamic-tabular"
|
|
220
|
+
else -> "gregorian"
|
|
221
|
+
}
|
|
222
|
+
}
|
|
223
|
+
|
|
224
|
+
fun numberFormatSettings(): NumberFormatSettings {
|
|
225
|
+
val symbols = DecimalFormatSymbols.getInstance(primary)
|
|
226
|
+
return NumberFormatSettings(symbols.decimalSeparator.toString(), symbols.groupingSeparator.toString())
|
|
227
|
+
}
|
|
228
|
+
|
|
229
|
+
fun temperatureUnit(): TemperatureUnit {
|
|
230
|
+
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.TIRAMISU) {
|
|
231
|
+
// Android 14 regional preferences add "-u-mu-" to the locale; ICU's "weather" usage reads it.
|
|
232
|
+
val unit = android.icu.number.NumberFormatter.withLocale(primary)
|
|
233
|
+
.usage("weather")
|
|
234
|
+
.unit(android.icu.util.MeasureUnit.CELSIUS)
|
|
235
|
+
.format(1)
|
|
236
|
+
.outputUnit
|
|
237
|
+
return if (unit == android.icu.util.MeasureUnit.FAHRENHEIT) TemperatureUnit.FAHRENHEIT else TemperatureUnit.CELSIUS
|
|
238
|
+
}
|
|
239
|
+
return if (country() in FAHRENHEIT_COUNTRIES) TemperatureUnit.FAHRENHEIT else TemperatureUnit.CELSIUS
|
|
240
|
+
}
|
|
241
|
+
|
|
242
|
+
fun measurementSystem(): MeasurementSystem {
|
|
243
|
+
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.P) {
|
|
244
|
+
return when (android.icu.util.LocaleData.getMeasurementSystem(android.icu.util.ULocale.forLocale(primary))) {
|
|
245
|
+
android.icu.util.LocaleData.MeasurementSystem.US -> MeasurementSystem.US
|
|
246
|
+
android.icu.util.LocaleData.MeasurementSystem.UK -> MeasurementSystem.UK
|
|
247
|
+
else -> MeasurementSystem.METRIC
|
|
248
|
+
}
|
|
249
|
+
}
|
|
250
|
+
return if (country() in US_SYSTEM_COUNTRIES) MeasurementSystem.US else MeasurementSystem.METRIC
|
|
251
|
+
}
|
|
252
|
+
|
|
253
|
+
fun firstDayOfWeek(): Weekday {
|
|
254
|
+
// ICU reads a "-u-fw-" regional preference from the locale when Android 14 adds one.
|
|
255
|
+
val day = android.icu.util.Calendar.getInstance(android.icu.util.ULocale.forLocale(primary)).firstDayOfWeek
|
|
256
|
+
return when (day) {
|
|
257
|
+
android.icu.util.Calendar.MONDAY -> Weekday.MONDAY
|
|
258
|
+
android.icu.util.Calendar.TUESDAY -> Weekday.TUESDAY
|
|
259
|
+
android.icu.util.Calendar.WEDNESDAY -> Weekday.WEDNESDAY
|
|
260
|
+
android.icu.util.Calendar.THURSDAY -> Weekday.THURSDAY
|
|
261
|
+
android.icu.util.Calendar.FRIDAY -> Weekday.FRIDAY
|
|
262
|
+
android.icu.util.Calendar.SATURDAY -> Weekday.SATURDAY
|
|
263
|
+
else -> Weekday.SUNDAY
|
|
264
|
+
}
|
|
265
|
+
}
|
|
266
|
+
|
|
267
|
+
fun timeZone(): String = TimeZone.getDefault().id
|
|
268
|
+
|
|
269
|
+
fun textDirection(): TextDirection {
|
|
270
|
+
val configuration = (LocalizeModule.activity.get() ?: context).resources.configuration
|
|
271
|
+
return if (configuration.layoutDirection == LayoutDirection.RTL) TextDirection.RTL else TextDirection.LTR
|
|
272
|
+
}
|
|
273
|
+
|
|
274
|
+
fun uses24HourClock(): Boolean = DateFormat.is24HourFormat(context)
|
|
275
|
+
|
|
276
|
+
fun globalSetting(name: String): Boolean? =
|
|
277
|
+
try {
|
|
278
|
+
Settings.Global.getInt(context.contentResolver, name) != 0
|
|
279
|
+
} catch (_: Settings.SettingNotFoundException) {
|
|
280
|
+
null
|
|
281
|
+
}
|
|
282
|
+
|
|
283
|
+
private fun languageCode(locale: JavaLocale): String =
|
|
284
|
+
when (val language = locale.language) {
|
|
285
|
+
"iw" -> "he"
|
|
286
|
+
"in" -> "id"
|
|
287
|
+
"ji" -> "yi"
|
|
288
|
+
"" -> "en"
|
|
289
|
+
else -> language
|
|
290
|
+
}
|
|
291
|
+
|
|
292
|
+
private companion object {
|
|
293
|
+
val FAHRENHEIT_COUNTRIES = setOf("BS", "BZ", "KY", "PR", "PW", "US")
|
|
294
|
+
val US_SYSTEM_COUNTRIES = setOf("LR", "MM", "US")
|
|
295
|
+
}
|
|
296
|
+
}
|
|
@@ -0,0 +1,243 @@
|
|
|
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
|
+
func getLocales() throws -> [Locale] { LocalizeValues.locales() }
|
|
9
|
+
func getCountry() throws -> String { LocalizeValues.country() }
|
|
10
|
+
func getCurrencies() throws -> [String] { LocalizeValues.currencies() }
|
|
11
|
+
func getCalendar() throws -> String { LocalizeValues.calendar() }
|
|
12
|
+
|
|
13
|
+
func getNumberFormatSettings() throws -> NumberFormatSettings {
|
|
14
|
+
let locale = Foundation.Locale.current
|
|
15
|
+
return NumberFormatSettings(
|
|
16
|
+
decimalSeparator: locale.decimalSeparator ?? ".",
|
|
17
|
+
groupingSeparator: locale.groupingSeparator ?? ","
|
|
18
|
+
)
|
|
19
|
+
}
|
|
20
|
+
|
|
21
|
+
func getTemperatureUnit() throws -> TemperatureUnit { LocalizeValues.temperatureUnit() }
|
|
22
|
+
func getMeasurementSystem() throws -> MeasurementSystem { LocalizeValues.measurementSystem() }
|
|
23
|
+
func getFirstDayOfWeek() throws -> Weekday { LocalizeValues.firstDayOfWeek() }
|
|
24
|
+
func getTimeZone() throws -> String { TimeZone.current.identifier }
|
|
25
|
+
func getTextDirection() throws -> TextDirection { LocalizeValues.textDirection() }
|
|
26
|
+
func uses24HourClock() throws -> Bool { LocalizeValues.uses24HourClock() }
|
|
27
|
+
|
|
28
|
+
// iOS has no public API for these settings.
|
|
29
|
+
func usesAutoDateAndTime() throws -> Bool? { nil }
|
|
30
|
+
func usesAutoTimeZone() throws -> Bool? { nil }
|
|
31
|
+
|
|
32
|
+
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)
|
|
38
|
+
})
|
|
39
|
+
}
|
|
40
|
+
|
|
41
|
+
func openAppLanguageSettings() throws -> any Promise<Void> {
|
|
42
|
+
// The app's Settings page shows a Language row once the app declares two or more localizations.
|
|
43
|
+
guard let url = URL(string: UIApplication.openSettingsURLString) else {
|
|
44
|
+
throw RuntimeError("The Settings URL is unavailable.")
|
|
45
|
+
}
|
|
46
|
+
let promise: any Promise<Void> = .pending()
|
|
47
|
+
UIApplication.shared.open(url) { opened in
|
|
48
|
+
if opened {
|
|
49
|
+
promise.resolve()
|
|
50
|
+
} else {
|
|
51
|
+
promise.reject(error: RuntimeError("Settings could not be opened."))
|
|
52
|
+
}
|
|
53
|
+
}
|
|
54
|
+
return promise
|
|
55
|
+
}
|
|
56
|
+
}
|
|
57
|
+
|
|
58
|
+
/// Tells listeners when a localization setting changes, at most once per run-loop turn.
|
|
59
|
+
///
|
|
60
|
+
/// Changing the device or app language terminates the app, so a relaunch reads fresh values.
|
|
61
|
+
final class LocalizeObserver {
|
|
62
|
+
static let shared = LocalizeObserver()
|
|
63
|
+
|
|
64
|
+
private var listeners: [UUID: () -> Void] = [:]
|
|
65
|
+
private var observers: [any NSObjectProtocol] = []
|
|
66
|
+
private var snapshot: String?
|
|
67
|
+
private var emitScheduled = false
|
|
68
|
+
|
|
69
|
+
func add(_ listener: @escaping () -> Void) -> UUID {
|
|
70
|
+
let id = UUID()
|
|
71
|
+
listeners[id] = listener
|
|
72
|
+
if observers.isEmpty { start() }
|
|
73
|
+
return id
|
|
74
|
+
}
|
|
75
|
+
|
|
76
|
+
func remove(_ id: UUID) {
|
|
77
|
+
listeners.removeValue(forKey: id)
|
|
78
|
+
if listeners.isEmpty { stop() }
|
|
79
|
+
}
|
|
80
|
+
|
|
81
|
+
private func start() {
|
|
82
|
+
snapshot = LocalizeValues.snapshot()
|
|
83
|
+
let center = NotificationCenter.default
|
|
84
|
+
let names: [Notification.Name] = [
|
|
85
|
+
NSLocale.currentLocaleDidChangeNotification,
|
|
86
|
+
.NSSystemTimeZoneDidChange,
|
|
87
|
+
// A safety net for anything that changed while the app was suspended.
|
|
88
|
+
UIApplication.willEnterForegroundNotification,
|
|
89
|
+
]
|
|
90
|
+
observers = names.map { name in
|
|
91
|
+
center.addObserver(forName: name, object: nil, queue: .main) { [weak self] notification in
|
|
92
|
+
if notification.name == .NSSystemTimeZoneDidChange { NSTimeZone.resetSystemTimeZone() }
|
|
93
|
+
self?.scheduleEmitIfChanged()
|
|
94
|
+
}
|
|
95
|
+
}
|
|
96
|
+
}
|
|
97
|
+
|
|
98
|
+
private func stop() {
|
|
99
|
+
for observer in observers { NotificationCenter.default.removeObserver(observer) }
|
|
100
|
+
observers = []
|
|
101
|
+
snapshot = nil
|
|
102
|
+
}
|
|
103
|
+
|
|
104
|
+
private func scheduleEmitIfChanged() {
|
|
105
|
+
if emitScheduled { return }
|
|
106
|
+
emitScheduled = true
|
|
107
|
+
DispatchQueue.main.async { [weak self] in
|
|
108
|
+
guard let self else { return }
|
|
109
|
+
self.emitScheduled = false
|
|
110
|
+
let next = LocalizeValues.snapshot()
|
|
111
|
+
if next == self.snapshot { return }
|
|
112
|
+
self.snapshot = next
|
|
113
|
+
for listener in Array(self.listeners.values) { listener() }
|
|
114
|
+
}
|
|
115
|
+
}
|
|
116
|
+
}
|
|
117
|
+
|
|
118
|
+
/// Reads every value fresh from `Locale.current`, so a change is visible on the next call.
|
|
119
|
+
enum LocalizeValues {
|
|
120
|
+
static func locales() -> [Locale] {
|
|
121
|
+
let fallbackCountry = country()
|
|
122
|
+
var seen = Set<String>()
|
|
123
|
+
var result: [Locale] = []
|
|
124
|
+
// Already adjusted for a per-app language.
|
|
125
|
+
for identifier in Foundation.Locale.preferredLanguages {
|
|
126
|
+
let language = Foundation.Locale.Language(identifier: identifier)
|
|
127
|
+
guard let languageCode = language.languageCode?.identifier else { continue }
|
|
128
|
+
// `language.script` fills in the implied script ("Latn" for "en-IN"). Only keep a script
|
|
129
|
+
// the tag spells out, such as "zh-Hant-HK", like react-native-localize.
|
|
130
|
+
let script = NSLocale(localeIdentifier: identifier).object(forKey: .scriptCode) as? String
|
|
131
|
+
var country = language.region?.identifier ?? fallbackCountry
|
|
132
|
+
if country == "419" { country = "UN" }
|
|
133
|
+
let tag = [languageCode, script, country].compactMap { $0 }.joined(separator: "-")
|
|
134
|
+
guard seen.insert(tag).inserted else { continue }
|
|
135
|
+
result.append(Locale(
|
|
136
|
+
languageCode: languageCode,
|
|
137
|
+
scriptCode: script,
|
|
138
|
+
countryCode: country,
|
|
139
|
+
languageTag: tag,
|
|
140
|
+
isRTL: language.characterDirection == .rightToLeft
|
|
141
|
+
))
|
|
142
|
+
}
|
|
143
|
+
if result.isEmpty {
|
|
144
|
+
result.append(Locale(languageCode: "en", scriptCode: nil, countryCode: fallbackCountry, languageTag: "en-\(fallbackCountry)", isRTL: false))
|
|
145
|
+
}
|
|
146
|
+
return result
|
|
147
|
+
}
|
|
148
|
+
|
|
149
|
+
static func country() -> String {
|
|
150
|
+
// The simulator can report no region.
|
|
151
|
+
Foundation.Locale.current.region?.identifier ?? "US"
|
|
152
|
+
}
|
|
153
|
+
|
|
154
|
+
static func currencies() -> [String] {
|
|
155
|
+
var codes: [String] = []
|
|
156
|
+
func add(_ code: String?) {
|
|
157
|
+
if let code, !codes.contains(code) { codes.append(code) }
|
|
158
|
+
}
|
|
159
|
+
add(Foundation.Locale.current.currency?.identifier)
|
|
160
|
+
for identifier in Foundation.Locale.preferredLanguages {
|
|
161
|
+
add(Foundation.Locale(identifier: identifier).currency?.identifier)
|
|
162
|
+
}
|
|
163
|
+
return codes.isEmpty ? ["USD"] : codes
|
|
164
|
+
}
|
|
165
|
+
|
|
166
|
+
/// Same names as react-native-localize's Calendar type.
|
|
167
|
+
static func calendar() -> String {
|
|
168
|
+
switch Foundation.Locale.current.calendar.identifier {
|
|
169
|
+
case .buddhist: return "buddhist"
|
|
170
|
+
case .coptic: return "coptic"
|
|
171
|
+
case .ethiopicAmeteMihret: return "ethiopic"
|
|
172
|
+
case .ethiopicAmeteAlem: return "ethiopic-amete-alem"
|
|
173
|
+
case .hebrew: return "hebrew"
|
|
174
|
+
case .indian: return "indian"
|
|
175
|
+
case .islamic: return "islamic"
|
|
176
|
+
case .islamicCivil: return "islamic-civil"
|
|
177
|
+
case .islamicTabular: return "islamic-tabular"
|
|
178
|
+
case .islamicUmmAlQura: return "islamic-umm-al-qura"
|
|
179
|
+
case .iso8601: return "iso8601"
|
|
180
|
+
case .japanese: return "japanese"
|
|
181
|
+
case .persian: return "persian"
|
|
182
|
+
default: return "gregorian"
|
|
183
|
+
}
|
|
184
|
+
}
|
|
185
|
+
|
|
186
|
+
static func temperatureUnit() -> TemperatureUnit {
|
|
187
|
+
// Settings > General > Language & Region > Temperature writes this global default.
|
|
188
|
+
// Neither Locale.current nor MeasurementFormatter applies it (tested on iOS 26.5).
|
|
189
|
+
switch UserDefaults.standard.string(forKey: "AppleTemperatureUnit") {
|
|
190
|
+
case "Celsius": return .celsius
|
|
191
|
+
case "Fahrenheit": return .fahrenheit
|
|
192
|
+
default: break
|
|
193
|
+
}
|
|
194
|
+
// Not set: the region's default.
|
|
195
|
+
let formatter = MeasurementFormatter()
|
|
196
|
+
formatter.locale = .current
|
|
197
|
+
let text = formatter.string(from: Measurement(value: 0, unit: UnitTemperature.celsius))
|
|
198
|
+
return text.contains("F") ? .fahrenheit : .celsius
|
|
199
|
+
}
|
|
200
|
+
|
|
201
|
+
static func measurementSystem() -> MeasurementSystem {
|
|
202
|
+
switch Foundation.Locale.current.measurementSystem {
|
|
203
|
+
case .us: return .us
|
|
204
|
+
case .uk: return .uk
|
|
205
|
+
default: return .metric
|
|
206
|
+
}
|
|
207
|
+
}
|
|
208
|
+
|
|
209
|
+
static func firstDayOfWeek() -> Weekday {
|
|
210
|
+
switch Foundation.Locale.current.firstDayOfWeek {
|
|
211
|
+
case .monday: return .monday
|
|
212
|
+
case .tuesday: return .tuesday
|
|
213
|
+
case .wednesday: return .wednesday
|
|
214
|
+
case .thursday: return .thursday
|
|
215
|
+
case .friday: return .friday
|
|
216
|
+
case .saturday: return .saturday
|
|
217
|
+
default: return .sunday
|
|
218
|
+
}
|
|
219
|
+
}
|
|
220
|
+
|
|
221
|
+
static func textDirection() -> TextDirection {
|
|
222
|
+
UIApplication.shared.userInterfaceLayoutDirection == .rightToLeft ? .rtl : .ltr
|
|
223
|
+
}
|
|
224
|
+
|
|
225
|
+
static func uses24HourClock() -> Bool {
|
|
226
|
+
// The "j" skeleton resolves to the user's preferred hour symbol, including the 24-Hour Time switch.
|
|
227
|
+
let format = DateFormatter.dateFormat(fromTemplate: "j", options: 0, locale: .current) ?? ""
|
|
228
|
+
return !format.contains("a")
|
|
229
|
+
}
|
|
230
|
+
|
|
231
|
+
static func snapshot() -> String {
|
|
232
|
+
[
|
|
233
|
+
locales().map(\.languageTag).joined(separator: ","),
|
|
234
|
+
country(),
|
|
235
|
+
TimeZone.current.identifier,
|
|
236
|
+
String(uses24HourClock()),
|
|
237
|
+
calendar(),
|
|
238
|
+
String(describing: temperatureUnit()),
|
|
239
|
+
String(describing: measurementSystem()),
|
|
240
|
+
String(describing: firstDayOfWeek()),
|
|
241
|
+
].joined(separator: "|")
|
|
242
|
+
}
|
|
243
|
+
}
|
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.
|
|
4
|
-
"
|
|
5
|
-
"
|
|
6
|
-
|
|
3
|
+
"version": "0.1.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,74 @@
|
|
|
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
|
+
}
|
|
@@ -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,124 @@
|
|
|
1
|
+
import { 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
|
+
// One native listener shared by every subscriber.
|
|
65
|
+
const subscribers = new Set<() => void>()
|
|
66
|
+
let nativeSubscription: LocalizeSubscription | undefined
|
|
67
|
+
let version = 0
|
|
68
|
+
|
|
69
|
+
/**
|
|
70
|
+
* Calls `listener` when any localization setting changes. Read the values again inside it.
|
|
71
|
+
* Call `remove()` on the result when observation is no longer needed.
|
|
72
|
+
*/
|
|
73
|
+
export function addChangeListener(listener: () => void): LocalizeSubscription {
|
|
74
|
+
subscribers.add(listener)
|
|
75
|
+
nativeSubscription ??= getNative().addOnChangeListener(() => {
|
|
76
|
+
version++
|
|
77
|
+
for (const subscriber of [...subscribers]) subscriber()
|
|
78
|
+
})
|
|
79
|
+
let removed = false
|
|
80
|
+
return {
|
|
81
|
+
remove() {
|
|
82
|
+
if (removed) return
|
|
83
|
+
removed = true
|
|
84
|
+
subscribers.delete(listener)
|
|
85
|
+
if (subscribers.size === 0 && nativeSubscription) {
|
|
86
|
+
nativeSubscription.remove()
|
|
87
|
+
nativeSubscription = undefined
|
|
88
|
+
}
|
|
89
|
+
},
|
|
90
|
+
}
|
|
91
|
+
}
|
|
92
|
+
|
|
93
|
+
const api = {
|
|
94
|
+
getLocales,
|
|
95
|
+
getCountry,
|
|
96
|
+
getCurrencies,
|
|
97
|
+
getCalendar,
|
|
98
|
+
getNumberFormatSettings,
|
|
99
|
+
getTemperatureUnit,
|
|
100
|
+
getMeasurementSystem,
|
|
101
|
+
getFirstDayOfWeek,
|
|
102
|
+
getTimeZone,
|
|
103
|
+
getTextDirection,
|
|
104
|
+
uses24HourClock,
|
|
105
|
+
usesMetricSystem,
|
|
106
|
+
usesAutoDateAndTime,
|
|
107
|
+
usesAutoTimeZone,
|
|
108
|
+
findBestLanguageTag,
|
|
109
|
+
openAppLanguageSettings,
|
|
110
|
+
}
|
|
111
|
+
|
|
112
|
+
export type LocalizeApi = typeof api & { version: number }
|
|
113
|
+
|
|
114
|
+
const subscribe = (onChange: () => void) => {
|
|
115
|
+
const subscription = addChangeListener(onChange)
|
|
116
|
+
return () => subscription.remove()
|
|
117
|
+
}
|
|
118
|
+
const getVersion = () => version
|
|
119
|
+
|
|
120
|
+
/** The API, re-rendering the component whenever a localization setting changes. */
|
|
121
|
+
export function useLocalize(): LocalizeApi {
|
|
122
|
+
const current = useSyncExternalStore(subscribe, getVersion)
|
|
123
|
+
return { ...api, version: current }
|
|
124
|
+
}
|