@oxy.so/bloom 23.8.0 → 23.8.1

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.
Files changed (117) hide show
  1. package/android/src/main/java/so/oxy/bloom/AvatarLoops.kt +293 -0
  2. package/android/src/main/java/so/oxy/bloom/AvatarSurface.kt +351 -0
  3. package/android/src/main/java/so/oxy/bloom/BloomPackage.kt +1 -1
  4. package/docs/agent-avatar.mdx +77 -1
  5. package/docs/no-nativewind.mdx +3 -1
  6. package/docs/task-catalog.json +1 -1
  7. package/docs/task-catalog.mdx +1 -1
  8. package/docs/theme.mdx +21 -0
  9. package/lib/commonjs/agent-avatar/VectorCharacterAvatar.js +267 -111
  10. package/lib/commonjs/agent-avatar/VectorCharacterAvatar.js.map +1 -1
  11. package/lib/commonjs/agent-avatar/VectorNativeSurface.js +75 -0
  12. package/lib/commonjs/agent-avatar/VectorNativeSurface.js.map +1 -0
  13. package/lib/commonjs/agent-avatar/vector-loop.js +161 -0
  14. package/lib/commonjs/agent-avatar/vector-loop.js.map +1 -0
  15. package/lib/commonjs/agent-avatar/vector-visibility.js +4 -1
  16. package/lib/commonjs/agent-avatar/vector-visibility.js.map +1 -1
  17. package/lib/commonjs/blur/BlurIsland.js +112 -118
  18. package/lib/commonjs/blur/BlurIsland.js.map +1 -1
  19. package/lib/commonjs/button/Button.js +12 -22
  20. package/lib/commonjs/button/Button.js.map +1 -1
  21. package/lib/commonjs/button/GroupBase.js +35 -50
  22. package/lib/commonjs/button/GroupBase.js.map +1 -1
  23. package/lib/commonjs/floating/lens/lens-frame.js +286 -0
  24. package/lib/commonjs/floating/lens/lens-frame.js.map +1 -0
  25. package/lib/commonjs/floating/lens/lens-material.js +1 -1
  26. package/lib/commonjs/page-header/PageHeader.js +24 -15
  27. package/lib/commonjs/page-header/PageHeader.js.map +1 -1
  28. package/lib/commonjs/panel-routing/expo-router/StackScene.js +1 -0
  29. package/lib/commonjs/panel-routing/expo-router/StackScene.js.map +1 -1
  30. package/lib/commonjs/surface/Surface.js +64 -193
  31. package/lib/commonjs/surface/Surface.js.map +1 -1
  32. package/lib/commonjs/tab-bar/TabBarBase.js +18 -15
  33. package/lib/commonjs/tab-bar/TabBarBase.js.map +1 -1
  34. package/lib/module/agent-avatar/VectorCharacterAvatar.js +268 -112
  35. package/lib/module/agent-avatar/VectorCharacterAvatar.js.map +1 -1
  36. package/lib/module/agent-avatar/VectorNativeSurface.js +66 -0
  37. package/lib/module/agent-avatar/VectorNativeSurface.js.map +1 -0
  38. package/lib/module/agent-avatar/vector-loop.js +150 -0
  39. package/lib/module/agent-avatar/vector-loop.js.map +1 -0
  40. package/lib/module/agent-avatar/vector-visibility.js +3 -1
  41. package/lib/module/agent-avatar/vector-visibility.js.map +1 -1
  42. package/lib/module/blur/BlurIsland.js +112 -116
  43. package/lib/module/blur/BlurIsland.js.map +1 -1
  44. package/lib/module/button/Button.js +13 -23
  45. package/lib/module/button/Button.js.map +1 -1
  46. package/lib/module/button/GroupBase.js +37 -52
  47. package/lib/module/button/GroupBase.js.map +1 -1
  48. package/lib/module/floating/lens/lens-frame.js +282 -0
  49. package/lib/module/floating/lens/lens-frame.js.map +1 -0
  50. package/lib/module/floating/lens/lens-material.js +1 -1
  51. package/lib/module/page-header/PageHeader.js +24 -15
  52. package/lib/module/page-header/PageHeader.js.map +1 -1
  53. package/lib/module/panel-routing/expo-router/StackScene.js +1 -0
  54. package/lib/module/panel-routing/expo-router/StackScene.js.map +1 -1
  55. package/lib/module/surface/Surface.js +65 -194
  56. package/lib/module/surface/Surface.js.map +1 -1
  57. package/lib/module/tab-bar/TabBarBase.js +18 -15
  58. package/lib/module/tab-bar/TabBarBase.js.map +1 -1
  59. package/lib/typescript/commonjs/agent-avatar/VectorCharacterAvatar.d.ts.map +1 -1
  60. package/lib/typescript/commonjs/agent-avatar/VectorNativeSurface.d.ts +75 -0
  61. package/lib/typescript/commonjs/agent-avatar/VectorNativeSurface.d.ts.map +1 -0
  62. package/lib/typescript/commonjs/agent-avatar/vector-loop.d.ts +93 -0
  63. package/lib/typescript/commonjs/agent-avatar/vector-loop.d.ts.map +1 -0
  64. package/lib/typescript/commonjs/agent-avatar/vector-visibility.d.ts +2 -0
  65. package/lib/typescript/commonjs/agent-avatar/vector-visibility.d.ts.map +1 -1
  66. package/lib/typescript/commonjs/blur/BlurIsland.d.ts +1 -1
  67. package/lib/typescript/commonjs/blur/BlurIsland.d.ts.map +1 -1
  68. package/lib/typescript/commonjs/button/Button.d.ts.map +1 -1
  69. package/lib/typescript/commonjs/button/GroupBase.d.ts.map +1 -1
  70. package/lib/typescript/commonjs/floating/lens/lens-frame.d.ts +52 -0
  71. package/lib/typescript/commonjs/floating/lens/lens-frame.d.ts.map +1 -0
  72. package/lib/typescript/commonjs/floating/lens/lens-material.d.ts +1 -1
  73. package/lib/typescript/commonjs/page-header/PageHeader.d.ts.map +1 -1
  74. package/lib/typescript/commonjs/panel-routing/expo-router/StackScene.d.ts.map +1 -1
  75. package/lib/typescript/commonjs/surface/Surface.d.ts.map +1 -1
  76. package/lib/typescript/commonjs/tab-bar/TabBarBase.d.ts.map +1 -1
  77. package/lib/typescript/module/agent-avatar/VectorCharacterAvatar.d.ts.map +1 -1
  78. package/lib/typescript/module/agent-avatar/VectorNativeSurface.d.ts +75 -0
  79. package/lib/typescript/module/agent-avatar/VectorNativeSurface.d.ts.map +1 -0
  80. package/lib/typescript/module/agent-avatar/vector-loop.d.ts +93 -0
  81. package/lib/typescript/module/agent-avatar/vector-loop.d.ts.map +1 -0
  82. package/lib/typescript/module/agent-avatar/vector-visibility.d.ts +2 -0
  83. package/lib/typescript/module/agent-avatar/vector-visibility.d.ts.map +1 -1
  84. package/lib/typescript/module/blur/BlurIsland.d.ts +1 -1
  85. package/lib/typescript/module/blur/BlurIsland.d.ts.map +1 -1
  86. package/lib/typescript/module/button/Button.d.ts.map +1 -1
  87. package/lib/typescript/module/button/GroupBase.d.ts.map +1 -1
  88. package/lib/typescript/module/floating/lens/lens-frame.d.ts +52 -0
  89. package/lib/typescript/module/floating/lens/lens-frame.d.ts.map +1 -0
  90. package/lib/typescript/module/floating/lens/lens-material.d.ts +1 -1
  91. package/lib/typescript/module/page-header/PageHeader.d.ts.map +1 -1
  92. package/lib/typescript/module/panel-routing/expo-router/StackScene.d.ts.map +1 -1
  93. package/lib/typescript/module/surface/Surface.d.ts.map +1 -1
  94. package/lib/typescript/module/tab-bar/TabBarBase.d.ts.map +1 -1
  95. package/package.json +1 -1
  96. package/src/agent-avatar/VectorCharacterAvatar.tsx +327 -120
  97. package/src/agent-avatar/VectorNativeSurface.tsx +117 -0
  98. package/src/agent-avatar/vector-loop.ts +213 -0
  99. package/src/agent-avatar/vector-visibility.ts +3 -1
  100. package/src/blur/BlurIsland.tsx +16 -14
  101. package/src/button/Button.tsx +19 -36
  102. package/src/button/GroupBase.tsx +42 -56
  103. package/src/floating/lens/lens-frame.tsx +195 -0
  104. package/src/floating/lens/lens-material.ts +1 -1
  105. package/src/page-header/PageHeader.tsx +26 -13
  106. package/src/panel-routing/expo-router/StackScene.tsx +9 -0
  107. package/src/surface/Surface.tsx +13 -28
  108. package/src/tab-bar/TabBarBase.tsx +13 -8
  109. package/lib/commonjs/floating/lens/lens-button-host.js +0 -218
  110. package/lib/commonjs/floating/lens/lens-button-host.js.map +0 -1
  111. package/lib/module/floating/lens/lens-button-host.js +0 -214
  112. package/lib/module/floating/lens/lens-button-host.js.map +0 -1
  113. package/lib/typescript/commonjs/floating/lens/lens-button-host.d.ts +0 -34
  114. package/lib/typescript/commonjs/floating/lens/lens-button-host.d.ts.map +0 -1
  115. package/lib/typescript/module/floating/lens/lens-button-host.d.ts +0 -34
  116. package/lib/typescript/module/floating/lens/lens-button-host.d.ts.map +0 -1
  117. package/src/floating/lens/lens-button-host.tsx +0 -148
