@nativue/core 0.6.0 → 0.8.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/android/src/main/java/dev/nativue/Bridge.kt +6 -7
- package/android/src/main/java/dev/nativue/KeyValueStorage.kt +119 -0
- package/android/src/main/java/dev/nativue/Style.kt +11 -0
- package/android/src/main/java/dev/nativue/Views.kt +6 -0
- package/cli/run.mjs +67 -18
- package/ios/Bridge.swift +1 -0
- package/ios/KeyValueStorage.swift +76 -13
- package/ios/NativeNode.swift +2 -0
- package/ios/Style.swift +24 -0
- package/package.json +1 -1
- package/src/storage.ts +3 -3
- package/src/types.ts +1 -0
|
@@ -2,7 +2,6 @@ package dev.nativue
|
|
|
2
2
|
|
|
3
3
|
import android.annotation.SuppressLint
|
|
4
4
|
import android.app.Activity
|
|
5
|
-
import android.content.Context
|
|
6
5
|
import android.content.pm.ApplicationInfo
|
|
7
6
|
import android.content.res.Configuration
|
|
8
7
|
import android.content.res.ColorStateList
|
|
@@ -55,7 +54,7 @@ class Bridge(private val activity: Activity, private val rootView: RootView) {
|
|
|
55
54
|
private val javaScriptHandler = startJavaScriptThread()
|
|
56
55
|
private val isDebuggable = activity.applicationInfo.flags and ApplicationInfo.FLAG_DEBUGGABLE != 0
|
|
57
56
|
private val density = activity.resources.displayMetrics.density
|
|
58
|
-
private val storage = activity
|
|
57
|
+
private val storage = KeyValueStorage(activity)
|
|
59
58
|
private val pluginRegistry = PluginRegistry(activity)
|
|
60
59
|
|
|
61
60
|
// Only touched on the JS thread.
|
|
@@ -392,11 +391,11 @@ class Bridge(private val activity: Activity, private val rootView: RootView) {
|
|
|
392
391
|
}
|
|
393
392
|
|
|
394
393
|
private fun storageFunctions(): Map<String, NativeFunction> = mapOf(
|
|
395
|
-
"storageGet" to { arguments -> storage.
|
|
396
|
-
"storageSet" to { arguments -> storage.
|
|
397
|
-
"storageRemove" to { arguments -> storage.
|
|
398
|
-
"storageKeys" to { _ -> storage.
|
|
399
|
-
"storageClear" to { _ -> storage.
|
|
394
|
+
"storageGet" to { arguments -> storage.value(arguments[0] as String) },
|
|
395
|
+
"storageSet" to { arguments -> storage.setValue(arguments[0] as String, arguments[1] as String) },
|
|
396
|
+
"storageRemove" to { arguments -> storage.removeValue(arguments[0] as String) },
|
|
397
|
+
"storageKeys" to { _ -> storage.keys },
|
|
398
|
+
"storageClear" to { _ -> storage.removeAll() },
|
|
400
399
|
)
|
|
401
400
|
|
|
402
401
|
private fun animatedFunctions(): Map<String, NativeFunction> = mapOf(
|
|
@@ -0,0 +1,119 @@
|
|
|
1
|
+
package dev.nativue
|
|
2
|
+
|
|
3
|
+
import android.content.ContentValues
|
|
4
|
+
import android.content.Context
|
|
5
|
+
import android.database.sqlite.SQLiteDatabase
|
|
6
|
+
import java.util.concurrent.Executors
|
|
7
|
+
import java.util.concurrent.TimeUnit
|
|
8
|
+
|
|
9
|
+
private const val SHARED_PREFERENCES_NAME = "dev.nativue.storage"
|
|
10
|
+
private const val SAVE_DELAY_MS = 50L
|
|
11
|
+
|
|
12
|
+
/**
|
|
13
|
+
* Behind AsyncStorage. Every value lives in memory, so reads never touch the disk; changes are saved to
|
|
14
|
+
* a SQLite table in the background, coalesced, so a burst of writes costs one transaction, and a save
|
|
15
|
+
* writes only the keys that changed. Read and changed on the JS thread; saved on its own thread.
|
|
16
|
+
* Limitation: Every value is kept in memory: meant for settings and small data, not large datasets.
|
|
17
|
+
*/
|
|
18
|
+
internal class KeyValueStorage(private val context: Context) {
|
|
19
|
+
private val saver = Executors.newSingleThreadScheduledExecutor()
|
|
20
|
+
private lateinit var database: SQLiteDatabase
|
|
21
|
+
private val values: MutableMap<String, String> by lazy { load() }
|
|
22
|
+
|
|
23
|
+
// Shared with the saver: guarded by `this`. A null value removes the key.
|
|
24
|
+
private val pendingChanges = mutableMapOf<String, String?>()
|
|
25
|
+
private var isClearPending = false
|
|
26
|
+
private var isSaveScheduled = false
|
|
27
|
+
|
|
28
|
+
fun value(key: String): String? = values[key]
|
|
29
|
+
|
|
30
|
+
val keys: List<String>
|
|
31
|
+
get() = values.keys.toList()
|
|
32
|
+
|
|
33
|
+
fun setValue(key: String, value: String) {
|
|
34
|
+
values[key] = value
|
|
35
|
+
recordChange { pendingChanges[key] = value }
|
|
36
|
+
}
|
|
37
|
+
|
|
38
|
+
fun removeValue(key: String) {
|
|
39
|
+
values.remove(key)
|
|
40
|
+
recordChange { pendingChanges[key] = null }
|
|
41
|
+
}
|
|
42
|
+
|
|
43
|
+
fun removeAll() {
|
|
44
|
+
values.clear()
|
|
45
|
+
recordChange {
|
|
46
|
+
pendingChanges.clear()
|
|
47
|
+
isClearPending = true
|
|
48
|
+
}
|
|
49
|
+
}
|
|
50
|
+
|
|
51
|
+
private fun load(): MutableMap<String, String> {
|
|
52
|
+
val file = context.getDatabasePath("nativue-async-storage.db").also { it.parentFile?.mkdirs() }
|
|
53
|
+
val flags = SQLiteDatabase.CREATE_IF_NECESSARY or SQLiteDatabase.NO_LOCALIZED_COLLATORS
|
|
54
|
+
database = SQLiteDatabase.openDatabase(file.path, null, flags)
|
|
55
|
+
database.enableWriteAheadLogging()
|
|
56
|
+
database.execSQL("CREATE TABLE IF NOT EXISTS storage (key TEXT PRIMARY KEY NOT NULL, value TEXT NOT NULL)")
|
|
57
|
+
importSharedPreferences()
|
|
58
|
+
|
|
59
|
+
val loaded = mutableMapOf<String, String>()
|
|
60
|
+
database.rawQuery("SELECT key, value FROM storage", null).use { cursor ->
|
|
61
|
+
while (cursor.moveToNext()) loaded[cursor.getString(0)] = cursor.getString(1)
|
|
62
|
+
}
|
|
63
|
+
|
|
64
|
+
return loaded
|
|
65
|
+
}
|
|
66
|
+
|
|
67
|
+
/** Before SQLite, values were saved to SharedPreferences: moved into the table once, then deleted. */
|
|
68
|
+
private fun importSharedPreferences() {
|
|
69
|
+
val saved = context.getSharedPreferences(SHARED_PREFERENCES_NAME, Context.MODE_PRIVATE).all
|
|
70
|
+
if (saved.isEmpty()) return
|
|
71
|
+
|
|
72
|
+
write(saved.mapValues { (_, value) -> value?.toString() }, clearingFirst = false)
|
|
73
|
+
context.deleteSharedPreferences(SHARED_PREFERENCES_NAME)
|
|
74
|
+
}
|
|
75
|
+
|
|
76
|
+
private fun recordChange(change: () -> Unit) = synchronized(this) {
|
|
77
|
+
change()
|
|
78
|
+
if (!isSaveScheduled) {
|
|
79
|
+
isSaveScheduled = true
|
|
80
|
+
saver.schedule(::save, SAVE_DELAY_MS, TimeUnit.MILLISECONDS)
|
|
81
|
+
}
|
|
82
|
+
}
|
|
83
|
+
|
|
84
|
+
private fun save() {
|
|
85
|
+
val (changes, clearingFirst) = synchronized(this) {
|
|
86
|
+
val snapshot = pendingChanges.toMap() to isClearPending
|
|
87
|
+
pendingChanges.clear()
|
|
88
|
+
isClearPending = false
|
|
89
|
+
isSaveScheduled = false
|
|
90
|
+
snapshot
|
|
91
|
+
}
|
|
92
|
+
|
|
93
|
+
write(changes, clearingFirst)
|
|
94
|
+
}
|
|
95
|
+
|
|
96
|
+
// A failed save leaves memory ahead of the disk: the next launch reads what was saved.
|
|
97
|
+
private fun write(changes: Map<String, String?>, clearingFirst: Boolean) {
|
|
98
|
+
database.beginTransaction()
|
|
99
|
+
try {
|
|
100
|
+
if (clearingFirst) database.delete("storage", null, null)
|
|
101
|
+
|
|
102
|
+
for ((key, value) in changes) {
|
|
103
|
+
if (value == null) {
|
|
104
|
+
database.delete("storage", "key = ?", arrayOf(key))
|
|
105
|
+
} else {
|
|
106
|
+
val row = ContentValues().apply {
|
|
107
|
+
put("key", key)
|
|
108
|
+
put("value", value)
|
|
109
|
+
}
|
|
110
|
+
database.insertWithOnConflict("storage", null, row, SQLiteDatabase.CONFLICT_REPLACE)
|
|
111
|
+
}
|
|
112
|
+
}
|
|
113
|
+
|
|
114
|
+
database.setTransactionSuccessful()
|
|
115
|
+
} finally {
|
|
116
|
+
database.endTransaction()
|
|
117
|
+
}
|
|
118
|
+
}
|
|
119
|
+
}
|
|
@@ -1,5 +1,6 @@
|
|
|
1
1
|
package dev.nativue
|
|
2
2
|
|
|
3
|
+
import android.graphics.Paint
|
|
3
4
|
import android.graphics.Typeface
|
|
4
5
|
import android.util.TypedValue
|
|
5
6
|
import android.view.Gravity
|
|
@@ -65,9 +66,19 @@ private fun NativeNode.applyVisualProperty(property: String, value: Any?) {
|
|
|
65
66
|
else -> androidColor(value)?.let { view?.setTextColor(it) }
|
|
66
67
|
}
|
|
67
68
|
"textAlign" -> textView?.gravity = textGravities[value] ?: Gravity.START
|
|
69
|
+
"textDecorationLine" -> textView?.let { it.paintFlags = decoratedPaintFlags(it.paintFlags, value as? String) }
|
|
68
70
|
}
|
|
69
71
|
}
|
|
70
72
|
|
|
73
|
+
/** 'underline', 'line-through' or both: paint flags, which outlast text changes. */
|
|
74
|
+
private fun decoratedPaintFlags(flags: Int, decorationLine: String?): Int {
|
|
75
|
+
val undecorated = flags and (Paint.UNDERLINE_TEXT_FLAG or Paint.STRIKE_THRU_TEXT_FLAG).inv()
|
|
76
|
+
val underline = if (decorationLine?.contains("underline") == true) Paint.UNDERLINE_TEXT_FLAG else 0
|
|
77
|
+
val lineThrough = if (decorationLine?.contains("line-through") == true) Paint.STRIKE_THRU_TEXT_FLAG else 0
|
|
78
|
+
|
|
79
|
+
return undecorated or underline or lineThrough
|
|
80
|
+
}
|
|
81
|
+
|
|
71
82
|
private fun NativeNode.updateBox(change: BoxDrawable.() -> Unit) {
|
|
72
83
|
box.change()
|
|
73
84
|
box.invalidateSelf()
|
|
@@ -367,6 +367,12 @@ class ScrollContainerView(context: Context) : ContainerView(context) {
|
|
|
367
367
|
refreshIndicator.layout(indicatorLeft, -size, indicatorLeft + size, 0)
|
|
368
368
|
}
|
|
369
369
|
|
|
370
|
+
// The visible area changes with the size too: FlatList renders more rows when it grows.
|
|
371
|
+
override fun onSizeChanged(width: Int, height: Int, oldWidth: Int, oldHeight: Int) {
|
|
372
|
+
super.onSizeChanged(width, height, oldWidth, oldHeight)
|
|
373
|
+
reportScrollThrottled()
|
|
374
|
+
}
|
|
375
|
+
|
|
370
376
|
// Within the throttle, the report waits for its end, so the last position always reaches JS.
|
|
371
377
|
private fun reportScrollThrottled() {
|
|
372
378
|
if (onScroll == null || hasPendingReport) return
|
package/cli/run.mjs
CHANGED
|
@@ -2,6 +2,7 @@
|
|
|
2
2
|
// or emulator when none is running, then installs and launches the app on it. `--device` picks one by
|
|
3
3
|
// name or id (a simulator, an emulator or a phone), or alone, the first phone connected.
|
|
4
4
|
import { execFileSync, spawn } from 'node:child_process'
|
|
5
|
+
import { X509Certificate } from 'node:crypto'
|
|
5
6
|
import { existsSync, readFileSync, rmSync } from 'node:fs'
|
|
6
7
|
import { homedir, tmpdir } from 'node:os'
|
|
7
8
|
import { join } from 'node:path'
|
|
@@ -22,20 +23,25 @@ const sleep = (milliseconds) => new Promise((resolve) => setTimeout(resolve, mil
|
|
|
22
23
|
|
|
23
24
|
// ---------- iOS ----------
|
|
24
25
|
|
|
26
|
+
const iOSVersion = (device) => Number(device.runtime.match(/iOS-(\d+)/)?.[1] ?? 0)
|
|
27
|
+
|
|
28
|
+
/** iOS simulators, the newest iOS first. */
|
|
25
29
|
function simulators() {
|
|
26
30
|
const { devices } = JSON.parse(run('xcrun', ['simctl', 'list', 'devices', 'available', '-j']))
|
|
27
31
|
|
|
28
|
-
return Object.entries(devices)
|
|
29
|
-
|
|
30
|
-
|
|
32
|
+
return Object.entries(devices)
|
|
33
|
+
.flatMap(([runtime, runtimeDevices]) =>
|
|
34
|
+
runtimeDevices.map((device) => ({ ...device, runtime })),
|
|
35
|
+
)
|
|
36
|
+
.filter(iOSVersion)
|
|
37
|
+
.sort((first, second) => iOSVersion(second) - iOSVersion(first))
|
|
31
38
|
}
|
|
32
39
|
|
|
33
|
-
|
|
40
|
+
const iPhoneSimulators = () => simulators().filter((device) => device.name.startsWith('iPhone'))
|
|
41
|
+
|
|
42
|
+
/** An iPhone on the newest iOS: one already booted if there is one. */
|
|
34
43
|
function defaultSimulator() {
|
|
35
|
-
const
|
|
36
|
-
const iPhones = simulators()
|
|
37
|
-
.filter((device) => device.name.startsWith('iPhone') && iOSVersion(device))
|
|
38
|
-
.sort((first, second) => iOSVersion(second) - iOSVersion(first))
|
|
44
|
+
const iPhones = iPhoneSimulators()
|
|
39
45
|
|
|
40
46
|
if (iPhones.length === 0)
|
|
41
47
|
throw new Error('No iPhone simulator found: add one in Xcode > Settings > Components.')
|
|
@@ -92,22 +98,65 @@ function pickIOSDevice(requested) {
|
|
|
92
98
|
...simulators().map((device) => ({ ...device, isSimulator: true })),
|
|
93
99
|
]
|
|
94
100
|
const device = candidates.find(({ name, udid }) => name === requested || udid === requested)
|
|
95
|
-
if (!device)
|
|
96
|
-
throw new Error(
|
|
97
|
-
noDeviceMessage(
|
|
98
|
-
requested,
|
|
99
|
-
candidates.map(({ name, udid }) => `${name} (${udid})`),
|
|
100
|
-
),
|
|
101
|
-
)
|
|
101
|
+
if (!device) throw new Error(noDeviceMessage(requested, suggestedIOSDevices(phones)))
|
|
102
102
|
|
|
103
103
|
return device
|
|
104
104
|
}
|
|
105
105
|
|
|
106
|
+
/** The phones, and the iPhone simulators on the newest iOS: the whole list runs long. */
|
|
107
|
+
function suggestedIOSDevices(phones) {
|
|
108
|
+
const iPhones = iPhoneSimulators()
|
|
109
|
+
const newestIPhones = iPhones.filter((device) => iOSVersion(device) === iOSVersion(iPhones[0]))
|
|
110
|
+
|
|
111
|
+
return [...phones, ...newestIPhones].map(({ name, udid }) => `${name} (${udid})`)
|
|
112
|
+
}
|
|
113
|
+
|
|
106
114
|
function noDeviceMessage(requested, available) {
|
|
107
115
|
return `No device named or with the id "${requested}". Available:\n ${available.join('\n ')}`
|
|
108
116
|
}
|
|
109
117
|
|
|
118
|
+
const IOS_PROJECT_FILE = 'ios/App.xcodeproj/project.pbxproj'
|
|
119
|
+
|
|
120
|
+
/** The teams of this Mac's valid "Apple Development" certificates (their OU). */
|
|
121
|
+
function developmentTeams() {
|
|
122
|
+
const certificates = run(
|
|
123
|
+
'security',
|
|
124
|
+
['find-certificate', '-a', '-c', 'Apple Development', '-p'],
|
|
125
|
+
{
|
|
126
|
+
stdio: ['ignore', 'pipe', 'ignore'],
|
|
127
|
+
},
|
|
128
|
+
).match(/-----BEGIN CERTIFICATE-----[\s\S]+?-----END CERTIFICATE-----/g)
|
|
129
|
+
|
|
130
|
+
const teams = (certificates ?? [])
|
|
131
|
+
.map((pem) => new X509Certificate(pem))
|
|
132
|
+
.filter((certificate) => new Date(certificate.validTo) > new Date())
|
|
133
|
+
.map((certificate) => certificate.subject.match(/^OU=(\w+)$/m)?.[1])
|
|
134
|
+
|
|
135
|
+
return [...new Set(teams.filter(Boolean))]
|
|
136
|
+
}
|
|
137
|
+
|
|
138
|
+
/**
|
|
139
|
+
* A phone only runs signed apps. Without a team in the project, the one of this Mac's development
|
|
140
|
+
* certificate, for this build only: the project stays as it is.
|
|
141
|
+
*/
|
|
142
|
+
function signingSettings() {
|
|
143
|
+
if (readFileSync(IOS_PROJECT_FILE, 'utf8').includes('DEVELOPMENT_TEAM')) return []
|
|
144
|
+
|
|
145
|
+
const teams = developmentTeams()
|
|
146
|
+
if (teams.length === 1) return [`DEVELOPMENT_TEAM=${teams[0]}`]
|
|
147
|
+
|
|
148
|
+
const reason =
|
|
149
|
+
teams.length === 0
|
|
150
|
+
? 'No Apple Development certificate on this Mac: sign in to your Apple account in Xcode > Settings > Accounts,'
|
|
151
|
+
: 'Your certificates belong to several teams:'
|
|
152
|
+
throw new Error(
|
|
153
|
+
`${reason} then pick your team in ios/App.xcodeproj, under Signing & Capabilities.`,
|
|
154
|
+
)
|
|
155
|
+
}
|
|
156
|
+
|
|
110
157
|
function buildIOSApp(destination, isSimulator) {
|
|
158
|
+
const signing = isSimulator ? [] : ['-allowProvisioningUpdates', ...signingSettings()]
|
|
159
|
+
|
|
111
160
|
step('Building the iOS app')
|
|
112
161
|
|
|
113
162
|
try {
|
|
@@ -124,8 +173,8 @@ function buildIOSApp(destination, isSimulator) {
|
|
|
124
173
|
`id=${destination}`,
|
|
125
174
|
'-derivedDataPath',
|
|
126
175
|
IOS_BUILD_DIRECTORY,
|
|
127
|
-
//
|
|
128
|
-
...
|
|
176
|
+
// Xcode creates the provisioning profile.
|
|
177
|
+
...signing,
|
|
129
178
|
'-quiet',
|
|
130
179
|
'build',
|
|
131
180
|
],
|
|
@@ -135,7 +184,7 @@ function buildIOSApp(destination, isSimulator) {
|
|
|
135
184
|
if (isSimulator) throw error
|
|
136
185
|
|
|
137
186
|
throw new Error(
|
|
138
|
-
'The build for the phone failed. If it
|
|
187
|
+
'The build for the phone failed. If it is about signing, open ios/App.xcodeproj in Xcode and check Signing & Capabilities.',
|
|
139
188
|
)
|
|
140
189
|
}
|
|
141
190
|
}
|
package/ios/Bridge.swift
CHANGED
|
@@ -1,22 +1,30 @@
|
|
|
1
1
|
import Foundation
|
|
2
|
+
import SQLite3
|
|
2
3
|
|
|
3
|
-
/// Behind AsyncStorage. Every value lives in memory, so reads never touch the disk; changes
|
|
4
|
-
///
|
|
5
|
-
/// the JS queue; the
|
|
6
|
-
///
|
|
4
|
+
/// Behind AsyncStorage. Every value lives in memory, so reads never touch the disk; changes are saved to
|
|
5
|
+
/// a SQLite table in the background, coalesced, so a burst of writes costs one transaction, and a save
|
|
6
|
+
/// writes only the keys that changed. Used only on the JS queue; the database, on the save queue once
|
|
7
|
+
/// loaded.
|
|
8
|
+
/// Limitation: Every value is kept in memory: meant for settings and small data, not large datasets.
|
|
7
9
|
final class KeyValueStorage {
|
|
10
|
+
/// SQLite copies bound text.
|
|
11
|
+
private static let transient = unsafeBitCast(-1, to: sqlite3_destructor_type.self)
|
|
12
|
+
|
|
8
13
|
private let javaScriptQueue: DispatchQueue
|
|
9
14
|
private let saveQueue = DispatchQueue(label: "dev.nativue.storage", qos: .utility)
|
|
10
|
-
private let
|
|
15
|
+
private let directory: URL
|
|
16
|
+
private var database: OpaquePointer?
|
|
11
17
|
private lazy var values: [String: String] = load()
|
|
18
|
+
/// Changed keys since the last save: a nil value removes the key.
|
|
19
|
+
private var pendingChanges: [String: String?] = [:]
|
|
20
|
+
private var isClearPending = false
|
|
12
21
|
private var isSaveScheduled = false
|
|
13
22
|
|
|
14
23
|
init(javaScriptQueue: DispatchQueue) {
|
|
15
24
|
self.javaScriptQueue = javaScriptQueue
|
|
16
25
|
|
|
17
|
-
|
|
26
|
+
directory = FileManager.default.urls(for: .applicationSupportDirectory, in: .userDomainMask)[0]
|
|
18
27
|
try? FileManager.default.createDirectory(at: directory, withIntermediateDirectories: true)
|
|
19
|
-
fileURL = directory.appending(path: "async-storage.json")
|
|
20
28
|
}
|
|
21
29
|
|
|
22
30
|
func value(forKey key: String) -> String? {
|
|
@@ -29,23 +37,48 @@ final class KeyValueStorage {
|
|
|
29
37
|
|
|
30
38
|
func setValue(_ value: String, forKey key: String) {
|
|
31
39
|
values[key] = value
|
|
40
|
+
pendingChanges[key] = .some(value)
|
|
32
41
|
scheduleSave()
|
|
33
42
|
}
|
|
34
43
|
|
|
35
44
|
func removeValue(forKey key: String) {
|
|
36
45
|
values[key] = nil
|
|
46
|
+
pendingChanges[key] = .some(nil)
|
|
37
47
|
scheduleSave()
|
|
38
48
|
}
|
|
39
49
|
|
|
40
50
|
func removeAll() {
|
|
41
51
|
values = [:]
|
|
52
|
+
pendingChanges = [:]
|
|
53
|
+
isClearPending = true
|
|
42
54
|
scheduleSave()
|
|
43
55
|
}
|
|
44
56
|
|
|
45
57
|
private func load() -> [String: String] {
|
|
46
|
-
|
|
58
|
+
let path = directory.appending(path: "async-storage.db").path
|
|
59
|
+
guard sqlite3_open(path, &database) == SQLITE_OK else { return [:] }
|
|
60
|
+
|
|
61
|
+
execute("PRAGMA journal_mode = WAL")
|
|
62
|
+
execute("CREATE TABLE IF NOT EXISTS storage (key TEXT PRIMARY KEY NOT NULL, value TEXT NOT NULL)")
|
|
63
|
+
importJSONFile()
|
|
47
64
|
|
|
48
|
-
|
|
65
|
+
var loaded: [String: String] = [:]
|
|
66
|
+
forEachRow("SELECT key, value FROM storage") { statement in
|
|
67
|
+
loaded[String(cString: sqlite3_column_text(statement, 0))] = String(cString: sqlite3_column_text(statement, 1))
|
|
68
|
+
}
|
|
69
|
+
|
|
70
|
+
return loaded
|
|
71
|
+
}
|
|
72
|
+
|
|
73
|
+
/// Before SQLite, values were saved to a JSON file: moved into the table once, then deleted.
|
|
74
|
+
private func importJSONFile() {
|
|
75
|
+
let fileURL = directory.appending(path: "async-storage.json")
|
|
76
|
+
guard let data = try? Data(contentsOf: fileURL),
|
|
77
|
+
let saved = try? JSONDecoder().decode([String: String].self, from: data)
|
|
78
|
+
else { return }
|
|
79
|
+
|
|
80
|
+
write(saved.mapValues { .some($0) }, clearingFirst: false)
|
|
81
|
+
try? FileManager.default.removeItem(at: fileURL)
|
|
49
82
|
}
|
|
50
83
|
|
|
51
84
|
private func scheduleSave() {
|
|
@@ -54,13 +87,43 @@ final class KeyValueStorage {
|
|
|
54
87
|
isSaveScheduled = true
|
|
55
88
|
javaScriptQueue.asyncAfter(deadline: .now() + .milliseconds(50)) { [self] in
|
|
56
89
|
isSaveScheduled = false
|
|
57
|
-
let
|
|
90
|
+
let (changes, clearingFirst) = (pendingChanges, isClearPending)
|
|
91
|
+
pendingChanges = [:]
|
|
92
|
+
isClearPending = false
|
|
93
|
+
|
|
94
|
+
saveQueue.async { [self] in write(changes, clearingFirst: clearingFirst) }
|
|
95
|
+
}
|
|
96
|
+
}
|
|
58
97
|
|
|
59
|
-
|
|
60
|
-
|
|
98
|
+
private func write(_ changes: [String: String?], clearingFirst: Bool) {
|
|
99
|
+
execute("BEGIN")
|
|
100
|
+
if clearingFirst { execute("DELETE FROM storage") }
|
|
61
101
|
|
|
62
|
-
|
|
102
|
+
for (key, value) in changes {
|
|
103
|
+
if let value {
|
|
104
|
+
execute("INSERT OR REPLACE INTO storage (key, value) VALUES (?, ?)", key, value)
|
|
105
|
+
} else {
|
|
106
|
+
execute("DELETE FROM storage WHERE key = ?", key)
|
|
63
107
|
}
|
|
64
108
|
}
|
|
109
|
+
|
|
110
|
+
execute("COMMIT")
|
|
111
|
+
}
|
|
112
|
+
|
|
113
|
+
// A failed save leaves memory ahead of the disk: the next launch reads what was saved.
|
|
114
|
+
private func execute(_ sql: String, _ parameters: String...) {
|
|
115
|
+
forEachRow(sql, parameters) { _ in }
|
|
116
|
+
}
|
|
117
|
+
|
|
118
|
+
private func forEachRow(_ sql: String, _ parameters: [String] = [], _ readRow: (OpaquePointer?) -> Void) {
|
|
119
|
+
var statement: OpaquePointer?
|
|
120
|
+
guard sqlite3_prepare_v2(database, sql, -1, &statement, nil) == SQLITE_OK else { return }
|
|
121
|
+
defer { sqlite3_finalize(statement) }
|
|
122
|
+
|
|
123
|
+
for (index, parameter) in parameters.enumerated() {
|
|
124
|
+
sqlite3_bind_text(statement, Int32(index + 1), parameter, -1, Self.transient)
|
|
125
|
+
}
|
|
126
|
+
|
|
127
|
+
while sqlite3_step(statement) == SQLITE_ROW { readRow(statement) }
|
|
65
128
|
}
|
|
66
129
|
}
|
package/ios/NativeNode.swift
CHANGED
|
@@ -24,6 +24,8 @@ final class NativeNode {
|
|
|
24
24
|
var defaultFontSize: CGFloat = UIFont.labelFontSize
|
|
25
25
|
var fontSize: CGFloat = UIFont.labelFontSize
|
|
26
26
|
var fontWeight: UIFont.Weight = .regular
|
|
27
|
+
/// textDecorationLine: 'none', 'underline', 'line-through' or both.
|
|
28
|
+
var textDecorationLine = "none"
|
|
27
29
|
|
|
28
30
|
/// Leaf nodes (Text, Button) measure their own content; containers are sized by their children.
|
|
29
31
|
init(view: UIView, measuresContent: Bool) {
|
package/ios/Style.swift
CHANGED
|
@@ -80,11 +80,35 @@ extension NativeNode {
|
|
|
80
80
|
(view as? UILabel)?.textAlignment = alignment
|
|
81
81
|
(view as? UITextField)?.textAlignment = alignment
|
|
82
82
|
|
|
83
|
+
case "textDecorationLine":
|
|
84
|
+
textDecorationLine = value as? String ?? "none"
|
|
85
|
+
updateTextDecoration()
|
|
86
|
+
|
|
83
87
|
default:
|
|
84
88
|
break
|
|
85
89
|
}
|
|
86
90
|
}
|
|
87
91
|
|
|
92
|
+
/// UILabel has no underline or strikethrough of its own: they're attributes of its text, which setting
|
|
93
|
+
/// `text` drops, so setText calls this again. Later font, color and alignment changes keep them.
|
|
94
|
+
func updateTextDecoration() {
|
|
95
|
+
guard let label = view as? UILabel, let text = label.text else { return }
|
|
96
|
+
|
|
97
|
+
let paragraphStyle = NSMutableParagraphStyle()
|
|
98
|
+
paragraphStyle.alignment = label.textAlignment
|
|
99
|
+
paragraphStyle.lineBreakMode = label.lineBreakMode
|
|
100
|
+
|
|
101
|
+
var attributes: [NSAttributedString.Key: Any] = [
|
|
102
|
+
.font: label.font as Any,
|
|
103
|
+
.foregroundColor: label.textColor as Any,
|
|
104
|
+
.paragraphStyle: paragraphStyle,
|
|
105
|
+
]
|
|
106
|
+
if textDecorationLine.contains("underline") { attributes[.underlineStyle] = NSUnderlineStyle.single.rawValue }
|
|
107
|
+
if textDecorationLine.contains("line-through") { attributes[.strikethroughStyle] = NSUnderlineStyle.single.rawValue }
|
|
108
|
+
|
|
109
|
+
label.attributedText = NSAttributedString(string: text, attributes: attributes)
|
|
110
|
+
}
|
|
111
|
+
|
|
88
112
|
/// Font size and weight can change independently, so the node remembers both.
|
|
89
113
|
private func applyFont(_ changes: [String: Any]) {
|
|
90
114
|
if let size = changes["fontSize"] {
|
package/package.json
CHANGED
package/src/storage.ts
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
|
-
// AsyncStorage: promise-based, string values. Native keeps every
|
|
2
|
-
//
|
|
3
|
-
//
|
|
1
|
+
// AsyncStorage: promise-based, string values. Native keeps every value in memory (reads never touch
|
|
2
|
+
// the disk) and saves the changed keys to SQLite in the background, so each call is a fast synchronous
|
|
3
|
+
// native call behind the promise.
|
|
4
4
|
const native = globalThis.__native
|
|
5
5
|
|
|
6
6
|
export const AsyncStorage = {
|
package/src/types.ts
CHANGED
|
@@ -62,6 +62,7 @@ export type Style = {
|
|
|
62
62
|
fontWeight?:
|
|
63
63
|
'normal' | 'bold' | '100' | '200' | '300' | '400' | '500' | '600' | '700' | '800' | '900'
|
|
64
64
|
textAlign?: 'auto' | 'left' | 'right' | 'center' | 'justify'
|
|
65
|
+
textDecorationLine?: 'none' | 'underline' | 'line-through' | 'underline line-through'
|
|
65
66
|
}
|
|
66
67
|
|
|
67
68
|
export type GestureState = 'began' | 'changed' | 'ended' | 'cancelled' | 'failed'
|