@nativue/core 0.7.0 → 0.9.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/cpp/bridge.cpp +68 -3
- package/android/src/main/java/dev/nativue/BlobStore.kt +2 -3
- package/android/src/main/java/dev/nativue/Bridge.kt +11 -8
- package/android/src/main/java/dev/nativue/KeyValueStorage.kt +119 -0
- package/android/src/main/java/dev/nativue/Networking.kt +4 -4
- package/android/src/main/java/dev/nativue/Style.kt +11 -0
- package/ios/BlobStore.swift +3 -3
- package/ios/Bridge.swift +6 -1
- package/ios/JavaScriptRuntime/JavaScriptRuntime.mm +57 -1
- package/ios/KeyValueStorage.swift +76 -13
- package/ios/NativeNode.swift +2 -0
- package/ios/Networking.swift +5 -5
- package/ios/Style.swift +24 -0
- package/package.json +1 -2
- package/src/blob.ts +18 -8
- package/src/storage.ts +3 -3
- package/src/types.ts +10 -8
- package/src/xhr.ts +8 -7
|
@@ -1,11 +1,13 @@
|
|
|
1
1
|
// JNI bridge between dev.nativue.JavaScriptRuntime (Kotlin) and Hermes, through JSI. Values cross as
|
|
2
|
-
// plain Java objects: null, Boolean, Double, String,
|
|
3
|
-
// List, Map or Object[]). Every call
|
|
2
|
+
// plain Java objects: null, Boolean, Double, String, ByteArray (from an ArrayBuffer or a typed array, back
|
|
3
|
+
// as a Uint8Array), ArrayList and HashMap (and back from any Number, List, Map or Object[]). Every call
|
|
4
|
+
// happens on the JS thread.
|
|
4
5
|
#include <hermes/hermes.h>
|
|
5
6
|
#include <jni.h>
|
|
6
7
|
#include <jsi/jsi.h>
|
|
7
8
|
|
|
8
9
|
#include <memory>
|
|
10
|
+
#include <optional>
|
|
9
11
|
#include <string>
|
|
10
12
|
#include <vector>
|
|
11
13
|
|
|
@@ -16,7 +18,7 @@ namespace {
|
|
|
16
18
|
JavaVM* javaVM;
|
|
17
19
|
|
|
18
20
|
struct JavaTypes {
|
|
19
|
-
jclass object, boolean, number, doubleClass, string, list, arrayList, map, hashMap, objectArray;
|
|
21
|
+
jclass object, boolean, number, doubleClass, string, byteArray, list, arrayList, map, hashMap, objectArray;
|
|
20
22
|
jmethodID booleanValueOf, booleanValue, doubleValueOf, numberDoubleValue;
|
|
21
23
|
jmethodID listSize, listGet, arrayListInit, arrayListAdd;
|
|
22
24
|
jmethodID mapKeys, mapGet, hashMapInit, hashMapPut, setToArray;
|
|
@@ -84,6 +86,53 @@ std::string toStdString(JNIEnv* env, jstring string) {
|
|
|
84
86
|
return text;
|
|
85
87
|
}
|
|
86
88
|
|
|
89
|
+
// ---------- Bytes ----------
|
|
90
|
+
|
|
91
|
+
struct Bytes {
|
|
92
|
+
const uint8_t* data;
|
|
93
|
+
size_t size;
|
|
94
|
+
};
|
|
95
|
+
|
|
96
|
+
// An ArrayBuffer, or what a typed array or DataView sees of one. Not copied: use before calling JS again.
|
|
97
|
+
std::optional<Bytes> bytesOf(jsi::Runtime& runtime, const jsi::Object& object) {
|
|
98
|
+
if (object.isArrayBuffer(runtime)) {
|
|
99
|
+
jsi::ArrayBuffer buffer = object.getArrayBuffer(runtime);
|
|
100
|
+
|
|
101
|
+
return Bytes{buffer.data(runtime), buffer.size(runtime)};
|
|
102
|
+
}
|
|
103
|
+
|
|
104
|
+
jsi::Value buffer = object.getProperty(runtime, "buffer");
|
|
105
|
+
if (!buffer.isObject() || !buffer.getObject(runtime).isArrayBuffer(runtime)) return std::nullopt;
|
|
106
|
+
|
|
107
|
+
jsi::ArrayBuffer arrayBuffer = buffer.getObject(runtime).getArrayBuffer(runtime);
|
|
108
|
+
auto offset = static_cast<size_t>(object.getProperty(runtime, "byteOffset").asNumber());
|
|
109
|
+
auto length = static_cast<size_t>(object.getProperty(runtime, "byteLength").asNumber());
|
|
110
|
+
|
|
111
|
+
return Bytes{arrayBuffer.data(runtime) + offset, length};
|
|
112
|
+
}
|
|
113
|
+
|
|
114
|
+
class OwnedBuffer : public jsi::MutableBuffer {
|
|
115
|
+
public:
|
|
116
|
+
explicit OwnedBuffer(std::vector<uint8_t> bytes) : bytes_(std::move(bytes)) {}
|
|
117
|
+
|
|
118
|
+
size_t size() const override {
|
|
119
|
+
return bytes_.size();
|
|
120
|
+
}
|
|
121
|
+
|
|
122
|
+
uint8_t* data() override {
|
|
123
|
+
return bytes_.data();
|
|
124
|
+
}
|
|
125
|
+
|
|
126
|
+
private:
|
|
127
|
+
std::vector<uint8_t> bytes_;
|
|
128
|
+
};
|
|
129
|
+
|
|
130
|
+
jsi::Value uint8Array(jsi::Runtime& runtime, std::vector<uint8_t> bytes) {
|
|
131
|
+
jsi::ArrayBuffer buffer(runtime, std::make_shared<OwnedBuffer>(std::move(bytes)));
|
|
132
|
+
|
|
133
|
+
return runtime.global().getPropertyAsFunction(runtime, "Uint8Array").callAsConstructor(runtime, buffer);
|
|
134
|
+
}
|
|
135
|
+
|
|
87
136
|
// ---------- Values ----------
|
|
88
137
|
|
|
89
138
|
jobject toJava(JNIEnv* env, jsi::Runtime& runtime, const jsi::Value& value);
|
|
@@ -118,6 +167,13 @@ jobject objectToJava(JNIEnv* env, jsi::Runtime& runtime, const jsi::Object& obje
|
|
|
118
167
|
return map;
|
|
119
168
|
}
|
|
120
169
|
|
|
170
|
+
jbyteArray bytesToJava(JNIEnv* env, const Bytes& bytes) {
|
|
171
|
+
jbyteArray array = env->NewByteArray(static_cast<jsize>(bytes.size));
|
|
172
|
+
env->SetByteArrayRegion(array, 0, static_cast<jsize>(bytes.size), reinterpret_cast<const jbyte*>(bytes.data));
|
|
173
|
+
|
|
174
|
+
return array;
|
|
175
|
+
}
|
|
176
|
+
|
|
121
177
|
// Functions and other non-data values become null.
|
|
122
178
|
jobject toJava(JNIEnv* env, jsi::Runtime& runtime, const jsi::Value& value) {
|
|
123
179
|
if (value.isBool()) return env->CallStaticObjectMethod(types.boolean, types.booleanValueOf, value.getBool());
|
|
@@ -128,6 +184,7 @@ jobject toJava(JNIEnv* env, jsi::Runtime& runtime, const jsi::Value& value) {
|
|
|
128
184
|
jsi::Object object = value.getObject(runtime);
|
|
129
185
|
if (object.isFunction(runtime)) return nullptr;
|
|
130
186
|
if (object.isArray(runtime)) return arrayToJava(env, runtime, object.getArray(runtime));
|
|
187
|
+
if (auto bytes = bytesOf(runtime, object)) return bytesToJava(env, *bytes);
|
|
131
188
|
|
|
132
189
|
return objectToJava(env, runtime, object);
|
|
133
190
|
}
|
|
@@ -189,6 +246,13 @@ jsi::Value toJavaScript(JNIEnv* env, jsi::Runtime& runtime, jobject value) {
|
|
|
189
246
|
if (env->IsInstanceOf(value, types.string)) {
|
|
190
247
|
return toJavaScriptString(env, runtime, static_cast<jstring>(value));
|
|
191
248
|
}
|
|
249
|
+
if (env->IsInstanceOf(value, types.byteArray)) {
|
|
250
|
+
auto array = static_cast<jbyteArray>(value);
|
|
251
|
+
std::vector<uint8_t> bytes(env->GetArrayLength(array));
|
|
252
|
+
env->GetByteArrayRegion(array, 0, static_cast<jsize>(bytes.size()), reinterpret_cast<jbyte*>(bytes.data()));
|
|
253
|
+
|
|
254
|
+
return uint8Array(runtime, std::move(bytes));
|
|
255
|
+
}
|
|
192
256
|
if (env->IsInstanceOf(value, types.list)) return listToJavaScript(env, runtime, value);
|
|
193
257
|
if (env->IsInstanceOf(value, types.map)) return mapToJavaScript(env, runtime, value);
|
|
194
258
|
if (env->IsInstanceOf(value, types.objectArray)) {
|
|
@@ -364,6 +428,7 @@ extern "C" JNIEXPORT jint JNI_OnLoad(JavaVM* vm, void*) {
|
|
|
364
428
|
types.number = globalClass(env, "java/lang/Number");
|
|
365
429
|
types.doubleClass = globalClass(env, "java/lang/Double");
|
|
366
430
|
types.string = globalClass(env, "java/lang/String");
|
|
431
|
+
types.byteArray = globalClass(env, "[B");
|
|
367
432
|
types.list = globalClass(env, "java/util/List");
|
|
368
433
|
types.arrayList = globalClass(env, "java/util/ArrayList");
|
|
369
434
|
types.map = globalClass(env, "java/util/Map");
|
|
@@ -1,6 +1,5 @@
|
|
|
1
1
|
package dev.nativue
|
|
2
2
|
|
|
3
|
-
import android.util.Base64
|
|
4
3
|
import java.io.ByteArrayOutputStream
|
|
5
4
|
import java.util.UUID
|
|
6
5
|
import java.util.concurrent.ConcurrentHashMap
|
|
@@ -52,13 +51,13 @@ class BlobStore private constructor() {
|
|
|
52
51
|
/** On reload: the Blobs' JS is gone. */
|
|
53
52
|
fun removeAll() = bytesById.clear()
|
|
54
53
|
|
|
55
|
-
/** Joins `{ string }`, `{
|
|
54
|
+
/** Joins `{ string }`, `{ bytes }` and `{ blob }` parts into a new blob; null if a part's blob was released. */
|
|
56
55
|
fun create(parts: List<*>): Pair<String, Int>? {
|
|
57
56
|
val joined = ByteArrayOutputStream()
|
|
58
57
|
|
|
59
58
|
for (part in parts.filterIsInstance<Map<*, *>>()) {
|
|
60
59
|
(part["string"] as? String)?.let { joined.write(it.toByteArray()) }
|
|
61
|
-
(part["
|
|
60
|
+
(part["bytes"] as? ByteArray)?.let { joined.write(it) }
|
|
62
61
|
(part["blob"] as? Map<*, *>)?.let { joined.write(bytes(it) ?: return null) }
|
|
63
62
|
}
|
|
64
63
|
|
|
@@ -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(
|
|
@@ -454,7 +453,11 @@ class Bridge(private val activity: Activity, private val rootView: RootView) {
|
|
|
454
453
|
"blobRead" to { arguments ->
|
|
455
454
|
val (blobId, offset, size) = Triple(arguments[0] as String, (arguments[1] as Number).toInt(), (arguments[2] as Number).toInt())
|
|
456
455
|
blobStore.bytes(blobId, offset, size)?.let { bytes ->
|
|
457
|
-
|
|
456
|
+
when (arguments[3]) {
|
|
457
|
+
"bytes" -> bytes
|
|
458
|
+
"base64" -> Base64.encodeToString(bytes, Base64.NO_WRAP)
|
|
459
|
+
else -> String(bytes, Charsets.UTF_8)
|
|
460
|
+
}
|
|
458
461
|
}
|
|
459
462
|
},
|
|
460
463
|
"blobRelease" to { arguments -> blobStore.remove(arguments[0] as String) },
|
|
@@ -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
|
+
}
|
|
@@ -29,7 +29,7 @@ class Networking(
|
|
|
29
29
|
private val onEvent: (owner: JavaScriptRuntime?, requestId: Int, eventName: String, payload: Map<String, Any?>) -> Unit,
|
|
30
30
|
) {
|
|
31
31
|
private class Request(val id: Int, val owner: JavaScriptRuntime?, query: Map<*, *>) {
|
|
32
|
-
/** 'text', '
|
|
32
|
+
/** 'text', 'bytes' or 'blob'. */
|
|
33
33
|
val responseType = query["responseType"] as? String ?: "text"
|
|
34
34
|
val incrementalUpdates = query["incrementalUpdates"] == true
|
|
35
35
|
val streamsText = incrementalUpdates && responseType == "text"
|
|
@@ -173,7 +173,7 @@ class Networking(
|
|
|
173
173
|
/** What to send, or null for none. */
|
|
174
174
|
private fun body(body: Map<*, *>): Body? {
|
|
175
175
|
(body["string"] as? String)?.let { return bytesBody(it.toByteArray()) }
|
|
176
|
-
(body["
|
|
176
|
+
(body["bytes"] as? ByteArray)?.let { return bytesBody(it) }
|
|
177
177
|
(body["blob"] as? Map<*, *>)?.let { return bytesBody(blobBytes(it)) }
|
|
178
178
|
(body["uri"] as? String)?.let { uri -> return Body(-1) { openUri(uri) } }
|
|
179
179
|
|
|
@@ -237,9 +237,9 @@ class Networking(
|
|
|
237
237
|
emit(request, "data", mapOf("data" to responseData(request, bytes.toByteArray(), contentType)))
|
|
238
238
|
}
|
|
239
239
|
|
|
240
|
-
/** Text,
|
|
240
|
+
/** Text, the bytes, or for 'blob' the bytes kept in the BlobStore, described as a NativeBlob. */
|
|
241
241
|
private fun responseData(request: Request, bytes: ByteArray, contentType: String?): Any = when (request.responseType) {
|
|
242
|
-
"
|
|
242
|
+
"bytes" -> bytes
|
|
243
243
|
"blob" -> {
|
|
244
244
|
val type = contentType?.substringBefore(";")?.trim().orEmpty()
|
|
245
245
|
mapOf("blobId" to blobStore.store(bytes), "offset" to 0, "size" to bytes.size, "type" to type)
|
|
@@ -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()
|
package/ios/BlobStore.swift
CHANGED
|
@@ -50,15 +50,15 @@ final class BlobStore {
|
|
|
50
50
|
lock.withLock { dataById = [:] }
|
|
51
51
|
}
|
|
52
52
|
|
|
53
|
-
/// Joins `{ string }`, `{
|
|
53
|
+
/// Joins `{ string }`, `{ bytes }` and `{ blob }` parts into a new blob.
|
|
54
54
|
func create(parts: [[String: Any]]) throws -> (blobId: String, size: Int) {
|
|
55
55
|
var joined = Data()
|
|
56
56
|
|
|
57
57
|
for part in parts {
|
|
58
58
|
if let text = part["string"] as? String {
|
|
59
59
|
joined.append(Data(text.utf8))
|
|
60
|
-
} else if let
|
|
61
|
-
joined.append(
|
|
60
|
+
} else if let bytes = part["bytes"] as? Data {
|
|
61
|
+
joined.append(bytes)
|
|
62
62
|
} else if let blob = part["blob"] as? [String: Any] {
|
|
63
63
|
guard let data = data(of: blob) else { throw NetworkingError("The blob has been released") }
|
|
64
64
|
joined.append(data)
|
package/ios/Bridge.swift
CHANGED
|
@@ -671,7 +671,11 @@ final class Bridge {
|
|
|
671
671
|
let blob = ["blobId": arguments[0], "offset": arguments[1], "size": arguments[2]]
|
|
672
672
|
guard let data = blobStore.data(of: blob) else { return nil }
|
|
673
673
|
|
|
674
|
-
|
|
674
|
+
switch string(arguments[3]) {
|
|
675
|
+
case "bytes": return data
|
|
676
|
+
case "base64": return data.base64EncodedString()
|
|
677
|
+
default: return String(decoding: data, as: UTF8.self)
|
|
678
|
+
}
|
|
675
679
|
}
|
|
676
680
|
|
|
677
681
|
// Not through self: the runtime may collect Blobs as it's destroyed, with the Bridge.
|
|
@@ -766,6 +770,7 @@ final class Bridge {
|
|
|
766
770
|
guard let node = nodesById[id] else { return }
|
|
767
771
|
|
|
768
772
|
(node.view as? UILabel)?.text = text
|
|
773
|
+
if node.textDecorationLine != "none" { node.updateTextDecoration() }
|
|
769
774
|
node.markContentChanged()
|
|
770
775
|
}
|
|
771
776
|
|
|
@@ -1,5 +1,6 @@
|
|
|
1
1
|
// The bridge between Bridge.swift and Hermes, through JSI: the iOS side of android/src/main/cpp/bridge.cpp.
|
|
2
|
-
// Values cross as Foundation objects. Every call happens on the
|
|
2
|
+
// Values cross as Foundation objects, bytes as NSData (back as a Uint8Array). Every call happens on the
|
|
3
|
+
// JS queue.
|
|
3
4
|
#import "NativueJavaScriptRuntime.h"
|
|
4
5
|
|
|
5
6
|
#include <hermes/hermes.h>
|
|
@@ -7,6 +8,7 @@
|
|
|
7
8
|
|
|
8
9
|
#include <functional>
|
|
9
10
|
#include <memory>
|
|
11
|
+
#include <optional>
|
|
10
12
|
#include <string>
|
|
11
13
|
#include <vector>
|
|
12
14
|
|
|
@@ -38,6 +40,53 @@ NSString *toObjectiveCString(const std::string &string) {
|
|
|
38
40
|
return [NSString stringWithUTF8String:string.c_str()] ?: @"";
|
|
39
41
|
}
|
|
40
42
|
|
|
43
|
+
// ---------- Bytes ----------
|
|
44
|
+
|
|
45
|
+
struct Bytes {
|
|
46
|
+
const uint8_t *data;
|
|
47
|
+
size_t size;
|
|
48
|
+
};
|
|
49
|
+
|
|
50
|
+
// An ArrayBuffer, or what a typed array or DataView sees of one. Not copied: use before calling JS again.
|
|
51
|
+
std::optional<Bytes> bytesOf(jsi::Runtime &runtime, const jsi::Object &object) {
|
|
52
|
+
if (object.isArrayBuffer(runtime)) {
|
|
53
|
+
jsi::ArrayBuffer buffer = object.getArrayBuffer(runtime);
|
|
54
|
+
|
|
55
|
+
return Bytes{buffer.data(runtime), buffer.size(runtime)};
|
|
56
|
+
}
|
|
57
|
+
|
|
58
|
+
jsi::Value buffer = object.getProperty(runtime, "buffer");
|
|
59
|
+
if (!buffer.isObject() || !buffer.getObject(runtime).isArrayBuffer(runtime)) return std::nullopt;
|
|
60
|
+
|
|
61
|
+
jsi::ArrayBuffer arrayBuffer = buffer.getObject(runtime).getArrayBuffer(runtime);
|
|
62
|
+
auto offset = static_cast<size_t>(object.getProperty(runtime, "byteOffset").asNumber());
|
|
63
|
+
auto length = static_cast<size_t>(object.getProperty(runtime, "byteLength").asNumber());
|
|
64
|
+
|
|
65
|
+
return Bytes{arrayBuffer.data(runtime) + offset, length};
|
|
66
|
+
}
|
|
67
|
+
|
|
68
|
+
class OwnedBuffer : public jsi::MutableBuffer {
|
|
69
|
+
public:
|
|
70
|
+
explicit OwnedBuffer(std::vector<uint8_t> bytes) : bytes_(std::move(bytes)) {}
|
|
71
|
+
|
|
72
|
+
size_t size() const override {
|
|
73
|
+
return bytes_.size();
|
|
74
|
+
}
|
|
75
|
+
|
|
76
|
+
uint8_t *data() override {
|
|
77
|
+
return bytes_.data();
|
|
78
|
+
}
|
|
79
|
+
|
|
80
|
+
private:
|
|
81
|
+
std::vector<uint8_t> bytes_;
|
|
82
|
+
};
|
|
83
|
+
|
|
84
|
+
jsi::Value uint8Array(jsi::Runtime &runtime, std::vector<uint8_t> bytes) {
|
|
85
|
+
jsi::ArrayBuffer buffer(runtime, std::make_shared<OwnedBuffer>(std::move(bytes)));
|
|
86
|
+
|
|
87
|
+
return runtime.global().getPropertyAsFunction(runtime, "Uint8Array").callAsConstructor(runtime, buffer);
|
|
88
|
+
}
|
|
89
|
+
|
|
41
90
|
// ---------- Values ----------
|
|
42
91
|
|
|
43
92
|
id toObjectiveC(jsi::Runtime &runtime, const jsi::Value &value);
|
|
@@ -79,6 +128,7 @@ id toObjectiveC(jsi::Runtime &runtime, const jsi::Value &value) {
|
|
|
79
128
|
jsi::Object object = value.getObject(runtime);
|
|
80
129
|
if (object.isFunction(runtime)) return NSNull.null;
|
|
81
130
|
if (object.isArray(runtime)) return arrayToObjectiveC(runtime, object.getArray(runtime));
|
|
131
|
+
if (auto bytes = bytesOf(runtime, object)) return [NSData dataWithBytes:bytes->data length:bytes->size];
|
|
82
132
|
|
|
83
133
|
return objectToObjectiveC(runtime, object);
|
|
84
134
|
}
|
|
@@ -114,6 +164,12 @@ jsi::Value toJavaScript(jsi::Runtime &runtime, id value) {
|
|
|
114
164
|
return jsi::Value([value doubleValue]);
|
|
115
165
|
}
|
|
116
166
|
if ([value isKindOfClass:NSString.class]) return toJavaScriptString(runtime, value);
|
|
167
|
+
if ([value isKindOfClass:NSData.class]) {
|
|
168
|
+
NSData *data = value;
|
|
169
|
+
auto bytes = static_cast<const uint8_t *>(data.bytes);
|
|
170
|
+
|
|
171
|
+
return uint8Array(runtime, std::vector<uint8_t>(bytes, bytes + data.length));
|
|
172
|
+
}
|
|
117
173
|
if ([value isKindOfClass:NSArray.class]) return arrayToJavaScript(runtime, value);
|
|
118
174
|
if ([value isKindOfClass:NSDictionary.class]) return dictionaryToJavaScript(runtime, value);
|
|
119
175
|
|
|
@@ -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/Networking.swift
CHANGED
|
@@ -15,7 +15,7 @@ final class Networking: NSObject, URLSessionDataDelegate {
|
|
|
15
15
|
private final class RequestState {
|
|
16
16
|
let id: Int
|
|
17
17
|
weak var owner: AnyObject?
|
|
18
|
-
/// 'text', '
|
|
18
|
+
/// 'text', 'bytes' or 'blob'.
|
|
19
19
|
let responseType: String
|
|
20
20
|
let incrementalUpdates: Bool
|
|
21
21
|
var mimeType: String?
|
|
@@ -168,11 +168,11 @@ final class Networking: NSObject, URLSessionDataDelegate {
|
|
|
168
168
|
emit(state, "complete", ["error": NSNull(), "timedOut": false])
|
|
169
169
|
}
|
|
170
170
|
|
|
171
|
-
/// Text,
|
|
171
|
+
/// Text, the bytes, or for 'blob' the bytes kept in the BlobStore, described as a NativeBlob.
|
|
172
172
|
private func responseData(of state: RequestState) -> Any {
|
|
173
173
|
switch state.responseType {
|
|
174
|
-
case "
|
|
175
|
-
return state.data
|
|
174
|
+
case "bytes":
|
|
175
|
+
return state.data
|
|
176
176
|
case "blob":
|
|
177
177
|
let blobId = blobStore.store(state.data)
|
|
178
178
|
return ["blobId": blobId, "offset": 0, "size": state.data.count, "type": state.mimeType ?? ""]
|
|
@@ -206,7 +206,7 @@ final class Networking: NSObject, URLSessionDataDelegate {
|
|
|
206
206
|
guard let body else { return .none }
|
|
207
207
|
|
|
208
208
|
if let text = body["string"] as? String { return .data(Data(text.utf8)) }
|
|
209
|
-
if let
|
|
209
|
+
if let bytes = body["bytes"] as? Data { return .data(bytes) }
|
|
210
210
|
if let blob = body["blob"] as? [String: Any] { return .data(try blobData(blob)) }
|
|
211
211
|
if let uri = body["uri"] as? String {
|
|
212
212
|
let url = try fileOrDataURL(uri)
|
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
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@nativue/core",
|
|
3
|
-
"version": "0.
|
|
3
|
+
"version": "0.9.0",
|
|
4
4
|
"description": "Vue rendering real native views on iOS and Android",
|
|
5
5
|
"keywords": [
|
|
6
6
|
"vue",
|
|
@@ -38,7 +38,6 @@
|
|
|
38
38
|
"dependencies": {
|
|
39
39
|
"@vitejs/plugin-vue": "^6.0.11",
|
|
40
40
|
"@vue/runtime-core": "^3.5.45",
|
|
41
|
-
"base64-js": "^1.5.1",
|
|
42
41
|
"hermes-compiler": "260318099.0.8",
|
|
43
42
|
"vite": "^8.3.8",
|
|
44
43
|
"vue": "^3.5.45",
|
package/src/blob.ts
CHANGED
|
@@ -1,7 +1,6 @@
|
|
|
1
1
|
// Blob, File and FileReader, like the browser's. The bytes stay native (see BlobStore), so a large
|
|
2
2
|
// download never crosses into JS unless it's read. They're freed when the garbage collector collects
|
|
3
3
|
// the last Blob that points to them: __blobCollector gives an object whose collection frees them.
|
|
4
|
-
import { fromByteArray, toByteArray } from 'base64-js'
|
|
5
4
|
import { EventTarget, ProgressEvent } from './events'
|
|
6
5
|
import { ReadableStream } from './streams'
|
|
7
6
|
import type { NativeBlob, NativeBlobPart } from './types'
|
|
@@ -62,7 +61,7 @@ export class Blob {
|
|
|
62
61
|
}
|
|
63
62
|
|
|
64
63
|
async arrayBuffer(): Promise<ArrayBuffer> {
|
|
65
|
-
return
|
|
64
|
+
return this.readBytes().buffer as ArrayBuffer
|
|
66
65
|
}
|
|
67
66
|
|
|
68
67
|
/** The bytes in chunks, each read from native when the stream is read. */
|
|
@@ -75,7 +74,7 @@ export class Blob {
|
|
|
75
74
|
|
|
76
75
|
const chunk = this.slice(offset, offset + STREAM_CHUNK_SIZE)
|
|
77
76
|
offset += chunk.size
|
|
78
|
-
controller.enqueue(
|
|
77
|
+
controller.enqueue(chunk.readBytes())
|
|
79
78
|
},
|
|
80
79
|
})
|
|
81
80
|
}
|
|
@@ -83,10 +82,15 @@ export class Blob {
|
|
|
83
82
|
/** Synchronous: the bytes are in native memory. */
|
|
84
83
|
read(encoding: 'text' | 'base64'): string {
|
|
85
84
|
const { blobId, offset, size } = this.data
|
|
86
|
-
const contents = native.blobRead(blobId, offset, size, encoding)
|
|
87
|
-
if (contents === null) throw new Error('The blob has been released')
|
|
88
85
|
|
|
89
|
-
return
|
|
86
|
+
return released(native.blobRead(blobId, offset, size, encoding))
|
|
87
|
+
}
|
|
88
|
+
|
|
89
|
+
/** A copy of the bytes, in a buffer of their own. */
|
|
90
|
+
readBytes(): Uint8Array {
|
|
91
|
+
const { blobId, offset, size } = this.data
|
|
92
|
+
|
|
93
|
+
return released(native.blobRead(blobId, offset, size, 'bytes'))
|
|
90
94
|
}
|
|
91
95
|
}
|
|
92
96
|
|
|
@@ -109,7 +113,13 @@ function nativeBlobPart(part: BlobPart): NativeBlobPart {
|
|
|
109
113
|
if (typeof part === 'string') return { string: part }
|
|
110
114
|
if (part instanceof Blob) return { blob: part.data }
|
|
111
115
|
|
|
112
|
-
return {
|
|
116
|
+
return { bytes: bytesOf(part) }
|
|
117
|
+
}
|
|
118
|
+
|
|
119
|
+
function released<Contents>(contents: Contents | null): Contents {
|
|
120
|
+
if (contents === null) throw new Error('The blob has been released')
|
|
121
|
+
|
|
122
|
+
return contents
|
|
113
123
|
}
|
|
114
124
|
|
|
115
125
|
export function bytesOf(buffer: ArrayBuffer | ArrayBufferView): Uint8Array {
|
|
@@ -159,7 +169,7 @@ export class FileReader extends EventTarget {
|
|
|
159
169
|
}
|
|
160
170
|
|
|
161
171
|
readAsArrayBuffer(blob: Blob): void {
|
|
162
|
-
this.startReading(blob, () =>
|
|
172
|
+
this.startReading(blob, () => blob.readBytes().buffer as ArrayBuffer)
|
|
163
173
|
}
|
|
164
174
|
|
|
165
175
|
abort(): void {
|
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'
|
|
@@ -145,8 +146,9 @@ export interface NativeModule {
|
|
|
145
146
|
|
|
146
147
|
/** Joins the parts into new native bytes; null if a part's blob has been released. */
|
|
147
148
|
blobCreate(parts: NativeBlobPart[]): { blobId: string; size: number } | null
|
|
148
|
-
/** UTF-8 text
|
|
149
|
+
/** UTF-8 text, base64 (for data URLs) or the bytes themselves; null once released. */
|
|
149
150
|
blobRead(blobId: string, offset: number, size: number, encoding: 'text' | 'base64'): string | null
|
|
151
|
+
blobRead(blobId: string, offset: number, size: number, encoding: 'bytes'): Uint8Array | null
|
|
150
152
|
blobRelease(blobId: string): void
|
|
151
153
|
}
|
|
152
154
|
|
|
@@ -158,15 +160,15 @@ export interface NativeBlob {
|
|
|
158
160
|
type: string
|
|
159
161
|
}
|
|
160
162
|
|
|
161
|
-
export type NativeBlobPart = { string: string } | {
|
|
163
|
+
export type NativeBlobPart = { string: string } | { bytes: Uint8Array } | { blob: NativeBlob }
|
|
162
164
|
|
|
163
165
|
export interface NativeRequest {
|
|
164
166
|
method: string
|
|
165
167
|
url: string
|
|
166
168
|
headers: Record<string, string>
|
|
167
169
|
body: NativeRequestBody
|
|
168
|
-
/** '
|
|
169
|
-
responseType: 'text' | '
|
|
170
|
+
/** 'bytes' for arraybuffer responses; 'blob' keeps the bytes native. */
|
|
171
|
+
responseType: 'text' | 'bytes' | 'blob'
|
|
170
172
|
/** Send the text as it arrives (incrementaldata) and download progress, not just the whole at the end. */
|
|
171
173
|
incrementalUpdates: boolean
|
|
172
174
|
/** In milliseconds; 0 for the platform's. */
|
|
@@ -174,11 +176,11 @@ export interface NativeRequest {
|
|
|
174
176
|
withCredentials: boolean
|
|
175
177
|
}
|
|
176
178
|
|
|
177
|
-
// Text, bytes
|
|
179
|
+
// Text, bytes, a file native reads by uri, or the parts of a multipart/form-data body.
|
|
178
180
|
export type NativeRequestBody =
|
|
179
181
|
| null
|
|
180
182
|
| { string: string }
|
|
181
|
-
| {
|
|
183
|
+
| { bytes: Uint8Array }
|
|
182
184
|
| { uri: string }
|
|
183
185
|
| { blob: NativeBlob }
|
|
184
186
|
| { formData: NativeFormDataPart[] }
|
|
@@ -192,8 +194,8 @@ export type NativeFormDataPart =
|
|
|
192
194
|
export interface NetworkEventPayloads {
|
|
193
195
|
uploadprogress: { loaded: number; total: number }
|
|
194
196
|
response: { status: number; headers: Record<string, string>; url: string }
|
|
195
|
-
/** The whole response, once: text,
|
|
196
|
-
data: { data: string | NativeBlob }
|
|
197
|
+
/** The whole response, once: text, the bytes for 'bytes', a NativeBlob for 'blob'. Not sent after incrementaldata. */
|
|
198
|
+
data: { data: string | Uint8Array | NativeBlob }
|
|
197
199
|
incrementaldata: { text: string; loaded: number; total: number }
|
|
198
200
|
progress: { loaded: number; total: number }
|
|
199
201
|
/** The end: `error` set when it failed. */
|
package/src/xhr.ts
CHANGED
|
@@ -1,6 +1,5 @@
|
|
|
1
1
|
// XMLHttpRequest and FormData, like the browser's: native runs the request, and its progress comes back as
|
|
2
2
|
// events through __networkEvent. fetch and libraries like axios build on it.
|
|
3
|
-
import { fromByteArray, toByteArray } from 'base64-js'
|
|
4
3
|
import { Blob, bytesOf, File } from './blob'
|
|
5
4
|
import { Event, EventTarget, ProgressEvent } from './events'
|
|
6
5
|
import { URLSearchParams } from './url'
|
|
@@ -109,7 +108,7 @@ function nativeBody(body: XMLHttpRequestBody): NativeRequestBody {
|
|
|
109
108
|
if (body instanceof URLSearchParams) return { string: body.toString() }
|
|
110
109
|
if (body instanceof Blob) return { blob: body.data }
|
|
111
110
|
if (body instanceof ArrayBuffer || ArrayBuffer.isView(body)) {
|
|
112
|
-
return {
|
|
111
|
+
return { bytes: bytesOf(body) }
|
|
113
112
|
}
|
|
114
113
|
if ('uri' in body) return { uri: body.uri }
|
|
115
114
|
|
|
@@ -166,8 +165,8 @@ export class XMLHttpRequest extends EventTarget {
|
|
|
166
165
|
private requestHeaders: Record<string, string> = {}
|
|
167
166
|
private responseHeaders: Record<string, string> = {}
|
|
168
167
|
private chosenResponseType: XMLHttpRequestResponseType = ''
|
|
169
|
-
/** Text, or base64 for 'arraybuffer'. */
|
|
170
168
|
private rawResponse = ''
|
|
169
|
+
private bytesResponse: Uint8Array | null = null
|
|
171
170
|
private blobResponse: Blob | null = null
|
|
172
171
|
// Held until the request ends, so a Blob being uploaded isn't collected (and released) meanwhile.
|
|
173
172
|
private sentBody: XMLHttpRequestBody = null
|
|
@@ -312,8 +311,9 @@ export class XMLHttpRequest extends EventTarget {
|
|
|
312
311
|
this.setReadyState(HEADERS_RECEIVED)
|
|
313
312
|
}
|
|
314
313
|
|
|
315
|
-
private receiveData(data: string | NativeBlob) {
|
|
314
|
+
private receiveData(data: string | Uint8Array | NativeBlob) {
|
|
316
315
|
if (typeof data === 'string') this.rawResponse = data
|
|
316
|
+
else if (data instanceof Uint8Array) this.bytesResponse = data
|
|
317
317
|
else this.blobResponse = Blob.fromNative(data)
|
|
318
318
|
this.parsedResponse = undefined
|
|
319
319
|
this.setReadyState(LOADING)
|
|
@@ -349,7 +349,7 @@ export class XMLHttpRequest extends EventTarget {
|
|
|
349
349
|
: this.failed
|
|
350
350
|
? 'error'
|
|
351
351
|
: 'load'
|
|
352
|
-
const length = this.blobResponse?.size ?? this.rawResponse.length
|
|
352
|
+
const length = this.blobResponse?.size ?? this.bytesResponse?.length ?? this.rawResponse.length
|
|
353
353
|
this.dispatchProgress(this, outcome, length, length)
|
|
354
354
|
this.dispatchProgress(this, 'loadend', length, length)
|
|
355
355
|
}
|
|
@@ -369,7 +369,7 @@ export class XMLHttpRequest extends EventTarget {
|
|
|
369
369
|
}
|
|
370
370
|
|
|
371
371
|
private nativeResponseType() {
|
|
372
|
-
if (this.chosenResponseType === 'arraybuffer') return '
|
|
372
|
+
if (this.chosenResponseType === 'arraybuffer') return 'bytes'
|
|
373
373
|
if (this.chosenResponseType === 'blob') return 'blob'
|
|
374
374
|
|
|
375
375
|
return 'text'
|
|
@@ -381,7 +381,7 @@ export class XMLHttpRequest extends EventTarget {
|
|
|
381
381
|
|
|
382
382
|
private parseResponse(): unknown {
|
|
383
383
|
if (this.chosenResponseType === 'blob') return this.blobResponse
|
|
384
|
-
if (this.chosenResponseType === 'arraybuffer') return
|
|
384
|
+
if (this.chosenResponseType === 'arraybuffer') return (this.bytesResponse ?? new Uint8Array()).buffer
|
|
385
385
|
|
|
386
386
|
try {
|
|
387
387
|
return JSON.parse(this.rawResponse)
|
|
@@ -396,6 +396,7 @@ export class XMLHttpRequest extends EventTarget {
|
|
|
396
396
|
this.responseURL = ''
|
|
397
397
|
this.responseHeaders = {}
|
|
398
398
|
this.rawResponse = ''
|
|
399
|
+
this.bytesResponse = null
|
|
399
400
|
this.blobResponse = null
|
|
400
401
|
this.parsedResponse = undefined
|
|
401
402
|
this.failed = false
|