FazBrowse GitHub Viewer
|
Trending
|
URL:
|
Home
Tools:
[Download Repo ZIP]
[View Raw Code]
[Original HTTPS Page]
pythonnative/src/pythonnative/animated.py at refs/heads/main · pythonnative/pythonnative · GitHub
pythonnative
pythonnative
Repository navigation
Code
Issues
11
(11)
Pull requests
4
(4)
Actions
Projects
Security and quality
Insights
Expand file tree
Breadcrumbs
pythonnative
/
src
/
pythonnative
/
animated.py
Copy path
More file actions
More file actions
Latest commit
History
History
History
2204 lines (1810 loc) · 81.3 KB
Breadcrumbs
pythonnative
/
src
/
pythonnative
/
animated.py
Copy path
File metadata and controls
2204 lines (1810 loc) · 81.3 KB
Raw
Copy raw file
Download raw file
Open symbols panel
Edit and raw actions
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
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
"""Animated values, derived animated nodes, and native-driven animation.
Modeled on React Native's ``Animated`` API with an ``async``-aware
completion contract. The core primitives are:
- [`AnimatedValue`][pythonnative.animated.AnimatedValue]: a numeric
cell attached to native view properties; animations drive it over
time.
- **Derived nodes**: every animated node supports
[`interpolate`][pythonnative.animated.AnimatedNode.interpolate]
(range mapping with numeric, color, and angle outputs) and Python
arithmetic (``opacity * 0.5``, ``x + y``, ``-value``), producing
read-only [`AnimatedNode`][pythonnative.animated.AnimatedNode]
instances that update whenever their inputs change.
- ``Animated.timing`` / ``Animated.spring`` / ``Animated.decay``:
animation factories. The objects they return implement
``__await__``, so you can write ``await Animated.timing(v, to=1.0)``
to suspend until the animation finishes. Awaiting yields an
[`AnimationResult`][pythonnative.animated.AnimationResult] whose
``finished`` flag is ``False`` when the animation was stopped or
interrupted; ``handle.start(callback)`` passes the same value.
- ``Animated.sequence`` / ``Animated.parallel`` / ``Animated.stagger``
/ ``Animated.delay`` / ``Animated.loop``: composition; also
awaitable. A composite is ``finished`` only if every child finished.
- [`Easing`][pythonnative.animated.Easing]: serializable easing
descriptors for ``Animated.timing`` (``Easing.ease_in_out``,
``Easing.bezier(0.2, 0.8, 0.2, 1.0)``, ...). Every renderer evaluates
the same curve definitions; a plain Python callable is still accepted
but ticks in Python.
- ``Animated.event``: build an event-prop callback that copies event
fields into animated values (``on_scroll=pn.Animated.event(y=v)``).
- ``Animated.diff_clamp``: accumulate an input's *deltas* into a
clamped range (the collapsing-header primitive).
- ``Animated.View`` / ``Animated.Text`` / ``Animated.Image``:
components whose ``style`` may contain animated nodes, including
inside ``transform`` entries.
Driver architecture (the **native driver**):
Mounted bindings install a serialized graph of connected values, arithmetic,
interpolation, and view properties. When an animation starts, PythonNative
offers its timing, spring, or decay specification to the renderer through
the backend's ``start_animation`` hook (see
[`BridgeBackend`][pythonnative.native_views.bridge_backend.BridgeBackend]).
- **Accepted**: the renderer evaluates the graph and applies its bindings
without Python work on every frame. Completion callbacks settle the
[`AnimatedValue`][pythonnative.animated.AnimatedValue] and resolve
awaiting tasks.
- **Declined** (unattached values, callable easings,
values feeding Python-side listeners, or an unsupported backend): a single
background thread ticks the animation at ~60 Hz from Python, pushing
each frame through ``set_animated_property``. Semantics are
identical; only the frame source differs.
On mobile, scroll and gesture bindings feed graph values before input is
queued to Python. Derived expressions can run in the renderer alongside their
source drivers. Backends without graph support use Python for derived bindings.
Example:
```python
import pythonnative as pn
@pn.component
def FadeIn():
opacity = pn.use_animated_value(0.0)
async def fade_in():
await pn.Animated.timing(opacity, to=1.0, duration=400)
await pn.Animated.timing(opacity, to=0.5, duration=200)
pn.use_effect(fade_in, [])
return pn.Animated.View(
pn.Text("Hello!"),
style={"opacity": opacity, "padding": 20},
)
```
"""
from
__future__
import
annotations
import
asyncio
import
bisect
import
functools
import
itertools
import
math
import
threading
import
time
import
weakref
from
dataclasses
import
dataclass
from
typing
import
Any
,
Callable
,
Dict
,
FrozenSet
,
Generator
,
List
,
Mapping
,
Optional
,
Sequence
,
Tuple
,
Union
,
cast
from
.
element
import
Element
from
.
hooks
import
Ref
,
use_effect
,
use_ref
from
.
runtime
import
resolve_future
from
.
style
import
Style
,
StyleProp
,
resolve_style
# Maximum frame rate at which the Python fallback ticker drives
# animations (native-driven animations run at the display's refresh
# rate, managed by the platform).
_TARGET_FPS
=
60.0
_FRAME_DT
=
1.0
/
_TARGET_FPS
# Upper bound on how much wall-clock time the fallback loop will try to
# catch up on in a single iteration after thread starvation. At 60 fps
# this is ~333 ms of simulated motion; further drift is dropped to keep
# the loop responsive.
_MAX_CATCHUP_FRAMES
=
20
# Velocity (points per millisecond) below which a decay animation is at
# rest. React Native's ``DecayAnimation`` stops when a frame moves the
# value by less than 0.1 points; at 60 Hz that is about 0.006 pt/ms. We
# use the tighter 0.001 pt/ms so the tail of a fling is never clipped
# visibly, and every native decay driver shares this constant.
DECAY_REST_VELOCITY
=
0.001
# React Native's default ``deceleration`` for ``Animated.decay``.
DEFAULT_DECAY_DECELERATION
=
0.998
# ======================================================================
# Easing
# ======================================================================
_BEZIER_EPSILON
=
1e-7
_BEZIER_NEWTON_ITERATIONS
=
8
_BEZIER_BISECTION_ITERATIONS
=
40
def
_bezier_component
(
t
:
float
,
p1
:
float
,
p2
:
float
)
->
float
:
"""Evaluate one axis of a cubic bezier anchored at ``0`` and ``1``."""
inv
=
1.0
-
t
return
3.0
*
inv
*
inv
*
t
*
p1
+
3.0
*
inv
*
t
*
t
*
p2
+
t
*
t
*
t
def
_bezier_slope
(
t
:
float
,
p1
:
float
,
p2
:
float
)
->
float
:
"""Derivative of ``_bezier_component`` with respect to ``t``."""
inv
=
1.0
-
t
return
3.0
*
inv
*
inv
*
p1
+
6.0
*
inv
*
t
*
(
p2
-
p1
)
+
3.0
*
t
*
t
*
(
1.0
-
p2
)
@
functools
.
lru_cache
(
maxsize
=
64
)
def
_bezier_function
(
x1
:
float
,
y1
:
float
,
x2
:
float
,
y2
:
float
)
->
Callable
[[
float
],
float
]:
"""Build a ``progress -> eased`` function for a CSS-style cubic bezier.
The curve is parametric, so evaluating it at a given horizontal
``progress`` means solving ``bezier_x(t) = progress`` for ``t`` first.
Newton-Raphson from a linear guess converges in a handful of steps
for well-behaved curves; when the slope is too flat for Newton to be
trusted, bisection on ``[0, 1]`` finishes the job.
"""
if
x1
==
y1
and
x2
==
y2
:
return
lambda
progress
:
min
(
1.0
,
max
(
0.0
,
progress
))
def
solve_t
(
x
:
float
)
->
float
:
t
=
x
for
_
in
range
(
_BEZIER_NEWTON_ITERATIONS
):
error
=
_bezier_component
(
t
,
x1
,
x2
)
-
x
if
abs
(
error
)
<
_BEZIER_EPSILON
:
return
t
slope
=
_bezier_slope
(
t
,
x1
,
x2
)
if
abs
(
slope
)
<
1e-6
:
break
t
-=
error
/
slope
lo
,
hi
=
0.0
,
1.0
for
_
in
range
(
_BEZIER_BISECTION_ITERATIONS
):
t
=
(
lo
+
hi
)
/
2.0
if
_bezier_component
(
t
,
x1
,
x2
)
<
x
:
lo
=
t
else
:
hi
=
t
if
hi
-
lo
<
_BEZIER_EPSILON
:
break
return
t
def
evaluate
(
progress
:
float
)
->
float
:
if
progress
<=
0.0
:
return
0.0
if
progress
>=
1.0
:
return
1.0
return
_bezier_component
(
solve_t
(
progress
),
y1
,
y2
)
return
evaluate
def
_bounce
(
t
:
float
)
->
float
:
"""Robert Penner's bounce-out, the curve React Native ships as ``Easing.bounce``."""
if
t
<
1
/
2.75
:
return
7.5625
*
t
*
t
if
t
<
2
/
2.75
:
t
-=
1.5
/
2.75
return
7.5625
*
t
*
t
+
0.75
if
t
<
2.5
/
2.75
:
t
-=
2.25
/
2.75
return
7.5625
*
t
*
t
+
0.9375
t
-=
2.625
/
2.75
return
7.5625
*
t
*
t
+
0.984375
# Canonical definitions of the named easings. Every renderer (the Python
# ticker, Swift, Kotlin, and the browser preview) implements exactly these
# curves under these names; they follow React Native's ``Easing`` module,
# where ``ease`` is ``bezier(0.42, 0, 1, 1)`` and ``ease_in`` /
# ``ease_out`` / ``ease_in_out`` are ``Easing.in`` / ``out`` / ``inOut``
# of it, which coincide with the CSS ``ease-in`` / ``ease-out`` /
# ``ease-in-out`` keywords.
_NAMED_EASING_BEZIERS
:
Dict
[
str
,
Tuple
[
float
,
float
,
float
,
float
]]
=
{
"ease"
: (
0.42
,
0.0
,
1.0
,
1.0
),
"ease_in"
: (
0.42
,
0.0
,
1.0
,
1.0
),
"ease_out"
: (
0.0
,
0.0
,
0.58
,
1.0
),
"ease_in_out"
: (
0.42
,
0.0
,
0.58
,
1.0
),
}
_NAMED_EASING_FUNCTIONS
:
Dict
[
str
,
Callable
[[
float
],
float
]]
=
{
"linear"
:
lambda
t
:
t
,
"ease"
:
_bezier_function
(
*
_NAMED_EASING_BEZIERS
[
"ease"
]),
"ease_in"
:
_bezier_function
(
*
_NAMED_EASING_BEZIERS
[
"ease_in"
]),
"ease_out"
:
_bezier_function
(
*
_NAMED_EASING_BEZIERS
[
"ease_out"
]),
"ease_in_out"
:
_bezier_function
(
*
_NAMED_EASING_BEZIERS
[
"ease_in_out"
]),
"quad"
:
lambda
t
:
t
*
t
,
"cubic"
:
lambda
t
:
t
*
t
*
t
,
"bounce"
:
_bounce
,
}
EASING_NAMES
:
Tuple
[
str
, ...]
=
tuple
(
_NAMED_EASING_FUNCTIONS
)
"""The easing names ``Animated.timing`` accepts as strings."""
@
dataclass
(
frozen
=
True
)
class
EasingSpec
:
"""A serializable easing curve for ``Animated.timing``.
Build instances through the [`Easing`][pythonnative.animated.Easing]
namespace (``Easing.ease_in_out``, ``Easing.bezier(...)``) rather
than directly. The descriptor crosses the bridge as data, so the
native drivers can run the curve on the UI thread, and it evaluates
identically in Python for the fallback ticker and for tests.
Attributes:
name: One of the named curves (``"linear"``, ``"ease"``,
``"ease_in"``, ``"ease_out"``, ``"ease_in_out"``,
``"quad"``, ``"cubic"``, ``"bounce"``) or ``"bezier"``.
points: The ``(x1, y1, x2, y2)`` control points when ``name`` is
``"bezier"``; ``None`` otherwise.
"""
name
:
str
points
:
Optional
[
Tuple
[
float
,
float
,
float
,
float
]]
=
None
def
__post_init__
(
self
)
->
None
:
if
self
.
name
==
"bezier"
:
if
self
.
points
is
None
or
len
(
self
.
points
)
!=
4
:
raise
ValueError
(
"Easing.bezier() needs exactly four control-point coordinates"
)
x1
,
_y1
,
x2
,
_y2
=
self
.
points
if
not
(
0.0
<=
x1
<=
1.0
and
0.0
<=
x2
<=
1.0
):
raise
ValueError
(
"Easing.bezier() x control points must lie within [0, 1]"
)
elif
self
.
name
not
in
_NAMED_EASING_FUNCTIONS
:
raise
ValueError
(
f"Unknown easing
{
self
.
name
!r
}
; expected one of
{
', '
.
join
(
EASING_NAMES
)
}
or 'bezier'"
)
elif
self
.
points
is
not
None
:
raise
ValueError
(
f"Easing
{
self
.
name
!r
}
does not take control points"
)
def
evaluate
(
self
,
progress
:
float
)
->
float
:
"""Return the eased value for ``progress`` in ``[0, 1]``."""
return
_easing_function
(
self
)(
progress
)
def
to_wire
(
self
)
->
Any
:
"""Return the bridge representation: the name, or ``[x1, y1, x2, y2]`` for a bezier."""
if
self
.
name
==
"bezier"
:
assert
self
.
points
is
not
None
return
[
float
(
p
)
for
p
in
self
.
points
]
return
self
.
name
def
__repr__
(
self
)
->
str
:
if
self
.
name
==
"bezier"
:
return
f"Easing.bezier
{
self
.
points
}
"
return
f"Easing.
{
self
.
name
}
"
class
_EasingNamespace
:
"""Public ``Easing`` namespace: named curves plus ``bezier(...)``.
Mirrors React Native's ``Easing`` module. Each attribute is a frozen
[`EasingSpec`][pythonnative.animated.EasingSpec]:
| Name | Curve |
| --- | --- |
| ``linear`` | ``t`` |
| ``ease`` | ``bezier(0.42, 0, 1, 1)`` |
| ``ease_in`` | ``bezier(0.42, 0, 1, 1)`` (CSS ``ease-in``) |
| ``ease_out`` | ``bezier(0, 0, 0.58, 1)`` (CSS ``ease-out``) |
| ``ease_in_out`` | ``bezier(0.42, 0, 0.58, 1)`` (CSS ``ease-in-out``) |
| ``quad`` | ``t * t`` |
| ``cubic`` | ``t * t * t`` |
| ``bounce`` | Penner bounce-out |
``Animated.timing(easing=...)`` also accepts these names as plain
strings; any other string raises ``ValueError``.
Example:
```python
pn.Animated.timing(opacity, to=1.0, easing=pn.Easing.ease_out)
pn.Animated.timing(x, to=200, easing=pn.Easing.bezier(0.2, 0.8, 0.2, 1.0))
```
"""
linear
=
EasingSpec
(
"linear"
)
ease
=
EasingSpec
(
"ease"
)
ease_in
=
EasingSpec
(
"ease_in"
)
ease_out
=
EasingSpec
(
"ease_out"
)
ease_in_out
=
EasingSpec
(
"ease_in_out"
)
quad
=
EasingSpec
(
"quad"
)
cubic
=
EasingSpec
(
"cubic"
)
bounce
=
EasingSpec
(
"bounce"
)
@
staticmethod
def
bezier
(
x1
:
float
,
y1
:
float
,
x2
:
float
,
y2
:
float
)
->
EasingSpec
:
"""Return a cubic-bezier easing with the CSS ``cubic-bezier(x1, y1, x2, y2)`` control points.
``x1`` and ``x2`` must lie in ``[0, 1]``; ``y1`` and ``y2`` may
overshoot for anticipation or bounce effects.
"""
return
EasingSpec
(
"bezier"
, (
float
(
x1
),
float
(
y1
),
float
(
x2
),
float
(
y2
)))
Easing
=
_EasingNamespace
()
EasingLike
=
Union
[
EasingSpec
,
str
,
Callable
[[
float
],
float
]]
"""What ``Animated.timing(easing=...)`` accepts."""
def
_resolve_easing
(
easing
:
Any
)
->
Union
[
EasingSpec
,
Callable
[[
float
],
float
]]:
"""Normalize an ``easing`` argument to an ``EasingSpec`` or a Python callable.
Raises:
ValueError: For a string that is not one of ``EASING_NAMES``.
TypeError: For anything that is not a spec, a name, or a callable.
"""
if
isinstance
(
easing
,
EasingSpec
):
return
easing
if
isinstance
(
easing
,
str
):
if
easing
in
_NAMED_EASING_FUNCTIONS
:
return
EasingSpec
(
easing
)
raise
ValueError
(
f"Unknown easing
{
easing
!r
}
; expected one of
{
', '
.
join
(
EASING_NAMES
)
}
, "
"an Easing.* descriptor, or a callable"
)
if
callable
(
easing
):
return
easing
raise
TypeError
(
f"easing must be an Easing descriptor, a name, or a callable (got
{
type
(
easing
).
__name__
}
)"
)
def
_easing_function
(
easing
:
Union
[
EasingSpec
,
Callable
[[
float
],
float
]])
->
Callable
[[
float
],
float
]:
"""Return the ``progress -> eased`` callable for a resolved easing."""
if
isinstance
(
easing
,
EasingSpec
):
if
easing
.
name
==
"bezier"
:
assert
easing
.
points
is
not
None
return
_bezier_function
(
*
easing
.
points
)
return
_NAMED_EASING_FUNCTIONS
[
easing
.
name
]
return
easing
def
_backend
()
->
Any
:
"""Return the active view backend (the animation backend), or ``None`` off device.
Headless code that never installed a backend (plain ``AnimatedValue``
arithmetic in a unit test) still works: every caller treats ``None``
as "no renderer to push to."
"""
from
.
native_views
import
get_backend
try
:
return
get_backend
()
except
Exception
:
return
None
# Process-unique ids for native animations, so completion callbacks can
# be routed without holding references on the native side.
_anim_id_counter
=
itertools
.
count
(
1
)
# ======================================================================
# AnimatedNode: the shared graph-node base
# ======================================================================
class
AnimatedNode
:
"""Base class for every animated node (settable leaves and derived nodes).
An animated node holds a current output value and a set of
``(tag, prop)`` **attachments** binding it to native view
properties. Whenever the node's output changes (a leaf was set or
animated, or an input of a derived node changed), the new value is
pushed to every attachment through the registry's
``set_animated_property`` and to every Python-side listener, then
propagated to derived nodes built from this one.
Derived nodes are constructed with
[`interpolate`][pythonnative.animated.AnimatedNode.interpolate],
with Python arithmetic operators (``+``, ``-``, ``*``, ``/``,
``%``, unary ``-``), or with ``Animated.diff_clamp``. They are
read-only: only [`AnimatedValue`][pythonnative.AnimatedValue]
leaves can be set or animated directly.
"""
__slots__
=
(
"_subscribers"
,
"_attachments"
,
"_lock"
,
"_children"
,
"__weakref__"
)
def
__init__
(
self
)
->
None
:
self
.
_subscribers
:
List
[
Tuple
[
str
,
Callable
[[
Any
],
None
]]]
=
[]
self
.
_attachments
:
List
[
Tuple
[
int
,
str
]]
=
[]
self
.
_lock
=
threading
.
Lock
()
# Derived nodes built from this one. Weak so a discarded
# interpolation doesn't keep receiving pushes forever.
self
.
_children
:
"weakref.WeakSet[AnimatedNode]"
=
weakref
.
WeakSet
()
# -- value -----------------------------------------------------------
@
property
def
value
(
self
)
->
Any
:
"""Return the node's current output value."""
raise
NotImplementedError
def
__float__
(
self
)
->
float
:
try
:
return
float
(
self
.
value
)
except
(
TypeError
,
ValueError
):
return
0.0
# -- graph -----------------------------------------------------------
def
_adopt_child
(
self
,
child
:
"AnimatedNode"
)
->
None
:
with
self
.
_lock
:
self
.
_children
.
add
(
child
)
def
_has_dependents
(
self
)
->
bool
:
"""Whether any derived node consumes this node's output."""
with
self
.
_lock
:
return
len
(
self
.
_children
)
>
0
def
_refresh
(
self
)
->
None
:
"""Hook for stateful derived nodes to update from their inputs."""
def
_propagate
(
self
,
push_native
:
bool
=
True
)
->
None
:
"""Push the current output to attachments/listeners and descend.
Args:
push_native: When ``False`` the renderer already shows this
frame (a native-evaluated graph sample), so only Python
state, listeners, and dependents are updated.
"""
self
.
_refresh
()
current
=
self
.
value
with
self
.
_lock
:
subs
=
list
(
self
.
_subscribers
)
attachments
=
list
(
self
.
_attachments
)
children
=
list
(
self
.
_children
)
if
push_native
and
attachments
:
backend
=
_backend
()
if
backend
is
not
None
:
try
:
for
tag
,
prop
in
attachments
:
backend
.
set_animated_property
(
tag
,
prop
,
current
)
except
Exception
:
pass
for
_prop
,
cb
in
subs
:
try
:
cb
(
current
)
except
Exception
:
pass
for
child
in
children
:
child
.
_propagate
(
push_native
)
# -- bindings ----------------------------------------------------------
def
attach
(
self
,
tag
:
int
,
prop
:
str
)
->
Callable
[[],
None
]:
"""Bind this node to ``prop`` of the native view under ``tag``.
The current value is pushed immediately so the view reflects it
even if no animation is running. Returns a detach callable.
"""
binding
=
(
tag
,
prop
)
with
self
.
_lock
:
self
.
_attachments
.
append
(
binding
)
backend
=
_backend
()
if
backend
is
not
None
:
try
:
backend
.
set_animated_property
(
tag
,
prop
,
self
.
value
)
except
Exception
:
pass
from
.
animation_graph
import
install
install
(
self
)
def
_detach
()
->
None
:
with
self
.
_lock
:
try
:
self
.
_attachments
.
remove
(
binding
)
except
ValueError
:
pass
install
(
self
,
detached_tag
=
tag
)
return
_detach
def
attachments
(
self
)
->
List
[
Tuple
[
int
,
str
]]:
"""Snapshot of the current ``(tag, prop)`` bindings."""
with
self
.
_lock
:
return
list
(
self
.
_attachments
)
# -- listeners ---------------------------------------------------------
def
add_listener
(
self
,
prop
:
str
,
callback
:
Callable
[[
Any
],
None
])
->
Callable
[[],
None
]:
"""Register ``callback`` for Python-driven changes to this node.
Returns an unsubscribe callable. ``prop`` is metadata only; it
lets the subscriber differentiate this binding from others on
the same node.
"""
with
self
.
_lock
:
self
.
_subscribers
.
append
((
prop
,
callback
))
def
_unsubscribe
()
->
None
:
with
self
.
_lock
:
try
:
self
.
_subscribers
.
remove
((
prop
,
callback
))
except
ValueError
:
pass
return
_unsubscribe
def
has_listeners
(
self
)
->
bool
:
"""Whether any Python-side listeners are registered."""
with
self
.
_lock
:
return
bool
(
self
.
_subscribers
)
# -- derivation --------------------------------------------------------
def
interpolate
(
self
,
input_range
:
Sequence
[
float
],
output_range
:
Sequence
[
Any
],
extrapolate
:
str
=
"extend"
,
extrapolate_left
:
Optional
[
str
]
=
None
,
extrapolate_right
:
Optional
[
str
]
=
None
,
)
->
"AnimatedInterpolation"
:
"""Map this node's value through an input/output range.
Mirrors React Native's ``interpolate``. ``output_range`` may
contain numbers, colors (``"#RRGGBB"`` / ``"#AARRGGBB"``), or
angle strings (``"45deg"`` / ``"0.5rad"``, emitted as numeric
degrees for the ``rotate`` transform).
Args:
input_range: Monotonically non-decreasing breakpoints for
this node's value. At least two entries.
output_range: Output breakpoints, same length as
``input_range``.
extrapolate: Behavior outside the input range:
``"extend"`` (continue the edge segment's slope,
default), ``"clamp"`` (pin to the edge output), or
``"identity"`` (return the input unchanged).
extrapolate_left: Override ``extrapolate`` below the range.
extrapolate_right: Override ``extrapolate`` above the range.
Returns:
A derived, read-only animated node.
Example:
```python
header_height = scroll_y.interpolate(
input_range=[0, 120],
output_range=[160, 56],
extrapolate="clamp",
)
```
"""
return
AnimatedInterpolation
(
self
,
input_range
,
output_range
,
extrapolate
=
extrapolate
,
extrapolate_left
=
extrapolate_left
,
extrapolate_right
=
extrapolate_right
,
)
# -- arithmetic --------------------------------------------------------
def
__add__
(
self
,
other
:
Any
)
->
"_AnimatedOperation"
:
return
_AnimatedOperation
(
"add"
,
lambda
a
,
b
:
a
+
b
, [
self
,
other
])
def
__radd__
(
self
,
other
:
Any
)
->
"_AnimatedOperation"
:
return
_AnimatedOperation
(
"add"
,
lambda
a
,
b
:
a
+
b
, [
other
,
self
])
def
__sub__
(
self
,
other
:
Any
)
->
"_AnimatedOperation"
:
return
_AnimatedOperation
(
"subtract"
,
lambda
a
,
b
:
a
-
b
, [
self
,
other
])
def
__rsub__
(
self
,
other
:
Any
)
->
"_AnimatedOperation"
:
return
_AnimatedOperation
(
"subtract"
,
lambda
a
,
b
:
a
-
b
, [
other
,
self
])
def
__mul__
(
self
,
other
:
Any
)
->
"_AnimatedOperation"
:
return
_AnimatedOperation
(
"multiply"
,
lambda
a
,
b
:
a
*
b
, [
self
,
other
])
def
__rmul__
(
self
,
other
:
Any
)
->
"_AnimatedOperation"
:
return
_AnimatedOperation
(
"multiply"
,
lambda
a
,
b
:
a
*
b
, [
other
,
self
])
def
__truediv__
(
self
,
other
:
Any
)
->
"_AnimatedOperation"
:
return
_AnimatedOperation
(
"divide"
,
lambda
a
,
b
:
a
/
b
if
b
else
0.0
, [
self
,
other
])
def
__rtruediv__
(
self
,
other
:
Any
)
->
"_AnimatedOperation"
:
return
_AnimatedOperation
(
"divide"
,
lambda
a
,
b
:
a
/
b
if
b
else
0.0
, [
other
,
self
])
def
__mod__
(
self
,
other
:
Any
)
->
"_AnimatedOperation"
:
return
_AnimatedOperation
(
"modulo"
,
lambda
a
,
b
:
math
.
fmod
(
a
,
b
)
if
b
else
0.0
, [
self
,
other
])
def
__neg__
(
self
)
->
"_AnimatedOperation"
:
return
_AnimatedOperation
(
"negate"
,
lambda
a
:
-
a
, [
self
])
# ======================================================================
# AnimatedValue: the settable leaf
# ======================================================================
class
AnimatedValue
(
AnimatedNode
):
"""A numeric cell that can be attached to native view properties.
Animated components (``Animated.View`` et al.) **attach** the value
to ``(tag, prop)`` bindings after mount. Setting the value pushes
the new number to every attached native view through the registry's
``set_animated_property`` (and through every derived node built
from this value), and when an animation can be driven natively, the
platform animates those same bindings directly.
Python-side listeners registered via
[`add_listener`][pythonnative.animated.AnimatedNode.add_listener]
observe every Python-driven change. Natively-driven animations
intentionally skip per-frame Python callbacks (that's the point);
listeners see the final settled value.
"""
__slots__
=
(
"_value"
,
"_native_group"
)
def
__init__
(
self
,
initial
:
float
=
0.0
)
->
None
:
super
().
__init__
()
self
.
_value
=
float
(
initial
)
# The in-flight native animation group driving this value, if any.
self
.
_native_group
:
Optional
[
"_NativeAnimationGroup"
]
=
None
@
property
def
value
(
self
)
->
float
:
"""Return the current numeric value (without subscribing)."""
return
self
.
_value
def
set_value
(
self
,
new_value
:
float
)
->
None
:
"""Set the value immediately, pushing to native views and listeners."""
self
.
_apply
(
float
(
new_value
),
push_native
=
True
)
from
.
animation_graph
import
install
graph
=
install
(
self
)
if
graph
and
graph
[
"bindings"
]:
backend
=
_backend
()
if
backend
is
not
None
:
backend
.
set_animated_property
(
graph
[
"bindings"
][
0
][
0
],
f"_pn_graph:
{
id
(
self
)
}
"
,
float
(
new_value
))
def
_apply
(
self
,
new_value
:
float
,
push_native
:
bool
)
->
None
:
with
self
.
_lock
:
self
.
_value
=
new_value
subs
=
list
(
self
.
_subscribers
)
attachments
=
list
(
self
.
_attachments
)
children
=
list
(
self
.
_children
)
if
push_native
and
attachments
:
backend
=
_backend
()
if
backend
is
not
None
:
try
:
for
tag
,
prop
in
attachments
:
backend
.
set_animated_property
(
tag
,
prop
,
new_value
)
except
Exception
:
pass
for
prop
,
cb
in
subs
:
try
:
cb
(
new_value
)
except
Exception
:
pass
for
child
in
children
:
child
.
_propagate
(
push_native
)
# -- native handoff ------------------------------------------------
def
_adopt_native_group
(
self
,
group
:
Optional
[
"_NativeAnimationGroup"
])
->
None
:
previous
=
self
.
_native_group
self
.
_native_group
=
group
if
previous
is
not
None
and
previous
is
not
group
:
previous
.
cancel
()
def
stop_animation
(
self
)
->
None
:
"""Cancel any in-flight animation on this value (native or Python)."""
self
.
_adopt_native_group
(
None
)
_manager
.
cancel_for_value
(
self
)
def
__repr__
(
self
)
->
str
:
return
f"AnimatedValue(
{
self
.
_value
:g
}
)"
# ======================================================================
# Derived nodes
# ======================================================================
def
_parse_color_output
(
value
:
str
)
->
Optional
[
Tuple
[
int
,
int
,
int
,
int
]]:
"""Parse ``"#RRGGBB"`` / ``"#AARRGGBB"`` into an ``(a, r, g, b)`` tuple."""
c
=
value
.
strip
().
lstrip
(
"#"
)
if
len
(
c
)
==
6
:
c
=
"FF"
+
c
if
len
(
c
)
!=
8
:
return
None
try
:
raw
=
int
(
c
,
16
)
except
ValueError
:
return
None
return
((
raw
>>
24
)
&
0xFF
, (
raw
>>
16
)
&
0xFF
, (
raw
>>
8
)
&
0xFF
,
raw
&
0xFF
)
def
_parse_angle_output
(
value
:
str
)
->
Optional
[
float
]:
"""Parse ``"45deg"`` / ``"0.5rad"`` into numeric degrees."""
text
=
value
.
strip
()
try
:
if
text
.
endswith
(
"deg"
):
return
float
(
text
[:
-
3
])
if
text
.
endswith
(
"rad"
):
return
math
.
degrees
(
float
(
text
[:
-
3
]))
except
ValueError
:
return
None
return
None
class
AnimatedInterpolation
(
AnimatedNode
):
"""Read-only node mapping a parent node through an input/output range.
Built via
[`AnimatedNode.interpolate`][pythonnative.animated.AnimatedNode.interpolate];
see that method for the semantics of the arguments.
"""
__slots__
=
(
"_parent"
,
"_inputs"
,
"_outputs"
,
"_kind"
,
"_left"
,
"_right"
,
)
def
__init__
(
self
,
parent
:
AnimatedNode
,
input_range
:
Sequence
[
float
],
output_range
:
Sequence
[
Any
],
extrapolate
:
str
=
"extend"
,
extrapolate_left
:
Optional
[
str
]
=
None
,
extrapolate_right
:
Optional
[
str
]
=
None
,
)
->
None
:
super
().
__init__
()
inputs
=
[
float
(
v
)
for
v
in
input_range
]
outputs
=
list
(
output_range
)
if
len
(
inputs
)
<
2
:
raise
ValueError
(
"interpolate() needs at least two input_range entries"
)
if
len
(
inputs
)
!=
len
(
outputs
):
raise
ValueError
(
"interpolate() input_range and output_range must have the same length"
)
for
a
,
b
in
zip
(
inputs
,
inputs
[
1
:]):
if
b
<
a
:
raise
ValueError
(
"interpolate() input_range must be monotonically non-decreasing"
)
kind
=
"number"
first
=
outputs
[
0
]
if
isinstance
(
first
,
str
):
if
_parse_color_output
(
first
)
is
not
None
:
kind
=
"color"
outputs
=
[
_parse_color_output
(
str
(
v
))
for
v
in
outputs
]
if
any
(
v
is
None
for
v
in
outputs
):
raise
ValueError
(
"interpolate() color output_range entries must all be colors"
)
else
:
angles
=
[
_parse_angle_output
(
str
(
v
))
for
v
in
outputs
]
if
any
(
v
is
None
for
v
in
angles
):
raise
ValueError
(
f"interpolate() cannot parse output value
{
first
!r
}
"
)
outputs
=
angles
else
:
outputs
=
[
float
(
v
)
for
v
in
outputs
]
self
.
_parent
=
parent
self
.
_inputs
=
inputs
self
.
_outputs
:
List
[
Any
]
=
outputs
self
.
_kind
=
kind
self
.
_left
=
extrapolate_left
or
extrapolate
self
.
_right
=
extrapolate_right
or
extrapolate
parent
.
_adopt_child
(
self
)
@
property
def
value
(
self
)
->
Any
:
"""Return the interpolated output for the parent's current value."""
return
self
.
_compute
(
float
(
self
.
_parent
))
def
_compute
(
self
,
x
:
float
)
->
Any
:
inputs
=
self
.
_inputs
n
=
len
(
inputs
)
if
x
<
inputs
[
0
]:
if
self
.
_left
==
"identity"
:
return
x
if
self
.
_left
==
"clamp"
:
x
=
inputs
[
0
]
i
=
0
elif
x
>
inputs
[
-
1
]:
if
self
.
_right
==
"identity"
:
return
x
if
self
.
_right
==
"clamp"
:
x
=
inputs
[
-
1
]
i
=
n
-
2
else
:
i
=
max
(
0
,
min
(
n
-
2
,
bisect
.
bisect_right
(
inputs
,
x
)
-
1
))
x0
,
x1
=
inputs
[
i
],
inputs
[
i
+
1
]
span
=
x1
-
x0
t
=
0.0
if
span
<=
0
else
(
x
-
x0
)
/
span
if
self
.
_kind
==
"color"
:
c0
=
self
.
_outputs
[
i
]
c1
=
self
.
_outputs
[
i
+
1
]
t_cl
=
max
(
0.0
,
min
(
1.0
,
t
))
channels
=
[
int
(
round
(
c0
[
j
]
+
(
c1
[
j
]
-
c0
[
j
])
*
t_cl
))
for
j
in
range
(
4
)]
a
,
r
,
g
,
b
=
(
max
(
0
,
min
(
255
,
ch
))
for
ch
in
channels
)
return
f"#
{
a
:02X
}
{
r
:02X
}
{
g
:02X
}
{
b
:02X
}
"
y0
=
self
.
_outputs
[
i
]
y1
=
self
.
_outputs
[
i
+
1
]
return
y0
+
(
y1
-
y0
)
*
t
def
__repr__
(
self
)
->
str
:
return
f"AnimatedInterpolation(
{
self
.
_inputs
}
->
{
self
.
_outputs
}
)"
class
_AnimatedOperation
(
AnimatedNode
):
"""Read-only node computed from other nodes (and constants) by ``fn``."""
__slots__
=
(
"_op"
,
"_fn"
,
"_parents"
)
def
__init__
(
self
,
op
:
str
,
fn
:
Callable
[...,
float
],
parents
:
List
[
Any
])
->
None
:
super
().
__init__
()
self
.
_op
=
op
self
.
_fn
=
fn
self
.
_parents
=
list
(
parents
)
for
parent
in
self
.
_parents
:
if
isinstance
(
parent
,
AnimatedNode
):
parent
.
_adopt_child
(
self
)
@
property
def
value
(
self
)
->
float
:
args
=
[
float
(
p
)
if
isinstance
(
p
,
AnimatedNode
)
else
float
(
p
)
for
p
in
self
.
_parents
]
try
:
return
float
(
self
.
_fn
(
*
args
))
except
Exception
:
return
0.0
def
__repr__
(
self
)
->
str
:
return
f"AnimatedOperation(
{
self
.
_op
}
)"
class
_AnimatedDiffClamp
(
AnimatedNode
):
"""Accumulate a parent's *deltas* into a clamped range.
Mirrors React Native's ``Animated.diffClamp``: the output moves by
the same amount as the input but is pinned to ``[min, max]``, so
scrolling far down then slightly up immediately re-reveals a
collapsing header regardless of absolute offset.
"""
__slots__
=
(
"_parent"
,
"_min"
,
"_max"
,
"_last_input"
,
"_current"
)
def
__init__
(
self
,
parent
:
AnimatedNode
,
min_value
:
float
,
max_value
:
float
)
->
None
:
super
().
__init__
()
if
max_value
<
min_value
:
raise
ValueError
(
"diff_clamp() requires min_value <= max_value"
)
self
.
_parent
=
parent
self
.
_min
=
float
(
min_value
)
self
.
_max
=
float
(
max_value
)
self
.
_last_input
=
float
(
parent
)
self
.
_current
=
max
(
self
.
_min
,
min
(
self
.
_max
,
self
.
_last_input
))
parent
.
_adopt_child
(
self
)
@
property
def
value
(
self
)
->
float
:
return
self
.
_current
def
_refresh
(
self
)
->
None
:
latest
=
float
(
self
.
_parent
)
delta
=
latest
-
self
.
_last_input
self
.
_last_input
=
latest
self
.
_current
=
max
(
self
.
_min
,
min
(
self
.
_max
,
self
.
_current
+
delta
))
# ======================================================================
# Animated.event
# ======================================================================
class
AnimatedEvent
:
"""Callable event handler copying event fields into animated values.
Built via ``pn.Animated.event(...)``. Each keyword argument names a
field on the incoming event payload (a dict key for scroll payloads
such as ``{"x": ..., "y": ...}``, or an attribute for
[`GestureEvent`][pythonnative.gestures.GestureEvent] instances) and
maps it onto an [`AnimatedValue`][pythonnative.AnimatedValue].
Because the result is an ordinary callable, it can be passed to any
event prop:
```python
scroll_y = pn.use_animated_value(0.0)
pn.ScrollView(..., on_scroll=pn.Animated.event(y=scroll_y))
tx = pn.use_animated_value(0.0)
gestures.Pan(on_change=pn.Animated.event(translation_x=tx))
```
"""
__slots__
=
(
"_bindings"
,
"_listener"
)
def
__init__
(
self
,
listener
:
Optional
[
Callable
[...,
None
]]
=
None
,
**
bindings
:
AnimatedValue
)
->
None
:
for
name
,
node
in
bindings
.
items
():
if
not
isinstance
(
node
,
AnimatedValue
):
raise
TypeError
(
f"Animated.event() field
{
name
!r
}
must map to an AnimatedValue "
f"(got
{
type
(
node
).
__name__
}
); derived nodes are read-only."
)
self
.
_bindings
=
dict
(
bindings
)
self
.
_listener
=
listener
def
__call__
(
self
,
payload
:
Any
=
None
,
*
args
:
Any
)
->
None
:
"""Write bound payload fields into their values, then run the listener.
Args:
payload: The event payload; a dict is read by key, any
other object by attribute. Missing or non-numeric
fields are skipped.
*args: Extra positional arguments forwarded to the
listener.
"""
for
name
,
node
in
self
.
_bindings
.
items
():
raw
:
Any
=
None
if
isinstance
(
payload
,
dict
):
raw
=
payload
.
get
(
name
)
elif
payload
is
not
None
:
raw
=
getattr
(
payload
,
name
,
None
)
if
raw
is
None
:
continue
try
:
sample
=
float
(
raw
)
except
(
TypeError
,
ValueError
):
continue
if
getattr
(
_backend
(),
"install_animation_graph"
,
None
)
is
not
None
:
# None backend: plain set
# The renderer evaluated the installed graph at the input
# timestamp, so this frame is already on screen. Update the
# Python cell, its listeners, and stateful dependents such
# as ``diff_clamp`` without echoing an older frame back.
node
.
_apply
(
sample
,
push_native
=
False
)
else
:
node
.
set_value
(
sample
)
if
self
.
_listener
is
not
None
:
try
:
self
.
_listener
(
payload
,
*
args
)
except
Exception
:
pass
# ======================================================================
# Python fallback driver
# ======================================================================
class
_AnimationManager
:
"""Single-threaded fallback driver for Python-ticked animations.
Holds a list of ``_RunningAnimation`` instances and ticks them at
~60 Hz. The thread starts on first use and idles when nothing is
active. Native-driven animations never touch this loop.
"""
def
__init__
(
self
)
->
None
:
self
.
_lock
=
threading
.
Lock
()
self
.
_animations
:
List
[
_RunningAnimation
]
=
[]
self
.
_thread
:
Optional
[
threading
.
Thread
]
=
None
self
.
_stopped
=
False
def
add
(
self
,
anim
:
"_RunningAnimation"
)
->
None
:
with
self
.
_lock
:
self
.
_animations
.
append
(
anim
)
self
.
_ensure_thread_locked
()
def
remove
(
self
,
anim
:
"_RunningAnimation"
)
->
None
:
View remainder of file in raw view
Back
|
FazBrowse Home
|
New Git URL