FazBrowse GitHub Viewer
|
Trending
|
URL:
|
Home
Tools:
[Download Repo ZIP]
[View Raw Code]
[Original HTTPS Page]
pythonnative/src/pythonnative/animated.py at main · andevsr/pythonnative · GitHub
andevsr
pythonnative
Repository navigation
Code
Pull requests
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
1669 lines (1367 loc) · 59 KB
Breadcrumbs
pythonnative
/
src
/
pythonnative
/
animated.py
Copy path
File metadata and controls
1669 lines (1367 loc) · 59 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.
- ``Animated.sequence`` / ``Animated.parallel`` / ``Animated.stagger``
/ ``Animated.delay`` / ``Animated.loop``: composition; also
awaitable.
- ``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**):
When an animation starts, PythonNative compiles its spec (curve,
duration, target value) and offers it to the platform handler of every
native view the value is attached to
([`ViewHandler.start_animation`][pythonnative.native_views.base.ViewHandler.start_animation]).
- **Accepted** (iOS Core Animation, Android ``ViewPropertyAnimator`` /
``DynamicAnimation``): the platform animates the property entirely
natively; no Python code runs per frame. Python receives exactly one
callback when the animation settles, updates the
[`AnimatedValue`][pythonnative.animated.AnimatedValue], and resolves
any awaiting tasks.
- **Declined** (desktop preview, unattached values, callable easings,
values feeding Python-side listeners or derived nodes): 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.
Values driven by *events* (scroll offsets via ``Animated.event``,
gesture translations) flow through Python: the native listener fires,
the bound values update, and every attachment (including derived
nodes) is pushed in the same call.
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
itertools
import
math
import
threading
import
time
import
weakref
from
typing
import
Any
,
Callable
,
Dict
,
List
,
Optional
,
Sequence
,
Tuple
from
.
element
import
Element
from
.
hooks
import
use_effect
,
use_ref
from
.
runtime
import
resolve_future
from
.
style
import
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
_EASINGS
:
Dict
[
str
,
Callable
[[
float
],
float
]]
=
{
"linear"
:
lambda
t
:
t
,
"ease_in"
:
lambda
t
:
t
*
t
,
"ease_out"
:
lambda
t
:
1.0
-
(
1.0
-
t
)
*
(
1.0
-
t
),
"ease_in_out"
:
lambda
t
:
3.0
*
t
*
t
-
2.0
*
t
*
t
*
t
,
"ease_in_quad"
:
lambda
t
:
t
*
t
,
"ease_out_quad"
:
lambda
t
:
1.0
-
(
1.0
-
t
)
*
(
1.0
-
t
),
"bounce"
:
lambda
t
: (
# Robert Penner's bounce out, common easing.
7.5625
*
t
*
t
if
t
<
1
/
2.75
else
(
7.5625
*
(
t
-
1.5
/
2.75
)
*
(
t
-
1.5
/
2.75
)
+
0.75
if
t
<
2
/
2.75
else
(
7.5625
*
(
t
-
2.25
/
2.75
)
*
(
t
-
2.25
/
2.75
)
+
0.9375
if
t
<
2.5
/
2.75
else
7.5625
*
(
t
-
2.625
/
2.75
)
*
(
t
-
2.625
/
2.75
)
+
0.984375
)
)
),
}
def
_resolve_easing
(
name
:
Any
)
->
Callable
[[
float
],
float
]:
if
callable
(
name
):
return
name
return
_EASINGS
.
get
(
str
(
name
),
_EASINGS
[
"ease_in_out"
])
def
_backend
()
->
Any
:
"""Return the active native-view registry (the animation backend)."""
from
.
native_views
import
get_registry
return
get_registry
()
# 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
)
->
None
:
"""Push the current output to attachments/listeners and descend."""
self
.
_refresh
()
current
=
self
.
value
with
self
.
_lock
:
subs
=
list
(
self
.
_subscribers
)
attachments
=
list
(
self
.
_attachments
)
children
=
list
(
self
.
_children
)
if
attachments
:
try
:
backend
=
_backend
()
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
()
# -- 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
)
try
:
_backend
().
set_animated_property
(
tag
,
prop
,
self
.
value
)
except
Exception
:
pass
def
_detach
()
->
None
:
with
self
.
_lock
:
try
:
self
.
_attachments
.
remove
(
binding
)
except
ValueError
:
pass
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
)
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
:
try
:
backend
=
_backend
()
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
()
# -- 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
:
node
.
set_value
(
float
(
raw
))
except
(
TypeError
,
ValueError
):
continue
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
:
with
self
.
_lock
:
try
:
self
.
_animations
.
remove
(
anim
)
except
ValueError
:
pass
def
cancel_for_value
(
self
,
value
:
AnimatedValue
)
->
None
:
"""Cancel every queued/running Python-driven animation on ``value``."""
with
self
.
_lock
:
stale
=
[
a
for
a
in
self
.
_animations
if
a
.
value
is
value
]
for
anim
in
stale
:
self
.
_animations
.
remove
(
anim
)
for
anim
in
stale
:
anim
.
_finish
()
def
_ensure_thread_locked
(
self
)
->
None
:
if
self
.
_thread
is
not
None
and
self
.
_thread
.
is_alive
():
return
self
.
_thread
=
threading
.
Thread
(
target
=
self
.
_loop
,
daemon
=
True
,
name
=
"pn-animated"
)
self
.
_thread
.
start
()
def
_loop
(
self
)
->
None
:
last
=
time
.
monotonic
()
# Clamping the per-tick dt is important for numerical stability:
# an underdamped spring with a 0.3 s step explodes immediately,
# and the animation thread can be starved for several frames
# during render bursts. We integrate physics on a clamped dt
# (max 2 target frames) and sub-step when wall-clock has
# advanced more than that, so the perceived motion still tracks
# real time at most a couple of frames behind. After an extreme
# starvation (e.g. the app was backgrounded for seconds) we cap
# the catch-up at ``_MAX_CATCHUP_FRAMES`` worth of physics; any
# further wall-clock drift is dropped on the floor, which keeps
# the loop responsive instead of spinning forward through
# hundreds of substeps.
max_step
=
_FRAME_DT
*
2.0
max_catchup
=
_FRAME_DT
*
_MAX_CATCHUP_FRAMES
while
not
self
.
_stopped
:
now
=
time
.
monotonic
()
dt
=
now
-
last
last
=
now
with
self
.
_lock
:
active
=
list
(
self
.
_animations
)
if
not
active
:
time
.
sleep
(
0.05
)
last
=
time
.
monotonic
()
continue
remaining
=
min
(
dt
,
max_catchup
)
while
remaining
>
0.0
:
step
=
remaining
if
remaining
<=
max_step
else
max_step
remaining
-=
step
for
anim
in
active
:
if
getattr
(
anim
,
"_completed"
,
False
):
continue
try
:
finished
=
anim
.
advance
(
step
)
except
Exception
:
finished
=
True
if
finished
:
self
.
remove
(
anim
)
time
.
sleep
(
_FRAME_DT
)
_manager
=
_AnimationManager
()
# ======================================================================
# Python-driven animation primitives (the fallback path)
# ======================================================================
class
_RunningAnimation
:
"""Base class for Python-ticked animations; ``advance()`` returns True when done."""
def
__init__
(
self
,
value
:
AnimatedValue
)
->
None
:
self
.
value
=
value
self
.
_completion_futures
:
List
[
asyncio
.
Future
[
None
]]
=
[]
self
.
_completed
=
False
def
add_completion_future
(
self
,
future
:
asyncio
.
Future
[
None
])
->
None
:
"""Register ``future`` to be resolved when the animation ends."""
self
.
_completion_futures
.
append
(
future
)
if
self
.
_completed
:
resolve_future
(
future
,
None
)
def
advance
(
self
,
dt
:
float
)
->
bool
:
raise
NotImplementedError
def
_finish
(
self
)
->
None
:
if
self
.
_completed
:
return
self
.
_completed
=
True
for
fut
in
self
.
_completion_futures
:
resolve_future
(
fut
,
None
)
class
_TimingAnimation
(
_RunningAnimation
):
def
__init__
(
self
,
value
:
AnimatedValue
,
to
:
float
,
duration
:
float
,
easing
:
Callable
[[
float
],
float
],
)
->
None
:
super
().
__init__
(
value
)
self
.
_from
=
value
.
value
self
.
_to
=
float
(
to
)
self
.
_duration
=
max
(
0.001
,
float
(
duration
)
/
1000.0
)
self
.
_easing
=
easing
self
.
_elapsed
=
0.0
def
advance
(
self
,
dt
:
float
)
->
bool
:
self
.
_elapsed
+=
dt
progress
=
min
(
1.0
,
self
.
_elapsed
/
self
.
_duration
)
eased
=
self
.
_easing
(
progress
)
new_val
=
self
.
_from
+
(
self
.
_to
-
self
.
_from
)
*
eased
self
.
value
.
set_value
(
new_val
)
if
progress
>=
1.0
:
self
.
_finish
()
return
True
return
False
class
_SpringAnimation
(
_RunningAnimation
):
"""Damped harmonic spring driver."""
def
__init__
(
self
,
value
:
AnimatedValue
,
to
:
float
,
stiffness
:
float
,
damping
:
float
,
mass
:
float
,
initial_velocity
:
float
=
0.0
,
)
->
None
:
super
().
__init__
(
value
)
self
.
_to
=
float
(
to
)
self
.
_velocity
=
float
(
initial_velocity
)
self
.
_stiffness
=
float
(
stiffness
)
self
.
_damping
=
float
(
damping
)
self
.
_mass
=
float
(
mass
)
self
.
_rest_threshold
=
0.001
def
advance
(
self
,
dt
:
float
)
->
bool
:
x
=
self
.
value
.
value
a
=
(
-
self
.
_stiffness
*
(
x
-
self
.
_to
)
-
self
.
_damping
*
self
.
_velocity
)
/
self
.
_mass
self
.
_velocity
+=
a
*
dt
new_x
=
x
+
self
.
_velocity
*
dt
self
.
value
.
set_value
(
new_x
)
if
abs
(
new_x
-
self
.
_to
)
<
self
.
_rest_threshold
and
abs
(
self
.
_velocity
)
<
self
.
_rest_threshold
:
self
.
value
.
set_value
(
self
.
_to
)
self
.
_finish
()
return
True
return
False
class
_DecayAnimation
(
_RunningAnimation
):
def
__init__
(
self
,
value
:
AnimatedValue
,
velocity
:
float
,
deceleration
:
float
)
->
None
:
super
().
__init__
(
value
)
self
.
_velocity
=
float
(
velocity
)
self
.
_deceleration
=
float
(
deceleration
)
self
.
_rest_threshold
=
0.001
def
advance
(
self
,
dt
:
float
)
->
bool
:
self
.
_velocity
*=
math
.
exp
(
-
self
.
_deceleration
*
dt
*
1000.0
)
new_x
=
self
.
value
.
value
+
self
.
_velocity
*
dt
self
.
value
.
set_value
(
new_x
)
if
abs
(
self
.
_velocity
)
<
self
.
_rest_threshold
:
self
.
_finish
()
return
True
return
False
class
_DelayAnimation
(
_RunningAnimation
):
def
__init__
(
self
,
duration_ms
:
float
)
->
None
:
super
().
__init__
(
AnimatedValue
(
0.0
))
self
.
_elapsed
=
0.0
self
.
_duration
=
max
(
0.001
,
duration_ms
/
1000.0
)
def
advance
(
self
,
dt
:
float
)
->
bool
:
self
.
_elapsed
+=
dt
if
self
.
_elapsed
>=
self
.
_duration
:
self
.
_finish
()
return
True
return
False
# ======================================================================
# Native-driven animation group
# ======================================================================
class
_NativeAnimationGroup
:
"""One logical animation fanned out to N natively-animated views.
Each attached ``(tag, prop)`` binding gets its own ``anim_id``; the
group completes when the platform reports completion for all of
them. Cancellation asks each platform handler for the current
presentation value so the ``AnimatedValue`` lands wherever the view
visually was.
"""
def
__init__
(
self
,
value
:
AnimatedValue
,
final_value
:
float
)
->
None
:
self
.
value
=
value
self
.
final_value
=
final_value
self
.
_targets
:
Dict
[
int
,
Tuple
[
int
,
str
]]
=
{}
# anim_id -> (tag, prop)
self
.
_pending
:
set
=
set
()
self
.
_completion_futures
:
List
[
asyncio
.
Future
[
None
]]
=
[]
self
.
_completed
=
False
self
.
_lock
=
threading
.
Lock
()
def
add_target
(
self
,
anim_id
:
int
,
tag
:
int
,
prop
:
str
)
->
None
:
with
self
.
_lock
:
self
.
_targets
[
anim_id
]
=
(
tag
,
prop
)
self
.
_pending
.
add
(
anim_id
)
_native_groups
[
anim_id
]
=
self
def
add_completion_future
(
self
,
future
:
asyncio
.
Future
[
None
])
->
None
:
with
self
.
_lock
:
done
=
self
.
_completed
if
not
done
:
self
.
_completion_futures
.
append
(
future
)
if
done
:
resolve_future
(
future
,
None
)
def
target_completed
(
self
,
anim_id
:
int
,
finished
:
bool
)
->
None
:
with
self
.
_lock
:
self
.
_pending
.
discard
(
anim_id
)
remaining
=
len
(
self
.
_pending
)
_native_groups
.
pop
(
anim_id
,
None
)
if
remaining
==
0
:
self
.
_settle
(
self
.
final_value
if
finished
else
None
)
def
cancel
(
self
)
->
None
:
"""Cancel all in-flight native animations, syncing to presentation values."""
with
self
.
_lock
:
targets
=
dict
(
self
.
_targets
)
self
.
_pending
.
clear
()
presentation
:
Optional
[
float
]
=
None
try
:
backend
=
_backend
()
for
anim_id
, (
tag
,
_prop
)
in
targets
.
items
():
_native_groups
.
pop
(
anim_id
,
None
)
current
=
backend
.
cancel_animation
(
tag
,
anim_id
)
if
current
is
not
None
:
try
:
presentation
=
float
(
current
)
except
(
TypeError
,
ValueError
):
pass
except
Exception
:
pass
self
.
_settle
(
presentation
)
def
_settle
(
self
,
end_value
:
Optional
[
float
])
->
None
:
with
self
.
_lock
:
if
self
.
_completed
:
return
self
.
_completed
=
True
futures
=
list
(
self
.
_completion_futures
)
self
.
_completion_futures
.
clear
()
if
self
.
value
.
_native_group
is
self
:
self
.
value
.
_native_group
=
None
if
end_value
is
not
None
:
# The native side already shows this value; update the
# Python cell (and listeners) without re-pushing.
self
.
value
.
_apply
(
end_value
,
push_native
=
False
)
for
fut
in
futures
:
resolve_future
(
fut
,
None
)
View remainder of file in raw view
Back
|
FazBrowse Home
|
New Git URL