react-native-gleam 1.0.0-beta.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.
package/Gleam.podspec ADDED
@@ -0,0 +1,20 @@
1
+ require "json"
2
+
3
+ package = JSON.parse(File.read(File.join(__dir__, "package.json")))
4
+
5
+ Pod::Spec.new do |s|
6
+ s.name = "Gleam"
7
+ s.version = package["version"]
8
+ s.summary = package["description"]
9
+ s.homepage = package["homepage"]
10
+ s.license = package["license"]
11
+ s.authors = package["author"]
12
+
13
+ s.platforms = { :ios => min_ios_version_supported }
14
+ s.source = { :git => "https://github.com/AppAndFlow/react-native-gleam.git", :tag => "#{s.version}" }
15
+
16
+ s.source_files = "ios/**/*.{h,m,mm,swift,cpp}"
17
+ s.private_header_files = "ios/**/*.h"
18
+
19
+ install_modules_dependencies(s)
20
+ end
package/LICENSE ADDED
@@ -0,0 +1,20 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2026 David Boutin
4
+ Permission is hereby granted, free of charge, to any person obtaining a copy
5
+ of this software and associated documentation files (the "Software"), to deal
6
+ in the Software without restriction, including without limitation the rights
7
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
8
+ copies of the Software, and to permit persons to whom the Software is
9
+ furnished to do so, subject to the following conditions:
10
+
11
+ The above copyright notice and this permission notice shall be included in all
12
+ copies or substantial portions of the Software.
13
+
14
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
15
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
16
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
17
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
18
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
19
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
20
+ SOFTWARE.
package/README.md ADDED
@@ -0,0 +1,150 @@
1
+ # react-native-gleam
2
+
3
+ Native-powered shimmer loading effect for React Native. Built with pure native animations — no reanimated, no SVG, zero dependencies.
4
+
5
+ - **iOS**: `CAGradientLayer` + `CADisplayLink`
6
+ - **Android**: `Choreographer` + `LinearGradient`
7
+ - **Fabric only** (New Architecture)
8
+
9
+ https://github.com/user-attachments/assets/70eb886c-f3e2-4611-8ecc-0b03227267d0
10
+
11
+ ## Installation
12
+
13
+ ```sh
14
+ yarn add react-native-gleam
15
+ ```
16
+
17
+ ```sh
18
+ npm install react-native-gleam
19
+ ```
20
+
21
+ ### Bare React Native
22
+
23
+ Run `pod install` in your `ios/` directory.
24
+
25
+ ### Expo
26
+
27
+ This library includes native code and requires a [development build](https://docs.expo.dev/develop/development-builds/introduction/). It does not work with Expo Go.
28
+
29
+ ```sh
30
+ npx expo install react-native-gleam
31
+ npx expo prebuild
32
+ ```
33
+
34
+ No config plugin needed — autolinking and codegen handle everything.
35
+
36
+ ## Usage
37
+
38
+ ```tsx
39
+ import { GleamView, GleamDirection, GleamTransition } from 'react-native-gleam';
40
+
41
+ function UserCard({ loading, user }) {
42
+ return (
43
+ <GleamView
44
+ loading={loading}
45
+ style={{ width: '100%', height: 80, borderRadius: 12 }}
46
+ >
47
+ <Text>{user.name}</Text>
48
+ </GleamView>
49
+ );
50
+ }
51
+ ```
52
+
53
+ When `loading={true}`, children are hidden and a shimmer animation plays. When `loading={false}`, the shimmer fades out and children fade in.
54
+
55
+ ### Staggered skeleton
56
+
57
+ ```tsx
58
+ <GleamView loading delay={0} style={styles.row} />
59
+ <GleamView loading delay={150} style={styles.row} />
60
+ <GleamView loading delay={300} style={styles.row} />
61
+ ```
62
+
63
+ ### All props
64
+
65
+ ```tsx
66
+ <GleamView
67
+ loading={isLoading}
68
+ speed={800}
69
+ direction={GleamDirection.LeftToRight}
70
+ delay={0}
71
+ transitionDuration={300}
72
+ transitionType={GleamTransition.Fade}
73
+ intensity={0.7}
74
+ baseColor="#E0E0E0"
75
+ highlightColor="#F5F5F5"
76
+ onTransitionEnd={({ nativeEvent }) => {
77
+ console.log('Done', nativeEvent.finished);
78
+ }}
79
+ style={{ width: '100%', height: 80, borderRadius: 12 }}
80
+ >
81
+ <Text>Your content</Text>
82
+ </GleamView>
83
+ ```
84
+
85
+ ## Props
86
+
87
+ | Prop | Type | Default | Description |
88
+ |------|------|---------|-------------|
89
+ | `loading` | `boolean` | `true` | Toggle shimmer on/off |
90
+ | `speed` | `number` | `1000` | Duration of one shimmer cycle (ms) |
91
+ | `direction` | `GleamDirection` | `LeftToRight` | Animation direction |
92
+ | `delay` | `number` | `0` | Delay before animation starts (ms) — useful for stagger |
93
+ | `transitionDuration` | `number` | `300` | Duration of the transition from shimmer to content (ms). `0` = instant |
94
+ | `transitionType` | `GleamTransition` | `Fade` | Transition style when loading ends |
95
+ | `intensity` | `number` | `1` | Highlight strength (0-1). Lower = more subtle shimmer |
96
+ | `baseColor` | `string` | `#E0E0E0` | Background color of the shimmer |
97
+ | `highlightColor` | `string` | `#F5F5F5` | Color of the moving highlight |
98
+ | `onTransitionEnd` | `function` | — | Called when the fade transition completes. Receives `{ nativeEvent: { finished: boolean } }` |
99
+
100
+ All standard `View` props are also supported (`style`, `testID`, etc.).
101
+
102
+ ### GleamDirection
103
+
104
+ ```tsx
105
+ import { GleamDirection } from 'react-native-gleam';
106
+
107
+ GleamDirection.LeftToRight // 'ltr' (default)
108
+ GleamDirection.RightToLeft // 'rtl'
109
+ GleamDirection.TopToBottom // 'ttb'
110
+ ```
111
+
112
+ ### GleamTransition
113
+
114
+ ```tsx
115
+ import { GleamTransition } from 'react-native-gleam';
116
+
117
+ GleamTransition.Fade // 'fade' (default) — opacity crossfade
118
+ GleamTransition.Shrink // 'shrink' — shimmer scales down while fading
119
+ GleamTransition.Collapse // 'collapse' — shimmer collapses vertically then horizontally
120
+ ```
121
+
122
+ ## Requirements
123
+
124
+ - React Native **0.76+** (New Architecture / Fabric)
125
+ - iOS 15+
126
+ - Android SDK 24+
127
+
128
+ This library requires the New Architecture (Fabric). It does not support the old architecture (Paper).
129
+
130
+ ## How it works
131
+
132
+ `GleamView` wraps your content in a native view. When `loading={true}`:
133
+
134
+ 1. Children are hidden (opacity 0)
135
+ 2. A gradient overlay animates across the view
136
+ 3. The gradient uses `baseColor` → `highlightColor` → `baseColor`
137
+
138
+ When `loading` switches to `false`:
139
+
140
+ 1. The shimmer transitions out over `transitionDuration` ms (style depends on `transitionType`)
141
+ 2. Children fade in simultaneously
142
+ 3. `onTransitionEnd` fires when complete
143
+
144
+ All shimmer instances sharing the same `speed` are automatically synchronized via a shared clock.
145
+
146
+ The shimmer respects `borderRadius` and all standard view styles.
147
+
148
+ ## License
149
+
150
+ MIT
@@ -0,0 +1,67 @@
1
+ buildscript {
2
+ ext.Gleam = [
3
+ kotlinVersion: "2.0.21",
4
+ minSdkVersion: 24,
5
+ compileSdkVersion: 36,
6
+ targetSdkVersion: 36
7
+ ]
8
+
9
+ ext.getExtOrDefault = { prop ->
10
+ if (rootProject.ext.has(prop)) {
11
+ return rootProject.ext.get(prop)
12
+ }
13
+
14
+ return Gleam[prop]
15
+ }
16
+
17
+ repositories {
18
+ google()
19
+ mavenCentral()
20
+ }
21
+
22
+ dependencies {
23
+ classpath "com.android.tools.build:gradle:8.7.2"
24
+ // noinspection DifferentKotlinGradleVersion
25
+ classpath "org.jetbrains.kotlin:kotlin-gradle-plugin:${getExtOrDefault('kotlinVersion')}"
26
+ }
27
+ }
28
+
29
+
30
+ apply plugin: "com.android.library"
31
+ apply plugin: "kotlin-android"
32
+
33
+ apply plugin: "com.facebook.react"
34
+
35
+ android {
36
+ namespace "com.gleam"
37
+
38
+ compileSdkVersion getExtOrDefault("compileSdkVersion")
39
+
40
+ defaultConfig {
41
+ minSdkVersion getExtOrDefault("minSdkVersion")
42
+ targetSdkVersion getExtOrDefault("targetSdkVersion")
43
+ }
44
+
45
+ buildFeatures {
46
+ buildConfig true
47
+ }
48
+
49
+ buildTypes {
50
+ release {
51
+ minifyEnabled false
52
+ }
53
+ }
54
+
55
+ lint {
56
+ disable "GradleCompatible"
57
+ }
58
+
59
+ compileOptions {
60
+ sourceCompatibility JavaVersion.VERSION_1_8
61
+ targetCompatibility JavaVersion.VERSION_1_8
62
+ }
63
+ }
64
+
65
+ dependencies {
66
+ implementation "com.facebook.react:react-android"
67
+ }
@@ -0,0 +1,2 @@
1
+ <manifest xmlns:android="http://schemas.android.com/apk/res/android">
2
+ </manifest>
@@ -0,0 +1,17 @@
1
+ package com.gleam
2
+
3
+ import com.facebook.react.BaseReactPackage
4
+ import com.facebook.react.bridge.NativeModule
5
+ import com.facebook.react.bridge.ReactApplicationContext
6
+ import com.facebook.react.module.model.ReactModuleInfoProvider
7
+ import com.facebook.react.uimanager.ViewManager
8
+
9
+ class GleamViewPackage : BaseReactPackage() {
10
+ override fun createViewManagers(reactContext: ReactApplicationContext): List<ViewManager<*, *>> {
11
+ return listOf(GleamViewManager())
12
+ }
13
+
14
+ override fun getModule(name: String, reactContext: ReactApplicationContext): NativeModule? = null
15
+
16
+ override fun getReactModuleInfoProvider() = ReactModuleInfoProvider { emptyMap() }
17
+ }
@@ -0,0 +1,379 @@
1
+ package com.gleam
2
+
3
+ import android.animation.ValueAnimator
4
+ import android.content.Context
5
+ import android.graphics.Canvas
6
+ import android.graphics.Color
7
+ import android.graphics.LinearGradient
8
+ import android.graphics.Paint
9
+ import android.graphics.Path
10
+ import android.graphics.RectF
11
+ import android.graphics.Shader
12
+ import android.os.SystemClock
13
+ import android.view.Choreographer
14
+ import android.view.animation.DecelerateInterpolator
15
+ import com.facebook.react.bridge.Arguments
16
+ import com.facebook.react.bridge.ReactContext
17
+ import com.facebook.react.bridge.WritableMap
18
+ import com.facebook.react.uimanager.PixelUtil
19
+ import com.facebook.react.uimanager.UIManagerHelper
20
+ import com.facebook.react.uimanager.events.Event
21
+ import com.facebook.react.views.view.ReactViewGroup
22
+ import kotlin.math.cos
23
+ import kotlin.math.PI
24
+
25
+ class GleamView(context: Context) : ReactViewGroup(context) {
26
+
27
+ enum class Direction { LTR, RTL, TTB }
28
+ enum class TransitionType { FADE, SHRINK, COLLAPSE }
29
+
30
+ var loading: Boolean = true
31
+ set(value) {
32
+ if (field != value) {
33
+ val wasLoading = field
34
+ field = value
35
+ applyLoadingState(wasLoading)
36
+ }
37
+ }
38
+
39
+ var speed: Float = 1000f
40
+ set(value) {
41
+ if (field != value) {
42
+ field = value
43
+ }
44
+ }
45
+
46
+ var direction: Direction = Direction.LTR
47
+ set(value) {
48
+ if (field != value) {
49
+ field = value
50
+ }
51
+ }
52
+
53
+ var delay: Float = 0f
54
+ set(value) {
55
+ if (field != value) {
56
+ field = value
57
+ }
58
+ }
59
+
60
+ var transitionDuration: Float = 300f
61
+ set(value) {
62
+ if (field != value) {
63
+ field = value
64
+ }
65
+ }
66
+
67
+ var transitionType: TransitionType = TransitionType.FADE
68
+ set(value) {
69
+ if (field != value) {
70
+ field = value
71
+ }
72
+ }
73
+
74
+ var intensity: Float = 1f
75
+ set(value) {
76
+ if (field != value) {
77
+ field = value.coerceIn(0f, 1f)
78
+ invalidate()
79
+ }
80
+ }
81
+
82
+ var baseColor: Int = 0xFFE0E0E0.toInt()
83
+ set(value) {
84
+ if (field != value) {
85
+ field = value
86
+ invalidate()
87
+ }
88
+ }
89
+
90
+ var highlightColor: Int = 0xFFF5F5F5.toInt()
91
+ set(value) {
92
+ if (field != value) {
93
+ field = value
94
+ invalidate()
95
+ }
96
+ }
97
+
98
+ private val shimmerPaint = Paint()
99
+ private val gradientColors = IntArray(3)
100
+ private val gradientPositions = floatArrayOf(0f, 0.5f, 1f)
101
+ private val gradientCoords = FloatArray(4)
102
+ private val clipPath = Path()
103
+ private val clipRect = RectF()
104
+ internal var cornerRadius: Float = 0f
105
+ private var transitionAnimator: ValueAnimator? = null
106
+ private var shimmerOpacity: Float = 1f
107
+ private var contentOpacity: Float = 0f
108
+ private var isTransitioning: Boolean = false
109
+ private var transitionProgress: Float = 0f
110
+ private var isRegistered: Boolean = false
111
+
112
+ init {
113
+ setWillNotDraw(false)
114
+ }
115
+
116
+ override fun onAttachedToWindow() {
117
+ super.onAttachedToWindow()
118
+ if (loading) {
119
+ registerClock()
120
+ }
121
+ }
122
+
123
+ override fun onDetachedFromWindow() {
124
+ super.onDetachedFromWindow()
125
+ unregisterClock()
126
+ transitionAnimator?.cancel()
127
+ transitionAnimator = null
128
+ isTransitioning = false
129
+ }
130
+
131
+ override fun onSizeChanged(w: Int, h: Int, oldw: Int, oldh: Int) {
132
+ super.onSizeChanged(w, h, oldw, oldh)
133
+ if (loading && w > 0 && h > 0 && !isRegistered) {
134
+ registerClock()
135
+ }
136
+ }
137
+
138
+ private fun registerClock() {
139
+ if (!isRegistered) {
140
+ isRegistered = true
141
+ SharedClock.register(this)
142
+ }
143
+ }
144
+
145
+ private fun unregisterClock() {
146
+ if (isRegistered) {
147
+ isRegistered = false
148
+ SharedClock.unregister(this)
149
+ }
150
+ }
151
+
152
+ /** Called by SharedClock every frame */
153
+ fun onFrame() {
154
+ invalidate()
155
+ }
156
+
157
+ /**
158
+ * Compute progress from global time.
159
+ * Uses cosine easing: progress = (1 - cos(phase)) / 2
160
+ * This matches AccelerateDecelerateInterpolator and ensures smooth looping.
161
+ */
162
+ private fun computeProgress(): Float {
163
+ val timeMs = SystemClock.uptimeMillis().toFloat()
164
+ val effectiveTime = (timeMs - delay).coerceAtLeast(0f)
165
+ val rawProgress = (effectiveTime % speed) / speed
166
+ // AccelerateDecelerateInterpolator equivalent: (cos((x + 1) * PI) / 2) + 0.5
167
+ return ((cos((rawProgress + 1.0) * PI) / 2.0) + 0.5).toFloat()
168
+ }
169
+
170
+ override fun dispatchDraw(canvas: Canvas) {
171
+ val w = width.toFloat()
172
+ val h = height.toFloat()
173
+ if (w <= 0 || h <= 0) return
174
+
175
+ // Draw children with content opacity
176
+ if (contentOpacity > 0f) {
177
+ if (contentOpacity < 1f) {
178
+ val count = canvas.saveLayerAlpha(0f, 0f, w, h, (contentOpacity * 255).toInt())
179
+ super.dispatchDraw(canvas)
180
+ canvas.restoreToCount(count)
181
+ } else {
182
+ super.dispatchDraw(canvas)
183
+ }
184
+ }
185
+
186
+ // Draw shimmer overlay
187
+ if ((loading || isTransitioning) && shimmerOpacity > 0f) {
188
+ val animationProgress = computeProgress()
189
+
190
+ val effectiveHighlight = if (intensity < 1f) {
191
+ blendColor(baseColor, highlightColor, intensity)
192
+ } else {
193
+ highlightColor
194
+ }
195
+
196
+ gradientColors[0] = baseColor
197
+ gradientColors[1] = effectiveHighlight
198
+ gradientColors[2] = baseColor
199
+
200
+ when (direction) {
201
+ Direction.LTR -> {
202
+ val size = w
203
+ val s = -size + (animationProgress * (w + 2 * size))
204
+ gradientCoords[0] = s; gradientCoords[1] = 0f
205
+ gradientCoords[2] = s + size; gradientCoords[3] = 0f
206
+ }
207
+ Direction.RTL -> {
208
+ val size = w
209
+ val s = w + size - (animationProgress * (w + 2 * size))
210
+ gradientCoords[0] = s; gradientCoords[1] = 0f
211
+ gradientCoords[2] = s - size; gradientCoords[3] = 0f
212
+ }
213
+ Direction.TTB -> {
214
+ val size = h
215
+ val s = -size + (animationProgress * (h + 2 * size))
216
+ gradientCoords[0] = 0f; gradientCoords[1] = s
217
+ gradientCoords[2] = 0f; gradientCoords[3] = s + size
218
+ }
219
+ }
220
+
221
+ shimmerPaint.shader = LinearGradient(
222
+ gradientCoords[0], gradientCoords[1],
223
+ gradientCoords[2], gradientCoords[3],
224
+ gradientColors, gradientPositions,
225
+ Shader.TileMode.CLAMP
226
+ )
227
+ shimmerPaint.alpha = (shimmerOpacity * 255).toInt()
228
+
229
+ // Shrink: scale down, fade starts at 30%
230
+ if (isTransitioning && transitionType == TransitionType.SHRINK) {
231
+ val scale = 1f - transitionProgress * 0.5f
232
+ val shrinkOpacity = (1f - transitionProgress * 2.5f).coerceAtLeast(0f)
233
+ shimmerPaint.alpha = (shrinkOpacity * 255).toInt()
234
+ canvas.save()
235
+ canvas.scale(scale, scale, w / 2f, h / 2f)
236
+ }
237
+
238
+ // Collapse: vertically then horizontally, with opacity fade
239
+ if (isTransitioning && transitionType == TransitionType.COLLAPSE) {
240
+ val p = transitionProgress
241
+ val scaleY = if (p < 0.6f) 1f - (p / 0.6f) * 0.98f else 0.02f
242
+ val scaleX = if (p < 0.6f) 1f else 1f - ((p - 0.6f) / 0.4f)
243
+ val collapseOpacity = (1f - p * 2.5f).coerceAtLeast(0f)
244
+ shimmerPaint.alpha = (collapseOpacity * 255).toInt()
245
+ canvas.save()
246
+ canvas.scale(scaleX, scaleY, w / 2f, h / 2f)
247
+ }
248
+
249
+ if (cornerRadius > 0f) {
250
+ val r = PixelUtil.toPixelFromDIP(cornerRadius)
251
+ val count = canvas.save()
252
+ clipPath.reset()
253
+ clipRect.set(0f, 0f, w, h)
254
+ clipPath.addRoundRect(clipRect, r, r, Path.Direction.CW)
255
+ canvas.clipPath(clipPath)
256
+ canvas.drawRect(0f, 0f, w, h, shimmerPaint)
257
+ canvas.restoreToCount(count)
258
+ } else {
259
+ canvas.drawRect(0f, 0f, w, h, shimmerPaint)
260
+ }
261
+
262
+ // Restore scale/CRT transform
263
+ if (isTransitioning && (transitionType == TransitionType.SHRINK || transitionType == TransitionType.COLLAPSE)) {
264
+ canvas.restore()
265
+ }
266
+ }
267
+ }
268
+
269
+ private fun blendColor(from: Int, to: Int, ratio: Float): Int {
270
+ val r = Color.red(from) + ((Color.red(to) - Color.red(from)) * ratio).toInt()
271
+ val g = Color.green(from) + ((Color.green(to) - Color.green(from)) * ratio).toInt()
272
+ val b = Color.blue(from) + ((Color.blue(to) - Color.blue(from)) * ratio).toInt()
273
+ val a = Color.alpha(from) + ((Color.alpha(to) - Color.alpha(from)) * ratio).toInt()
274
+ return Color.argb(a, r, g, b)
275
+ }
276
+
277
+ private fun applyLoadingState(wasLoading: Boolean) {
278
+ if (loading) {
279
+ transitionAnimator?.cancel()
280
+ transitionAnimator = null
281
+ isTransitioning = false
282
+ contentOpacity = 0f
283
+ shimmerOpacity = 1f
284
+ registerClock()
285
+ invalidate()
286
+ } else {
287
+ if (wasLoading && transitionDuration > 0f) {
288
+ isTransitioning = true
289
+ transitionAnimator?.cancel()
290
+
291
+ transitionAnimator = ValueAnimator.ofFloat(0f, 1f).apply {
292
+ duration = transitionDuration.toLong()
293
+ interpolator = DecelerateInterpolator()
294
+ addUpdateListener { anim ->
295
+ val p = anim.animatedValue as Float
296
+ transitionProgress = p
297
+ contentOpacity = p
298
+ shimmerOpacity = 1f - p
299
+ invalidate()
300
+ }
301
+ addListener(object : android.animation.AnimatorListenerAdapter() {
302
+ override fun onAnimationEnd(animation: android.animation.Animator) {
303
+ finishTransition()
304
+ }
305
+ })
306
+ start()
307
+ }
308
+ } else {
309
+ unregisterClock()
310
+ contentOpacity = 1f
311
+ shimmerOpacity = 0f
312
+ invalidate()
313
+ emitTransitionEnd(true)
314
+ }
315
+ }
316
+ }
317
+
318
+ private fun finishTransition() {
319
+ isTransitioning = false
320
+ unregisterClock()
321
+ contentOpacity = 1f
322
+ shimmerOpacity = 0f
323
+ invalidate()
324
+ emitTransitionEnd(true)
325
+ }
326
+
327
+ private fun emitTransitionEnd(finished: Boolean) {
328
+ val reactContext = context as? ReactContext ?: return
329
+ val dispatcher = UIManagerHelper.getEventDispatcherForReactTag(reactContext, id) ?: return
330
+ val surfaceId = UIManagerHelper.getSurfaceId(this)
331
+ dispatcher.dispatchEvent(TransitionEndEvent(surfaceId, id, finished))
332
+ }
333
+
334
+ class TransitionEndEvent(
335
+ surfaceId: Int,
336
+ viewId: Int,
337
+ private val finished: Boolean
338
+ ) : Event<TransitionEndEvent>(surfaceId, viewId) {
339
+ override fun getEventName() = "topTransitionEnd"
340
+ override fun getEventData(): WritableMap {
341
+ return Arguments.createMap().apply {
342
+ putBoolean("finished", finished)
343
+ }
344
+ }
345
+ }
346
+
347
+ /**
348
+ * Shared Choreographer-based clock that drives all GleamView instances.
349
+ * Views with the same speed/delay are automatically in sync because
350
+ * they compute progress from the same global timestamp.
351
+ */
352
+ companion object SharedClock {
353
+ private val views = mutableSetOf<GleamView>()
354
+ private var frameCallback: Choreographer.FrameCallback? = null
355
+
356
+ fun register(view: GleamView) {
357
+ views.add(view)
358
+ if (views.size == 1) start()
359
+ }
360
+
361
+ fun unregister(view: GleamView) {
362
+ views.remove(view)
363
+ if (views.isEmpty()) stop()
364
+ }
365
+
366
+ private fun start() {
367
+ frameCallback = Choreographer.FrameCallback { _ ->
368
+ views.toList().forEach { it.onFrame() }
369
+ frameCallback?.let { Choreographer.getInstance().postFrameCallback(it) }
370
+ }
371
+ Choreographer.getInstance().postFrameCallback(frameCallback!!)
372
+ }
373
+
374
+ private fun stop() {
375
+ frameCallback?.let { Choreographer.getInstance().removeFrameCallback(it) }
376
+ frameCallback = null
377
+ }
378
+ }
379
+ }