-
Notifications
You must be signed in to change notification settings - Fork 8
Expand file tree
/
Copy pathRiveReactNativeView.kt
More file actions
436 lines (389 loc) · 13.4 KB
/
RiveReactNativeView.kt
File metadata and controls
436 lines (389 loc) · 13.4 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
package com.rive
import android.annotation.SuppressLint
import android.widget.FrameLayout
import androidx.lifecycle.LifecycleObserver
import androidx.lifecycle.LifecycleOwner
import app.rive.runtime.kotlin.RiveAnimationView
import app.rive.runtime.kotlin.RiveViewLifecycleObserver
import app.rive.runtime.kotlin.controllers.RiveFileController
import app.rive.runtime.kotlin.core.RefCount
import com.facebook.react.uimanager.ThemedReactContext
import app.rive.runtime.kotlin.core.Alignment
import app.rive.runtime.kotlin.core.File
import app.rive.runtime.kotlin.core.Fit
import app.rive.runtime.kotlin.core.RiveEvent
import app.rive.runtime.kotlin.core.RiveOpenURLEvent
import app.rive.runtime.kotlin.core.SMIBoolean
import app.rive.runtime.kotlin.core.SMIInput
import app.rive.runtime.kotlin.core.SMINumber
import app.rive.runtime.kotlin.core.SMITrigger
import app.rive.runtime.kotlin.core.ViewModelInstance
import app.rive.runtime.kotlin.core.errors.ViewModelException
import com.margelo.nitro.rive.EventPropertiesOutput
import com.margelo.nitro.rive.EventPropertiesOutputExtensions as EPO
import com.margelo.nitro.rive.RiveEventType
import com.margelo.nitro.rive.UnifiedRiveEvent as RNEvent
import kotlinx.coroutines.CompletableDeferred
sealed class BindData {
data object None : BindData()
data object Auto : BindData()
data class Instance(val instance: ViewModelInstance) : BindData()
data class ByName(val name: String) : BindData()
}
data class ViewConfiguration(
val artboardName: String?,
val stateMachineName: String?,
val autoPlay: Boolean,
val riveFile: File,
val alignment: Alignment,
val fit: Fit,
val layoutScaleFactor: Float?,
val bindData: BindData
)
class ReactNativeRiveViewLifecycleObserver(dependencies: MutableList<RefCount>) :
RiveViewLifecycleObserver(dependencies) {
@SuppressLint("MissingSuperCall")
override fun onDestroy(owner: LifecycleOwner) {
owner.lifecycle.removeObserver(this)
}
fun dispose() {
dependencies.forEach { it.release() }
dependencies.clear()
}
}
@SuppressLint("ViewConstructor")
class ReactNativeRiveAnimationView(context: ThemedReactContext) : RiveAnimationView(context) {
fun dispose() {
(lifecycleObserver as ReactNativeRiveViewLifecycleObserver).dispose()
}
@SuppressLint("VisibleForTests")
override fun createObserver(): LifecycleObserver {
return ReactNativeRiveViewLifecycleObserver(
listOfNotNull(controller, rendererAttributes.assetLoader).toMutableList()
)
}
}
@SuppressLint("ViewConstructor")
class RiveReactNativeView(context: ThemedReactContext) : FrameLayout(context) {
internal var riveAnimationView: ReactNativeRiveAnimationView? = null
private var eventListeners: MutableList<RiveFileController.RiveEventListener> = mutableListOf()
private val viewReadyDeferred = CompletableDeferred<Boolean>()
private var _activeStateMachineName: String? = null
private var willDispose = false
init {
riveAnimationView = ReactNativeRiveAnimationView(context)
addView(riveAnimationView)
}
fun dispose() {
willDispose = true
}
override fun onDetachedFromWindow() {
if (willDispose) {
riveAnimationView?.dispose()
removeEventListeners()
}
super.onDetachedFromWindow()
}
//region Public Methods (API)
suspend fun awaitViewReady(): Boolean {
return viewReadyDeferred.await()
}
fun configure(config: ViewConfiguration, dataBindingChanged: Boolean, reload: Boolean = false, initialUpdate: Boolean = false) {
if (reload) {
val hasDataBinding = when (config.bindData) {
is BindData.None -> false
is BindData.Auto -> false
is BindData.Instance, is BindData.ByName -> true
}
riveAnimationView?.setRiveFile(
config.riveFile,
artboardName = config.artboardName,
stateMachineName = config.stateMachineName,
autoplay = config.autoPlay,
autoBind = hasDataBinding,
alignment = config.alignment,
fit = config.fit
)
_activeStateMachineName = getSafeStateMachineName()
} else {
riveAnimationView?.alignment = config.alignment
riveAnimationView?.fit = config.fit
// TODO: this seems to require a reload for the view to take the new value (bug on Android)
riveAnimationView?.layoutScaleFactor = config.layoutScaleFactor
}
if (dataBindingChanged || initialUpdate || reload) {
applyDataBinding(config.bindData)
}
viewReadyDeferred.complete(true)
}
fun bindViewModelInstance(vmi: ViewModelInstance) {
val stateMachines = riveAnimationView?.controller?.stateMachines
if (!stateMachines.isNullOrEmpty()) {
stateMachines.first().viewModelInstance = vmi
}
}
fun getViewModelInstance(): ViewModelInstance? {
val stateMachines = riveAnimationView?.controller?.stateMachines
return if (!stateMachines.isNullOrEmpty()) {
stateMachines.first().viewModelInstance
} else {
null
}
}
fun applyDataBinding(bindData: BindData) {
bindToStateMachine(bindData)
}
fun play() {
if (_activeStateMachineName == null) {
_activeStateMachineName = getSafeStateMachineName()
}
riveAnimationView?.play()
}
fun pause() = riveAnimationView?.pause()
fun reset() = riveAnimationView?.reset()
fun playIfNeeded() {
if (riveAnimationView?.isPlaying == false) {
riveAnimationView?.post {
riveAnimationView?.play()
}
}
}
fun addEventListener(onEvent: (event: RNEvent) -> Unit) {
val eventListener = object : RiveFileController.RiveEventListener {
override fun notifyEvent(event: RiveEvent) {
// TODO: Handle general events better (in case of audio events)
val rnEvent = RNEvent(
name = event.name,
type = if (event is RiveOpenURLEvent) RiveEventType.OPENURL else RiveEventType.GENERAL,
delay = event.delay.toDouble(),
properties = convertEventProperties(event.properties),
url = (event as? RiveOpenURLEvent)?.url,
target = (event as? RiveOpenURLEvent)?.target
)
onEvent(rnEvent)
}
}
riveAnimationView?.addEventListener(eventListener)
eventListeners.add(eventListener)
}
fun removeEventListeners() {
for (eventListener in eventListeners) {
riveAnimationView?.removeEventListener(eventListener)
}
eventListeners.clear()
}
fun setNumberInputValue(name: String, value: Double, path: String?) {
handleInput(
name = name,
path = path,
type = InputType.Number,
onSuccess = { _ ->
// Use Rive Android's queue system to actually set the input
riveAnimationView?.controller?.setNumberState(
stateMachineName = activeStateMachineName,
inputName = name,
value = value.toFloat(),
path = path
)
value
}
)
}
fun getNumberInputValue(name: String, path: String?): Double {
return handleInput(
name = name,
path = path,
type = InputType.Number,
onSuccess = { smi -> (smi as SMINumber).value.toDouble() }
)
}
fun setBooleanInputValue(name: String, value: Boolean, path: String?) {
handleInput(
name = name,
path = path,
type = InputType.BooleanInput,
onSuccess = { _ ->
// Use Rive Android's queue system to actually set the input
riveAnimationView?.controller?.setBooleanState(
stateMachineName = activeStateMachineName,
inputName = name,
value = value,
path = path
)
value
}
)
}
fun getBooleanInputValue(name: String, path: String?): Boolean {
return handleInput(
name = name,
path = path,
type = InputType.BooleanInput,
onSuccess = { smi -> (smi as SMIBoolean).value }
)
}
fun triggerInput(name: String, path: String?) {
handleInput(
name = name,
path = path,
type = InputType.Trigger,
onSuccess = {
riveAnimationView?.controller?.fireState(
stateMachineName = activeStateMachineName,
inputName = name,
path = path
)
}
)
}
fun setTextRunValue(name: String, value: String, path: String?) {
try {
if (path == null) {
riveAnimationView?.setTextRunValue(name, value)
} else {
riveAnimationView?.setTextRunValue(name, value, path)
}
} catch (e: Exception) {
throw Error(e.message)
}
}
fun getTextRunValue(name: String, path: String?): String {
val value = if (path == null) {
riveAnimationView?.getTextRunValue(name)
} else {
riveAnimationView?.getTextRunValue(name, path)
}
if (value == null) {
throw Error("Could not find text run value (name: $name, path: $path)")
}
return value
}
//endregion
//region Internal
private fun bindToStateMachine(bindData: BindData) {
val stateMachines = riveAnimationView?.controller?.stateMachines
if (stateMachines.isNullOrEmpty()) return
val stateMachine = stateMachines.first()
when (bindData) {
is BindData.None -> {
stateMachine.viewModelInstance = null
}
is BindData.Auto -> {
val artboard = riveAnimationView?.controller?.activeArtboard
val file = riveAnimationView?.controller?.file
if (artboard != null && file != null) {
try {
file.defaultViewModelForArtboard(artboard)
} catch (e: ViewModelException) {
null
}?.let {
val instance = it.createDefaultInstance()
stateMachine.viewModelInstance = instance
}
}
}
is BindData.Instance -> {
stateMachine.viewModelInstance = bindData.instance
}
is BindData.ByName -> {
val artboard = riveAnimationView?.controller?.activeArtboard
val file = riveAnimationView?.controller?.file
if (artboard != null && file != null) {
val viewModel = file.defaultViewModelForArtboard(artboard)
val instance = viewModel.createInstanceFromName(bindData.name)
stateMachine.viewModelInstance = instance
}
}
}
}
private fun convertEventProperties(properties: Map<String, Any>?): Map<String, EventPropertiesOutput>? {
if (properties == null) return null
val newMap = HashMap<String, EventPropertiesOutput>()
properties.forEach { (key, value) ->
when (value) {
is String -> newMap.set(key, EPO.string(value))
is Number -> newMap.set(key, EPO.number(value.toDouble()))
is Boolean -> newMap.set(key, EPO.boolean(value))
}
}
return newMap
}
/**
* Gets the SMI input from the Rive file.
* @param name The name of the input.
* @param path The path of the input.
* @return The SMI input.
* @throws Error if the input is not found.
*/
private fun getSMIInput(name: String, path: String?): SMIInput {
try {
val smi = if (path == null) {
val stateMachine = riveAnimationView?.controller?.stateMachines?.get(0)
stateMachine?.input(name)
} else {
val artboard = riveAnimationView?.controller?.activeArtboard
artboard?.input(name, path)
}
if (smi == null) throw Exception("Could not find input (name: $name, path: $path)")
return smi
} catch (e: Exception) {
throw Error(e.message)
}
}
// This is a temporary solution to get the state machine name as Android supports
// playing multiple state machines, but in React Native we only allow playing one.
/**
* Gets the name of the active state machine, or null if no state machines are loaded yet
* (e.g. when autoPlay is false and the state machine hasn't been started).
* @return The name of the state machine, or null
*/
private fun getSafeStateMachineName(): String? {
val stateMachines = riveAnimationView?.controller?.stateMachines
if (stateMachines.isNullOrEmpty()) return null
return stateMachines.first().name
}
/**
* The name of the active state machine.
* @throws Error if the state machine name could not be found
* @return The name of the state machine that "is playing" / "will be played"
*/
private val activeStateMachineName: String
get() = _activeStateMachineName
?: throw Error("View not configured. Could not find active state machine name")
/**
* The type of the state machine input.
* @param T The type of the state machine input.
*/
private sealed class InputType<T> {
data object Number : InputType<Double>()
data object BooleanInput : InputType<Boolean>()
data object Trigger : InputType<Unit>()
}
/**
* Handles the state machine input.
* @param name The name of the input.
* @param path The path of the input.
* @param type The type of the input.
* @param onSuccess The function to call when the input is successfully handled.
* @return The value of the input.
*/
private inline fun <T> handleInput(
name: String,
path: String?,
type: InputType<T>,
onSuccess: (SMIInput) -> T
): T {
val smi = getSMIInput(name, path)
when (type) {
is InputType.Number -> if (smi !is SMINumber) throw Error("State machine input is not a number")
is InputType.BooleanInput -> if (smi !is SMIBoolean) throw Error("State machine input is not a boolean")
is InputType.Trigger -> if (smi !is SMITrigger) throw Error("State machine input is not a trigger")
}
try {
return onSuccess(smi)
} catch (e: Exception) {
throw Error("Could not handle ${type::class.simpleName?.lowercase()} state machine input")
}
}
//endregion
}