@nativue/core 0.7.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.
@@ -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.getSharedPreferences("dev.nativue.storage", Context.MODE_PRIVATE)
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.getString(arguments[0] as String, null) },
396
- "storageSet" to { arguments -> storage.edit().putString(arguments[0] as String, arguments[1] as String).apply() },
397
- "storageRemove" to { arguments -> storage.edit().remove(arguments[0] as String).apply() },
398
- "storageKeys" to { _ -> storage.all.keys.toList() },
399
- "storageClear" to { _ -> storage.edit().clear().apply() },
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()
package/ios/Bridge.swift CHANGED
@@ -766,6 +766,7 @@ final class Bridge {
766
766
  guard let node = nodesById[id] else { return }
767
767
 
768
768
  (node.view as? UILabel)?.text = text
769
+ if node.textDecorationLine != "none" { node.updateTextDecoration() }
769
770
  node.markContentChanged()
770
771
  }
771
772
 
@@ -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
- /// are saved to a file in the background, coalesced, so a burst of writes costs one save. Used only on
5
- /// the JS queue; the save itself runs on its own queue with a snapshot.
6
- /// Limitation: Each save rewrites the whole file; switch to SQLite or an append log if data grows large.
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 fileURL: URL
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
- let directory = FileManager.default.urls(for: .applicationSupportDirectory, in: .userDomainMask)[0]
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
- guard let data = try? Data(contentsOf: fileURL) else { return [:] }
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
- return (try? JSONDecoder().decode([String: String].self, from: data)) ?? [:]
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 snapshot = values
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
- saveQueue.async { [fileURL] in
60
- guard let data = try? JSONEncoder().encode(snapshot) else { return }
98
+ private func write(_ changes: [String: String?], clearingFirst: Bool) {
99
+ execute("BEGIN")
100
+ if clearingFirst { execute("DELETE FROM storage") }
61
101
 
62
- try? data.write(to: fileURL, options: .atomic)
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
  }
@@ -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
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@nativue/core",
3
- "version": "0.7.0",
3
+ "version": "0.8.0",
4
4
  "description": "Vue rendering real native views on iOS and Android",
5
5
  "keywords": [
6
6
  "vue",
package/src/storage.ts CHANGED
@@ -1,6 +1,6 @@
1
- // AsyncStorage: promise-based, string values. Native keeps every
2
- // value in memory (reads never touch the disk) and saves to a file in the background, so
3
- // each call is a fast synchronous native call behind the promise.
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'