Abrarul8541 commited on
Commit
b1f530e
·
verified ·
1 Parent(s): 9d0beff

Phase 3: on-demand JSON localization

Browse files
app/src/main/java/io/github/abrarul/modularai/i18n/LocaleManager.kt ADDED
@@ -0,0 +1,39 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ package io.github.abrarul.modularai.i18n
2
+
3
+ import android.content.Context
4
+ import androidx.compose.runtime.getValue
5
+ import androidx.compose.runtime.mutableStateOf
6
+ import androidx.compose.runtime.setValue
7
+ import kotlinx.coroutines.Dispatchers
8
+ import kotlinx.coroutines.withContext
9
+ import org.json.JSONObject
10
+ import java.io.File
11
+ import java.net.URL
12
+
13
+ /**
14
+ * Zero bundled languages. A locale is a small JSON object {"key":"text"} fetched on demand
15
+ * from [baseUrl]/<code>.json, cached in filesDir/locales, and applied instantly via Compose state.
16
+ */
17
+ class LocaleManager(ctx: Context, private val baseUrl: String) {
18
+ private val dir = File(ctx.filesDir, "locales").apply { mkdirs() }
19
+ private var strings by mutableStateOf<Map<String, String>>(emptyMap())
20
+ var current by mutableStateOf("en")
21
+ private set
22
+
23
+ /** English fallback keys live in code; missing keys return the key's default. */
24
+ fun t(key: String, default: String): String = strings[key] ?: default
25
+
26
+ suspend fun apply(code: String, persist: Boolean = true) = withContext(Dispatchers.IO) {
27
+ val cached = File(dir, "$code.json")
28
+ val text = if (cached.exists()) cached.readText() else URL("$baseUrl/$code.json").readText()
29
+ val json = JSONObject(text)
30
+ val map = json.keys().asSequence().associateWith { json.getString(it) }
31
+ if (persist) cached.writeText(text)
32
+ strings = map
33
+ current = code
34
+ }
35
+
36
+ fun reset() { strings = emptyMap(); current = "en" }
37
+ fun purge(code: String) { File(dir, "$code.json").delete() }
38
+ fun purgeAll() { dir.listFiles()?.forEach { it.delete() } }
39
+ }