@@ -0,0 +1,293 @@
1
+ package so.oxy.bloom
2
+
3
+ import android.content.Context
4
+ import android.graphics.Path
5
+ import android.os.Handler
6
+ import android.os.Looper
7
+ import java.io.BufferedInputStream
8
+ import java.io.BufferedOutputStream
9
+ import java.io.DataInputStream
10
+ import java.io.DataOutputStream
11
+ import java.io.File
12
+ import java.util.concurrent.Executors
13
+
14
+ /**
15
+ * One outline of an avatar frame, as the renderer writes it: absolute `M`, `L`, `H`, `V` and `Z`
16
+ * commands (`vector-contour.ts`, `vector-visibility.ts`). `H` and `V` are kept as lines.
17
+ */
18
+ class AvatarPathData(val verbs: ByteArray, val points: FloatArray) {
19
+ fun toPath(): Path {
20
+ val path = Path()
21
+ path.fillType = Path.FillType.WINDING
22
+ var p = 0
23
+ for (verb in verbs) {
24
+ when (verb) {
25
+ MOVE -> { path.moveTo(points[p], points[p + 1]); p += 2 }
26
+ LINE -> { path.lineTo(points[p], points[p + 1]); p += 2 }
27
+ else -> path.close()
28
+ }
29
+ }
30
+ return path
31
+ }
32
+
33
+ companion object {
34
+ const val MOVE: Byte = 0
35
+ const val LINE: Byte = 1
36
+ const val CLOSE: Byte = 2
37
+
38
+ /** Parses SVG path data with absolute M/L/H/V/Z commands; anything else is an error. */
39
+ fun parse(d: String): AvatarPathData {
40
+ val verbs = ByteArray(d.length / 2 + 1)
41
+ val points = FloatArray(d.length + 2)
42
+ var verbCount = 0
43
+ var pointCount = 0
44
+ var x = 0f
45
+ var y = 0f
46
+ var startX = 0f
47
+ var startY = 0f
48
+ var i = 0
49
+ val n = d.length
50
+ fun number(): Float {
51
+ while (i < n && (d[i] == ' ' || d[i] == ',')) i++
52
+ val start = i
53
+ if (i < n && (d[i] == '-' || d[i] == '+')) i++
54
+ while (i < n && (d[i].isDigit() || d[i] == '.' || d[i] == 'e' || d[i] == 'E' ||
55
+ ((d[i] == '-' || d[i] == '+') && (d[i - 1] == 'e' || d[i - 1] == 'E')))) i++
56
+ require(i > start) { "Avatar path: number expected at $start" }
57
+ return d.substring(start, i).toFloat()
58
+ }
59
+ fun add(verb: Byte, px: Float, py: Float) {
60
+ verbs[verbCount++] = verb
61
+ points[pointCount++] = px
62
+ points[pointCount++] = py
63
+ x = px
64
+ y = py
65
+ }
66
+ while (i < n) {
67
+ val command = d[i]
68
+ if (command == ' ' || command == ',') { i++; continue }
69
+ i++
70
+ when (command) {
71
+ 'M' -> { add(MOVE, number(), number()); startX = x; startY = y }
72
+ 'L' -> add(LINE, number(), number())
73
+ 'H' -> add(LINE, number(), y)
74
+ 'V' -> add(LINE, x, number())
75
+ 'Z', 'z' -> { verbs[verbCount++] = CLOSE; x = startX; y = startY }
76
+ else -> throw IllegalArgumentException("Avatar path: unsupported command $command")
77
+ }
78
+ // Repeated coordinate pairs after M or L continue as lines, as in SVG.
79
+ while (command == 'M' || command == 'L') {
80
+ var j = i
81
+ while (j < n && d[j] == ' ') j++
82
+ if (j >= n || !(d[j].isDigit() || d[j] == '-' || d[j] == '.')) break
83
+ add(LINE, number(), number())
84
+ }
85
+ }
86
+ return AvatarPathData(verbs.copyOf(verbCount), points.copyOf(pointCount))
87
+ }
88
+ }
89
+ }
90
+
91
+ /** The paint and outlines one path of a loop has on every frame. */
92
+ class AvatarTrack(
93
+ val fill: Int,
94
+ val fillOpacity: Float,
95
+ val stroke: Int?,
96
+ val strokeWidth: Float,
97
+ val opacity: FloatArray,
98
+ val d: Array<Path>,
99
+ val clip: Array<Path>?,
100
+ )
101
+
102
+ /** A character's rest loop: `length` frames evenly over `duration` seconds. */
103
+ class AvatarLoop(val duration: Double, val length: Int, val viewBox: FloatArray, val tracks: List<AvatarTrack>, val bytes: Int) {
104
+ /** The frame a loop clock reads at `seconds` (`vectorLoopIndex` in vector-loop.ts). */
105
+ fun index(seconds: Double): Int {
106
+ if (duration <= 0) return 0
107
+ val elapsed = ((seconds % duration) + duration) % duration
108
+ return minOf(length - 1, kotlin.math.floor(elapsed / duration * length).toInt()).coerceAtLeast(0)
109
+ }
110
+ }
111
+
112
+ /** A loop as JS hands it over, still as numbers: what is parsed once, written to disk and read back. */
113
+ class AvatarLoopData(
114
+ val duration: Double,
115
+ val length: Int,
116
+ val viewBox: FloatArray,
117
+ val tracks: List<Track>,
118
+ ) {
119
+ class Track(
120
+ val fill: Int,
121
+ val fillOpacity: Float,
122
+ val stroke: Int?,
123
+ val strokeWidth: Float,
124
+ val opacity: FloatArray,
125
+ val d: List<AvatarPathData>,
126
+ val clip: List<AvatarPathData>?,
127
+ )
128
+
129
+ fun toLoop(): AvatarLoop {
130
+ var bytes = 0
131
+ val built = tracks.map { track ->
132
+ fun paths(list: List<AvatarPathData>) = Array(list.size) { list[it].also { data -> bytes += data.points.size * 4 + data.verbs.size }.toPath() }
133
+ AvatarTrack(track.fill, track.fillOpacity, track.stroke, track.strokeWidth, track.opacity, paths(track.d), track.clip?.let(::paths))
134
+ }
135
+ return AvatarLoop(duration, length, viewBox, built, bytes)
136
+ }
137
+
138
+ fun write(out: DataOutputStream) {
139
+ out.writeInt(FORMAT)
140
+ out.writeDouble(duration)
141
+ out.writeInt(length)
142
+ viewBox.forEach(out::writeFloat)
143
+ out.writeInt(tracks.size)
144
+ for (track in tracks) {
145
+ out.writeInt(track.fill)
146
+ out.writeFloat(track.fillOpacity)
147
+ out.writeBoolean(track.stroke != null)
148
+ out.writeInt(track.stroke ?: 0)
149
+ out.writeFloat(track.strokeWidth)
150
+ track.opacity.forEach(out::writeFloat)
151
+ track.d.forEach { writePath(out, it) }
152
+ out.writeBoolean(track.clip != null)
153
+ track.clip?.forEach { writePath(out, it) }
154
+ }
155
+ }
156
+
157
+ companion object {
158
+ private const val FORMAT = 1
159
+
160
+ private fun writePath(out: DataOutputStream, path: AvatarPathData) {
161
+ out.writeInt(path.verbs.size)
162
+ out.write(path.verbs)
163
+ out.writeInt(path.points.size)
164
+ path.points.forEach(out::writeFloat)
165
+ }
166
+
167
+ private fun readPath(input: DataInputStream): AvatarPathData {
168
+ val verbs = ByteArray(input.readInt())
169
+ input.readFully(verbs)
170
+ val points = FloatArray(input.readInt()) { input.readFloat() }
171
+ return AvatarPathData(verbs, points)
172
+ }
173
+
174
+ fun read(input: DataInputStream): AvatarLoopData? {
175
+ if (input.readInt() != FORMAT) return null
176
+ val duration = input.readDouble()
177
+ val length = input.readInt()
178
+ val viewBox = FloatArray(4) { input.readFloat() }
179
+ val tracks = List(input.readInt()) {
180
+ val fill = input.readInt()
181
+ val fillOpacity = input.readFloat()
182
+ val stroked = input.readBoolean()
183
+ val stroke = input.readInt()
184
+ val strokeWidth = input.readFloat()
185
+ val opacity = FloatArray(length) { input.readFloat() }
186
+ val d = List(length) { readPath(input) }
187
+ val clip = if (input.readBoolean()) List(length) { readPath(input) } else null
188
+ Track(fill, fillOpacity, if (stroked) stroke else null, strokeWidth, opacity, d, clip)
189
+ }
190
+ return AvatarLoopData(duration, length, viewBox, tracks)
191
+ }
192
+ }
193
+ }
194
+
195
+ /**
196
+ * The rest loops this process has, shared by every avatar surface: the ones in use in memory, and
197
+ * every loop JS has ever handed over in the app's cache directory, so a cold start plays a
198
+ * character's loop without computing it again. Keys come from JS (`vectorLoopKey`) and name the
199
+ * loop's content, so a loop is never read back for anything but what it was made from.
200
+ *
201
+ * Memory is touched on the main thread only; parsing and file work run on one background thread.
202
+ */
203
+ object AvatarLoops {
204
+ /** Loops kept in memory, in bytes of path data. */
205
+ private const val MEMORY_BYTES = 24 shl 20
206
+ /** Loops kept on disk, in bytes of files. */
207
+ private const val DISK_BYTES = 48L shl 20
208
+ private val KEY = Regex("^[0-9a-z]{1,64}$")
209
+
210
+ private val main = Handler(Looper.getMainLooper())
211
+ private val worker = Executors.newSingleThreadExecutor { runnable -> Thread(runnable, "BloomAvatarLoops") }
212
+ private val memory = LinkedHashMap<String, AvatarLoop>(16, .75f, true)
213
+ private var held = 0
214
+ private val waiting = HashMap<String, MutableList<(AvatarLoop?) -> Unit>>()
215
+
216
+ fun validKey(key: String) = KEY.matches(key)
217
+
218
+ private fun directory(context: Context) = File(context.cacheDir, "bloom-avatar-loops")
219
+
220
+ /** The loop `key` names, from memory or disk; `null` when this device has never been given it. */
221
+ fun get(context: Context, key: String, done: (AvatarLoop?) -> Unit) {
222
+ memory[key]?.let { done(it); return }
223
+ if (enqueue(key, done)) return
224
+ val file = File(directory(context), "$key.loop")
225
+ worker.execute {
226
+ val loop = try {
227
+ if (!file.isFile) null else DataInputStream(BufferedInputStream(file.inputStream(), 1 shl 16)).use { input ->
228
+ AvatarLoopData.read(input)?.toLoop()
229
+ }?.also { file.setLastModified(System.currentTimeMillis()) }
230
+ } catch (_: Exception) {
231
+ file.delete()
232
+ null
233
+ }
234
+ main.post { finish(key, loop) }
235
+ }
236
+ }
237
+
238
+ /** Keeps the loop JS computed, in memory and on disk, then hands it to whoever asked for it. */
239
+ fun put(context: Context, key: String, data: () -> AvatarLoopData, done: (AvatarLoop?) -> Unit) {
240
+ memory[key]?.let { done(it); return }
241
+ if (enqueue(key, done)) return
242
+ val directory = directory(context)
243
+ worker.execute {
244
+ val parsed = try { data() } catch (_: Exception) { null }
245
+ val loop = parsed?.toLoop()
246
+ main.post { finish(key, loop) }
247
+ if (parsed != null) save(directory, key, parsed)
248
+ }
249
+ }
250
+
251
+ private fun enqueue(key: String, done: (AvatarLoop?) -> Unit): Boolean {
252
+ val list = waiting[key]
253
+ if (list != null) { list.add(done); return true }
254
+ waiting[key] = mutableListOf(done)
255
+ return false
256
+ }
257
+
258
+ private fun finish(key: String, loop: AvatarLoop?) {
259
+ if (loop != null) remember(key, loop)
260
+ waiting.remove(key)?.forEach { it(loop) }
261
+ }
262
+
263
+ private fun remember(key: String, loop: AvatarLoop) {
264
+ memory.remove(key)?.let { held -= it.bytes }
265
+ memory[key] = loop
266
+ held += loop.bytes
267
+ val oldest = memory.entries.iterator()
268
+ while (held > MEMORY_BYTES && oldest.hasNext()) {
269
+ val entry = oldest.next()
270
+ if (entry.key == key) continue
271
+ held -= entry.value.bytes
272
+ oldest.remove()
273
+ }
274
+ }
275
+
276
+ private fun save(directory: File, key: String, data: AvatarLoopData) {
277
+ try {
278
+ directory.mkdirs()
279
+ val file = File(directory, "$key.loop")
280
+ val partial = File(directory, "$key.part")
281
+ DataOutputStream(BufferedOutputStream(partial.outputStream(), 1 shl 16)).use(data::write)
282
+ if (!partial.renameTo(file)) partial.delete()
283
+ val files = directory.listFiles()?.sortedByDescending { it.lastModified() } ?: return
284
+ var total = 0L
285
+ for (old in files) {
286
+ total += old.length()
287
+ if (total > DISK_BYTES) old.delete()
288
+ }
289
+ } catch (_: Exception) {
290
+ // A loop that cannot be written is computed again on the next start; nothing else changes.
291
+ }
292
+ }
293
+ }
@@ -0,0 +1,351 @@
1
+ package so.oxy.bloom
2
+
3
+ import android.content.Context
4
+ import android.graphics.Bitmap
5
+ import android.graphics.Canvas
6
+ import android.graphics.Paint
7
+ import android.graphics.Path
8
+ import android.os.SystemClock
9
+ import android.util.Base64
10
+ import android.view.Choreographer
11
+ import android.view.View
12
+ import com.facebook.react.bridge.Arguments
13
+ import com.facebook.react.bridge.ReadableArray
14
+ import com.facebook.react.bridge.ReadableMap
15
+ import com.facebook.react.bridge.WritableMap
16
+ import com.facebook.react.uimanager.SimpleViewManager
17
+ import com.facebook.react.uimanager.ThemedReactContext
18
+ import com.facebook.react.uimanager.UIManagerHelper
19
+ import com.facebook.react.uimanager.annotations.ReactProp
20
+ import com.facebook.react.uimanager.events.Event
21
+ import java.io.ByteArrayOutputStream
22
+ import kotlin.math.floor
23
+
24
+ /**
25
+ * Draws an agent avatar (`VectorCharacterAvatar` on Android). JS hands it either one frame to show
26
+ * (`frame`) or, at rest, a loop to play by itself (`loopKey`, `loopTracks`, `loopClock`); the
27
+ * prop and event contract is versioned by the name. See `VectorNativeSurface.tsx`.
28
+ */
29
+ class AvatarSurfaceManager : SimpleViewManager<AvatarSurface>() {
30
+ override fun getName() = "BloomAvatarSurfaceV1"
31
+ override fun getExportedCustomDirectEventTypeConstants(): MutableMap<String, Any> = mutableMapOf(
32
+ "topLoop" to mapOf("registrationName" to "onLoop"),
33
+ "topCapture" to mapOf("registrationName" to "onCapture"),
34
+ )
35
+ override fun createViewInstance(context: ThemedReactContext) = AvatarSurface(context)
36
+ @ReactProp(name = "frame") fun frame(view: AvatarSurface, value: ReadableMap?) { view.nextFrame = value }
37
+ @ReactProp(name = "loopKey") fun loopKey(view: AvatarSurface, value: String?) { view.nextKey = value }
38
+ @ReactProp(name = "loopTracks") fun loopTracks(view: AvatarSurface, value: ReadableMap?) { view.nextTracks = value }
39
+ @ReactProp(name = "loopClock") fun loopClock(view: AvatarSurface, value: ReadableMap?) {
40
+ view.nextClock = value?.let { AvatarSurface.Clock(it.getDouble("epoch"), it.getDouble("time")) }
41
+ }
42
+ @ReactProp(name = "capture") fun capture(view: AvatarSurface, value: Double) { view.nextCapture = value }
43
+ override fun onAfterUpdateTransaction(view: AvatarSurface) {
44
+ super.onAfterUpdateTransaction(view)
45
+ view.commit()
46
+ }
47
+ override fun onDropViewInstance(view: AvatarSurface) {
48
+ view.stop()
49
+ super.onDropViewInstance(view)
50
+ }
51
+ }
52
+
53
+ class AvatarSurface(context: Context) : View(context) {
54
+ /** `epoch` is a `performance.now()` reading (ms, CLOCK_MONOTONIC on Android) at loop time `time` s. */
55
+ data class Clock(val epoch: Double, val time: Double)
56
+
57
+ private class FramePath(val d: Path, val clip: Path?, val fill: Int, val fillAlpha: Int, val stroke: Int?, val strokeAlpha: Int, val strokeWidth: Float)
58
+ private class Frame(val viewBox: FloatArray, val alpha: Int, val paths: List<FramePath>)
59
+
60
+ var nextFrame: ReadableMap? = null
61
+ var nextKey: String? = null
62
+ var nextTracks: ReadableMap? = null
63
+ var nextClock: Clock? = null
64
+ var nextCapture = 0.0
65
+
66
+ private var frameProp: ReadableMap? = null
67
+ private var frame: Frame? = null
68
+ private var key: String? = null
69
+ private var loop: AvatarLoop? = null
70
+ private var request = 0
71
+ private var clock: Clock? = null
72
+ /** The loop frame on screen. Kept after the clock stops, until JS sends a frame of its own. */
73
+ private var loopIndex = -1
74
+ private var showLoop = false
75
+ private var capture = 0.0
76
+ private var ticking = false
77
+ private var visible = true
78
+
79
+ private val density = resources.displayMetrics.density
80
+ private val fillPaint = Paint(Paint.ANTI_ALIAS_FLAG).apply { style = Paint.Style.FILL }
81
+ // As react-native-svg draws a stroke: butt caps, miter joins, its miter limit scaled by density.
82
+ private val strokePaint = Paint(Paint.ANTI_ALIAS_FLAG).apply {
83
+ style = Paint.Style.STROKE
84
+ strokeCap = Paint.Cap.BUTT
85
+ strokeJoin = Paint.Join.MITER
86
+ strokeMiter = 4f * density
87
+ }
88
+ private val tick = Choreographer.FrameCallback { frameTimeNanos -> onTick(frameTimeNanos) }
89
+
90
+ init {
91
+ importantForAccessibility = IMPORTANT_FOR_ACCESSIBILITY_NO
92
+ isClickable = false
93
+ isFocusable = false
94
+ }
95
+
96
+ fun commit() {
97
+ if (nextFrame !== frameProp) {
98
+ frameProp = nextFrame
99
+ frame = nextFrame?.let(::parseFrame)
100
+ // A frame of JS's own replaces the loop frame left on screen when the loop stopped.
101
+ if (nextClock == null) showLoop = false
102
+ invalidate()
103
+ }
104
+ val requestedKey = nextKey?.takeIf(AvatarLoops::validKey)
105
+ if (requestedKey != key) {
106
+ key = requestedKey
107
+ loop = null
108
+ request++
109
+ if (requestedKey != null) resolve(requestedKey, nextTracks)
110
+ } else if (requestedKey != null && loop == null && nextTracks != null) {
111
+ resolve(requestedKey, nextTracks)
112
+ }
113
+ val wasPlaying = clock != null
114
+ clock = nextClock
115
+ if (clock != null) showLoop = true
116
+ if (wasPlaying != (clock != null)) {
117
+ // A new clock reads its frame afresh; a stopped one leaves its last frame on screen.
118
+ if (clock != null) loopIndex = -1
119
+ invalidate()
120
+ }
121
+ if (nextCapture != capture) {
122
+ capture = nextCapture
123
+ if (capture != 0.0) emitCapture(capture)
124
+ }
125
+ schedule()
126
+ }
127
+
128
+ private fun resolve(requested: String, tracks: ReadableMap?) {
129
+ val generation = request
130
+ val done = { found: AvatarLoop? ->
131
+ if (generation == request) {
132
+ loop = found
133
+ emitLoop(requested, found != null)
134
+ schedule()
135
+ invalidate()
136
+ }
137
+ }
138
+ // The props are read here; the paths are parsed off the main thread.
139
+ val copy = tracks?.let { try { tracksOf(it) } catch (_: Exception) { null } }
140
+ if (copy != null) AvatarLoops.put(context, requested, copy, done)
141
+ else AvatarLoops.get(context, requested, done)
142
+ }
143
+
144
+ fun stop() {
145
+ ticking = false
146
+ Choreographer.getInstance().removeFrameCallback(tick)
147
+ }
148
+
149
+ private fun schedule() {
150
+ val run = clock != null && loop != null && visible && isAttachedToWindow
151
+ if (run == ticking) return
152
+ if (run) {
153
+ ticking = true
154
+ Choreographer.getInstance().postFrameCallback(tick)
155
+ } else stop()
156
+ }
157
+
158
+ private fun onTick(frameTimeNanos: Long) {
159
+ if (!ticking) return
160
+ val playing = loop
161
+ val at = clock
162
+ if (playing == null || at == null) { stop(); return }
163
+ val seconds = at.time + (frameTimeNanos / 1e6 - at.epoch) / 1000.0
164
+ val index = playing.index(seconds)
165
+ if (index != loopIndex) {
166
+ loopIndex = index
167
+ invalidate()
168
+ }
169
+ // Wake on the vsync the next loop frame is due, not on every one. Choreographer runs a delayed
170
+ // callback on the first frame whose time (ms) has reached `now + delay`, so the delay is measured
171
+ // from now to the moment the next loop frame is due on this frame's clock: that frame's vsync,
172
+ // not one before it (an early wake finds the same loop frame and has to wake again).
173
+ val frameSeconds = playing.duration / playing.length
174
+ val wrapped = ((seconds % playing.duration) + playing.duration) % playing.duration
175
+ val nextDueMs = frameTimeNanos / 1e6 + ((index + 1) * frameSeconds - wrapped) * 1000.0
176
+ val delay = floor(nextDueMs - SystemClock.uptimeMillis()).toLong()
177
+ Choreographer.getInstance().postFrameCallbackDelayed(tick, maxOf(0L, delay))
178
+ }
179
+
180
+ override fun onAttachedToWindow() {
181
+ super.onAttachedToWindow()
182
+ schedule()
183
+ }
184
+
185
+ override fun onDetachedFromWindow() {
186
+ stop()
187
+ super.onDetachedFromWindow()
188
+ }
189
+
190
+ override fun onVisibilityAggregated(isVisible: Boolean) {
191
+ super.onVisibilityAggregated(isVisible)
192
+ visible = isVisible
193
+ schedule()
194
+ }
195
+
196
+ override fun onDraw(canvas: Canvas) {
197
+ super.onDraw(canvas)
198
+ val playing = loop
199
+ if (showLoop && playing != null) {
200
+ if (loopIndex < 0 || loopIndex >= playing.length) {
201
+ val at = clock ?: return
202
+ loopIndex = playing.index(at.time + (System.nanoTime() / 1e6 - at.epoch) / 1000.0)
203
+ }
204
+ drawLoopFrame(canvas, playing, loopIndex)
205
+ } else frame?.let { drawFrame(canvas, it) }
206
+ }
207
+
208
+ private fun fit(canvas: Canvas, viewBox: FloatArray) {
209
+ if (viewBox[2] <= 0f || viewBox[3] <= 0f) return
210
+ // xMidYMid meet, as an <Svg viewBox> fills its box.
211
+ val scale = minOf(width / viewBox[2], height / viewBox[3])
212
+ canvas.translate((width - viewBox[2] * scale) / 2f - viewBox[0] * scale, (height - viewBox[3] * scale) / 2f - viewBox[1] * scale)
213
+ canvas.scale(scale, scale)
214
+ }
215
+
216
+ private fun drawPath(canvas: Canvas, d: Path, clip: Path?, fill: Int, fillAlpha: Int, stroke: Int?, strokeAlpha: Int, strokeWidth: Float) {
217
+ val saved = canvas.save()
218
+ if (clip != null) canvas.clipPath(clip)
219
+ if (fillAlpha > 0) {
220
+ fillPaint.color = fill
221
+ fillPaint.alpha = fillAlpha
222
+ canvas.drawPath(d, fillPaint)
223
+ }
224
+ if (stroke != null && strokeAlpha > 0 && strokeWidth > 0f) {
225
+ strokePaint.color = stroke
226
+ strokePaint.alpha = strokeAlpha
227
+ strokePaint.strokeWidth = strokeWidth
228
+ canvas.drawPath(d, strokePaint)
229
+ }
230
+ canvas.restoreToCount(saved)
231
+ }
232
+
233
+ private fun drawLoopFrame(canvas: Canvas, playing: AvatarLoop, index: Int) {
234
+ val saved = canvas.save()
235
+ fit(canvas, playing.viewBox)
236
+ for (track in playing.tracks) {
237
+ val opacity = track.opacity[index]
238
+ drawPath(
239
+ canvas, track.d[index], track.clip?.get(index), track.fill, alpha(opacity * track.fillOpacity),
240
+ track.stroke, alpha(opacity), track.strokeWidth,
241
+ )
242
+ }
243
+ canvas.restoreToCount(saved)
244
+ }
245
+
246
+ private fun drawFrame(canvas: Canvas, shown: Frame) {
247
+ val saved = canvas.save()
248
+ // A group's opacity is one layer, as react-native-svg draws `<G opacity>`.
249
+ if (shown.alpha < 255) canvas.saveLayerAlpha(0f, 0f, width.toFloat(), height.toFloat(), shown.alpha)
250
+ fit(canvas, shown.viewBox)
251
+ for (path in shown.paths) drawPath(canvas, path.d, path.clip, path.fill, path.fillAlpha, path.stroke, path.strokeAlpha, path.strokeWidth)
252
+ canvas.restoreToCount(saved)
253
+ }
254
+
255
+ private fun parseFrame(map: ReadableMap): Frame? = try {
256
+ val paths = map.getArray("paths")!!
257
+ Frame(
258
+ floats(map.getArray("viewBox")!!),
259
+ (map.getDouble("opacity") * 255).toInt().coerceIn(0, 255),
260
+ List(paths.size()) { i ->
261
+ val path = paths.getMap(i)!!
262
+ val opacity = path.getDouble("opacity").toFloat()
263
+ val stroke = if (path.hasKey("stroke") && !path.isNull("stroke")) path.getDouble("stroke").toLong().toInt() else null
264
+ FramePath(
265
+ AvatarPathData.parse(path.getString("d")!!).toPath(),
266
+ if (path.hasKey("clip") && !path.isNull("clip")) AvatarPathData.parse(path.getString("clip")!!).toPath() else null,
267
+ path.getDouble("fill").toLong().toInt(),
268
+ alpha(opacity * path.getDouble("fillOpacity").toFloat()),
269
+ stroke,
270
+ alpha(opacity),
271
+ if (stroke != null) path.getDouble("strokeWidth").toFloat() else 0f,
272
+ )
273
+ },
274
+ )
275
+ } catch (_: Exception) {
276
+ null
277
+ }
278
+
279
+ private fun emitLoop(loopKey: String, ready: Boolean) = emit("topLoop") {
280
+ putString("key", loopKey)
281
+ putBoolean("ready", ready)
282
+ }
283
+
284
+ private fun emitCapture(id: Double) {
285
+ val data = try {
286
+ val bitmap = Bitmap.createBitmap(maxOf(1, width), maxOf(1, height), Bitmap.Config.ARGB_8888)
287
+ draw(Canvas(bitmap))
288
+ val bytes = ByteArrayOutputStream()
289
+ bitmap.compress(Bitmap.CompressFormat.PNG, 100, bytes)
290
+ bitmap.recycle()
291
+ Base64.encodeToString(bytes.toByteArray(), Base64.NO_WRAP)
292
+ } catch (_: Exception) {
293
+ null
294
+ }
295
+ emit("topCapture") {
296
+ putDouble("id", id)
297
+ if (data != null) putString("data", data) else putNull("data")
298
+ }
299
+ }
300
+
301
+ private fun emit(name: String, fill: WritableMap.() -> Unit) {
302
+ val context = context as? ThemedReactContext ?: return
303
+ val dispatcher = UIManagerHelper.getEventDispatcherForReactTag(context, id) ?: return
304
+ dispatcher.dispatchEvent(SurfaceEvent(UIManagerHelper.getSurfaceId(this), id, name, Arguments.createMap().apply(fill)))
305
+ }
306
+
307
+ companion object {
308
+ /** react-native-svg's rounding of an opacity to a paint alpha. */
309
+ fun alpha(opacity: Float) = Math.round(255f * opacity).coerceIn(0, 255)
310
+
311
+ private fun floats(array: ReadableArray) = FloatArray(array.size()) { array.getDouble(it).toFloat() }
312
+ private fun strings(array: ReadableArray) = List(array.size()) { array.getString(it)!! }
313
+
314
+ /** Copies a loop's props; the returned function parses them (`AvatarLoops.put` runs it off the main thread). */
315
+ fun tracksOf(map: ReadableMap): () -> AvatarLoopData {
316
+ val duration = map.getDouble("duration")
317
+ val length = map.getInt("length")
318
+ val viewBox = floats(map.getArray("viewBox")!!)
319
+ val paths = map.getArray("paths")!!
320
+ val raw = List(paths.size()) { i ->
321
+ val path = paths.getMap(i)!!
322
+ val stroke = if (path.hasKey("stroke") && !path.isNull("stroke")) path.getDouble("stroke").toLong().toInt() else null
323
+ val clip = if (path.hasKey("clip") && !path.isNull("clip")) strings(path.getArray("clip")!!) else null
324
+ val opacity = floats(path.getArray("opacity")!!)
325
+ val d = strings(path.getArray("d")!!)
326
+ require(opacity.size == length && d.size == length && (clip == null || clip.size == length)) { "Avatar loop: tracks of unequal length" }
327
+ RawTrack(
328
+ path.getDouble("fill").toLong().toInt(), path.getDouble("fillOpacity").toFloat(), stroke,
329
+ if (stroke != null) path.getDouble("strokeWidth").toFloat() else 0f, opacity, d, clip,
330
+ )
331
+ }
332
+ return {
333
+ AvatarLoopData(duration, length, viewBox, raw.map { track ->
334
+ AvatarLoopData.Track(
335
+ track.fill, track.fillOpacity, track.stroke, track.strokeWidth, track.opacity,
336
+ track.d.map(AvatarPathData::parse), track.clip?.map(AvatarPathData::parse),
337
+ )
338
+ })
339
+ }
340
+ }
341
+
342
+ private class RawTrack(val fill: Int, val fillOpacity: Float, val stroke: Int?, val strokeWidth: Float, val opacity: FloatArray, val d: List<String>, val clip: List<String>?)
343
+ }
344
+ }
345
+
346
+ private class SurfaceEvent(surfaceId: Int, viewId: Int, private val name: String, private val data: WritableMap) :
347
+ Event<SurfaceEvent>(surfaceId, viewId) {
348
+ override fun getEventName() = name
349
+ override fun canCoalesce() = false
350
+ override fun getEventData() = data
351
+ }
@@ -11,6 +11,6 @@ class BloomPackage : ReactPackage {
11
11
  override fun createNativeModules(context: ReactApplicationContext): List<NativeModule> = emptyList()
12
12
  override fun createViewManagers(context: ReactApplicationContext): List<ViewManager<*, *>> =
13
13
  listOf<ViewManager<*, *>>(BloomIconManager()) +
14
- PredictiveBackManagers.create() +
14
+ PredictiveBackManagers.create() + AvatarSurfaceManager() +
15
15
  if (Build.VERSION.SDK_INT >= 31) listOf(ComposerLightManager()) else emptyList()
16
16
  }