FazBrowse GitHub Viewer
|
Trending
|
URL:
|
Home
Tools:
[Download Repo ZIP]
[View Raw Code]
[Original HTTPS Page]
pythonnative/src/pythonnative/hooks.py at docs/fix-navigation-examples · crux200/pythonnative · GitHub
crux200
pythonnative
Repository navigation
Code
Pull requests
Actions
Projects
Security and quality
Insights
Expand file tree
Breadcrumbs
pythonnative
/
src
/
pythonnative
/
hooks.py
Copy path
More file actions
More file actions
Latest commit
History
History
History
1889 lines (1481 loc) · 63.9 KB
Breadcrumbs
pythonnative
/
src
/
pythonnative
/
hooks.py
Copy path
File metadata and controls
1889 lines (1481 loc) · 63.9 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
"""Hook primitives for function components.
Provides React-like hooks for managing state, effects, memoization,
context, and navigation within function components decorated with
[`component`][pythonnative.component]. Hooks must be called at the top
level of a component (not inside conditionals or loops) so they map to
the same slot across renders. In dev mode the framework verifies this
and raises [`HookOrderError`][pythonnative.diagnostics.HookOrderError]
on a violation instead of silently cross-wiring state.
Two effect phases exist, mirroring React:
- [`use_layout_effect`][pythonnative.use_layout_effect] callbacks run
synchronously inside the commit, after native mutations and the
layout pass have been applied. They can measure committed frames and
issue imperative view commands before the user sees the new frame.
- [`use_effect`][pythonnative.use_effect] callbacks (passive effects)
run after the layout effects, at the end of the same commit. An
effect may be an ``async def``; it runs as a task on the framework
loop and is cancelled when its dependencies change or the component
unmounts.
The current hook state travels in a :mod:`contextvars` context rather
than a plain global, so ``async def`` component bodies keep their hook
identity across ``await`` boundaries even when several coroutine
renders interleave on the event loop.
Example:
```python
import pythonnative as pn
@pn.component
def Counter(initial=0):
count, set_count = pn.use_state(initial)
return pn.Column(
pn.Text(f"Count: {count}"),
pn.Button("+", on_press=lambda: set_count(count + 1)),
)
```
"""
import
asyncio
import
inspect
from
contextlib
import
contextmanager
from
contextvars
import
ContextVar
,
Token
from
dataclasses
import
dataclass
,
field
,
replace
from
typing
import
Any
,
Awaitable
,
Callable
,
Dict
,
Generator
,
Generic
,
List
,
Optional
,
Tuple
,
TypeVar
from
.
import
diagnostics
from
.
element
import
Element
from
.
suspense
import
CoroDriver
,
Resource
T
=
TypeVar
(
"T"
)
_SENTINEL
=
object
()
# The component whose body is currently executing. A ContextVar (not a
# global or thread-local) so coroutine component bodies resume with the
# right hook state after every ``await``, no matter how renders
# interleave on the loop.
_hook_context
:
"ContextVar[Optional[HookState]]"
=
ContextVar
(
"pn_hook_state"
,
default
=
None
)
# Depth of nested ``batch_updates`` blocks plus the trigger deferred by
# the outermost block, per execution context.
_batch_depth
:
"ContextVar[int]"
=
ContextVar
(
"pn_batch_depth"
,
default
=
0
)
_batch_pending
:
"ContextVar[Optional[List[Callable[[], None]]]]"
=
ContextVar
(
"pn_batch_pending"
,
default
=
None
)
# Whether state updates in the current execution context were marked as
# transitions (see ``use_transition``). Transition updates defer their
# re-render to a later loop turn so urgent updates stay responsive.
_transition_var
:
"ContextVar[bool]"
=
ContextVar
(
"pn_transition"
,
default
=
False
)
# ======================================================================
# Ref
# ======================================================================
class
Ref
(
Generic
[
T
]):
"""Mutable container returned by [`use_ref`][pythonnative.use_ref].
A ``Ref`` holds one value on its ``current`` attribute. Mutating
``current`` never triggers a re-render, which makes refs the right
place for timers, last-seen values, and imperative handles.
When a ``Ref`` is passed to a built-in element via the ``ref=``
prop, the reconciler populates ``current`` with the underlying
native view (``UIView`` on iOS, ``android.view.View`` on Android,
a Tk widget on desktop) after commit, and clears it back to
``None`` on unmount. Composite components (e.g.
[`FlatList`][pythonnative.FlatList]) instead publish a typed
controller object on ``current`` via
[`use_imperative_handle`][pythonnative.use_imperative_handle].
Attributes:
current: The referenced value. ``None`` until populated.
"""
__slots__
=
(
"current"
,
"_pn_tag"
,
"_pn_frame"
)
def
__init__
(
self
,
initial
:
Optional
[
T
]
=
None
)
->
None
:
self
.
current
:
Optional
[
T
]
=
initial
# Internal: the native view tag, populated by the reconciler
# when the ref is attached to a built-in element.
self
.
_pn_tag
:
Optional
[
int
]
=
None
# Internal: the last committed frame ``(x, y, w, h)``, mirrored
# by the layout pass so Python code can read measured geometry
# without a native round-trip.
self
.
_pn_frame
:
Optional
[
Tuple
[
float
,
float
,
float
,
float
]]
=
None
def
__repr__
(
self
)
->
str
:
return
f"Ref(
{
self
.
current
!r
}
)"
# ======================================================================
# Hook state container
# ======================================================================
class
HookState
:
"""Per-instance storage for one component's hooks.
Each `@component` instance owns one `HookState`. Hooks are matched
to slots by call order, so they must always be called in the same
order across renders. Effects scheduled during render are deferred
(layout effects into ``_pending_layout_effects``, passive effects
into ``_pending_effects``) and flushed by the reconciler in two
phases after native mutations commit.
Attributes:
states: One entry per `use_state` / `use_reducer` call.
effects: One `(deps, cleanup)` tuple per `use_effect` call.
layout_effects: One `(deps, cleanup)` tuple per
`use_layout_effect` call.
memos: One `(deps, value)` tuple per `use_memo` / `use_callback`.
refs: One [`Ref`][pythonnative.Ref] per `use_ref` call.
"""
__slots__
=
(
"states"
,
"effects"
,
"layout_effects"
,
"memos"
,
"refs"
,
"resources"
,
"state_index"
,
"effect_index"
,
"layout_effect_index"
,
"memo_index"
,
"ref_index"
,
"resource_index"
,
"context_deps"
,
"_trigger_render"
,
"_pending_effects"
,
"_pending_layout_effects"
,
"_pending_effects_mark"
,
"_pending_layout_effects_mark"
,
"_dirty"
,
"_vnode"
,
"_reconciler"
,
"_hook_log"
,
"_hook_signature"
,
"_component_name"
,
"_async_driver"
,
)
def
__init__
(
self
)
->
None
:
self
.
states
:
List
[
Any
]
=
[]
self
.
effects
:
List
[
Tuple
[
Any
,
Any
]]
=
[]
self
.
layout_effects
:
List
[
Tuple
[
Any
,
Any
]]
=
[]
self
.
memos
:
List
[
Tuple
[
Any
,
Any
]]
=
[]
self
.
refs
:
List
[
Ref
]
=
[]
# One ``(deps, Resource)`` per ``use_resource`` call.
self
.
resources
:
List
[
Tuple
[
Any
,
Resource
]]
=
[]
self
.
state_index
:
int
=
0
self
.
effect_index
:
int
=
0
self
.
layout_effect_index
:
int
=
0
self
.
memo_index
:
int
=
0
self
.
ref_index
:
int
=
0
self
.
resource_index
:
int
=
0
# Contexts read during the last completed render, keyed by
# ``id(context)``. The reconciler consults this when a
# Provider's value changes so consumers re-render even when a
# memoized ancestor skipped (reactive context).
self
.
context_deps
:
Dict
[
int
,
Any
]
=
{}
self
.
_trigger_render
:
Optional
[
Callable
[[],
None
]]
=
None
self
.
_pending_effects
:
List
[
Tuple
[
int
,
Callable
,
Any
]]
=
[]
self
.
_pending_layout_effects
:
List
[
Tuple
[
int
,
Callable
,
Any
]]
=
[]
# Cleared by the reconciler after each successful render.
# ``use_state`` / ``use_reducer`` setters flip it to ``True``
# whenever they actually mutate state, so [`memo`][pythonnative.memo]
# knows that a memoized component still needs to re-render even
# when its props didn't change.
self
.
_dirty
:
bool
=
False
# Back-references wired by the reconciler so a state setter can
# mark *its own* component subtree dirty for a local re-render
# (instead of forcing a whole-app re-render from the root). Both
# stay ``None`` until the component is mounted, and are cleared
# again when it unmounts.
self
.
_vnode
:
Any
=
None
self
.
_reconciler
:
Any
=
None
# Dev-mode hook-order guard: the sequence of hook kinds called
# during the in-flight render, and the signature captured from
# the first successful render.
self
.
_hook_log
:
Optional
[
List
[
str
]]
=
None
self
.
_hook_signature
:
Optional
[
List
[
str
]]
=
None
self
.
_component_name
:
str
=
""
# For ``async def`` components: the CoroDriver running the
# in-flight body, cancelled when a newer render supersedes it.
self
.
_async_driver
:
Optional
[
CoroDriver
]
=
None
# Effect-queue lengths at ``begin_render``, so a suspended
# render can be rolled back without double-queueing effects.
self
.
_pending_effects_mark
:
int
=
0
self
.
_pending_layout_effects_mark
:
int
=
0
def
begin_render
(
self
,
component_name
:
str
=
""
)
->
None
:
"""Prepare for a render pass: reset cursors and the dev-mode hook log.
Called by the reconciler before each invocation of the
component body so the next render reads slots in the same
order they were written.
"""
self
.
state_index
=
0
self
.
effect_index
=
0
self
.
layout_effect_index
=
0
self
.
memo_index
=
0
self
.
ref_index
=
0
self
.
resource_index
=
0
self
.
context_deps
=
{}
if
component_name
:
self
.
_component_name
=
component_name
self
.
_hook_log
=
[]
if
diagnostics
.
is_dev
()
else
None
self
.
_pending_effects_mark
=
len
(
self
.
_pending_effects
)
self
.
_pending_layout_effects_mark
=
len
(
self
.
_pending_layout_effects
)
def
abort_render
(
self
)
->
None
:
"""Roll back a suspended render's effect queue.
A suspended body re-runs from the top on retry, so any effects
it queued before suspending would otherwise be queued twice.
"""
del
self
.
_pending_effects
[
self
.
_pending_effects_mark
:]
del
self
.
_pending_layout_effects
[
self
.
_pending_layout_effects_mark
:]
self
.
_hook_log
=
None
def
finish_render
(
self
)
->
None
:
"""Finalize a successful render: lock in / verify the hook signature.
Only called when the component body returned without raising,
so a failed render never corrupts the signature.
Raises:
HookOrderError: In dev mode, when this render called fewer
hooks than the previous one.
"""
log
=
self
.
_hook_log
self
.
_hook_log
=
None
if
log
is
None
:
return
if
self
.
_hook_signature
is
None
:
self
.
_hook_signature
=
log
return
if
len
(
log
)
<
len
(
self
.
_hook_signature
):
missing
=
self
.
_hook_signature
[
len
(
log
)]
raise
diagnostics
.
HookOrderError
(
f"
{
self
.
_component_name
or
'Component'
}
rendered fewer hooks than the previous "
f"render (expected
{
missing
!r
}
at position
{
len
(
log
)
+
1
}
). Hooks must be called "
"unconditionally, in the same order, on every render."
)
def
record_hook
(
self
,
kind
:
str
)
->
None
:
"""Record a hook call for the dev-mode order guard.
Raises:
HookOrderError: In dev mode, when the hook at this position
differs from (or extends past) the previous render.
"""
log
=
self
.
_hook_log
if
log
is
None
:
return
position
=
len
(
log
)
log
.
append
(
kind
)
signature
=
self
.
_hook_signature
if
signature
is
None
:
return
if
position
>=
len
(
signature
):
raise
diagnostics
.
HookOrderError
(
f"
{
self
.
_component_name
or
'Component'
}
rendered more hooks than the previous "
f"render (
{
kind
!r
}
at position
{
position
+
1
}
). Hooks must be called "
"unconditionally, in the same order, on every render."
)
if
signature
[
position
]
!=
kind
:
raise
diagnostics
.
HookOrderError
(
f"
{
self
.
_component_name
or
'Component'
}
called
{
kind
!r
}
at position "
f"
{
position
+
1
}
, but the previous render called
{
signature
[
position
]!r
}
there. "
"Hooks must be called unconditionally, in the same order, on every render."
)
def
reset_hook_signature
(
self
)
->
None
:
"""Forget the recorded hook signature (used by Fast Refresh).
After a hot reload swaps in a new component body, the old
signature no longer applies; the next render records a fresh
one.
"""
self
.
_hook_signature
=
None
def
flush_layout_effects
(
self
)
->
None
:
"""Run layout effects queued during render (commit phase, pre-paint)."""
pending
=
self
.
_pending_layout_effects
self
.
_pending_layout_effects
=
[]
self
.
_pending_layout_effects_mark
=
0
for
idx
,
effect_fn
,
deps
in
pending
:
_
,
prev_cleanup
=
self
.
layout_effects
[
idx
]
if
callable
(
prev_cleanup
):
try
:
prev_cleanup
()
except
Exception
:
pass
cleanup
=
_activate_effect
(
effect_fn
)
self
.
layout_effects
[
idx
]
=
(
list
(
deps
)
if
deps
is
not
None
else
None
,
cleanup
)
def
flush_pending_effects
(
self
)
->
None
:
"""Run passive effects queued during render, after native commit.
For each pending effect, the previous cleanup is invoked first
(if any), then the new effect callback. The new return value
becomes the next cleanup. Effects that are ``async def`` (or
that return an awaitable) run as tasks on the framework loop;
their cleanup cancels the task, and a callable returned by the
coroutine runs as an additional cleanup once it completed.
"""
pending
=
self
.
_pending_effects
self
.
_pending_effects
=
[]
self
.
_pending_effects_mark
=
0
for
idx
,
effect_fn
,
deps
in
pending
:
_
,
prev_cleanup
=
self
.
effects
[
idx
]
if
callable
(
prev_cleanup
):
try
:
prev_cleanup
()
except
Exception
:
pass
cleanup
=
_activate_effect
(
effect_fn
)
self
.
effects
[
idx
]
=
(
list
(
deps
)
if
deps
is
not
None
else
None
,
cleanup
)
def
cleanup_all_effects
(
self
)
->
None
:
"""Run every outstanding cleanup function, then clear state.
Layout-effect cleanups run before passive-effect cleanups,
matching the mount order in reverse. Also cancels in-flight
resources and any pending ``async def`` body. Called when the
component instance is unmounted by the reconciler.
"""
for
i
, (
_deps
,
cleanup
)
in
enumerate
(
self
.
layout_effects
):
if
callable
(
cleanup
):
try
:
cleanup
()
except
Exception
:
pass
self
.
layout_effects
[
i
]
=
(
_SENTINEL
,
None
)
for
i
, (
_deps
,
cleanup
)
in
enumerate
(
self
.
effects
):
if
callable
(
cleanup
):
try
:
cleanup
()
except
Exception
:
pass
self
.
effects
[
i
]
=
(
_SENTINEL
,
None
)
self
.
_pending_effects
=
[]
self
.
_pending_layout_effects
=
[]
self
.
_pending_effects_mark
=
0
self
.
_pending_layout_effects_mark
=
0
for
_deps
,
resource
in
self
.
resources
:
try
:
resource
.
cancel
()
except
Exception
:
pass
self
.
resources
=
[]
driver
=
self
.
_async_driver
self
.
_async_driver
=
None
if
driver
is
not
None
:
driver
.
cancel
()
# ======================================================================
# Context helpers
# ======================================================================
def
_get_hook_state
()
->
Optional
[
HookState
]:
"""Return the active `HookState`, or `None` if no render is in flight."""
return
_hook_context
.
get
()
def
_set_hook_state
(
state
:
Optional
[
HookState
])
->
"Token[Optional[HookState]]"
:
"""Install `state` as the active `HookState`; returns the reset token."""
return
_hook_context
.
set
(
state
)
def
_reset_hook_state
(
token
:
"Token[Optional[HookState]]"
)
->
None
:
"""Restore the hook state that was active before `_set_hook_state`."""
_hook_context
.
reset
(
token
)
def
_deps_changed
(
prev
:
Any
,
current
:
Any
)
->
bool
:
"""Return whether the dependency arrays differ enough to re-run an effect."""
if
prev
is
_SENTINEL
:
return
True
if
prev
is
None
or
current
is
None
:
return
True
if
len
(
prev
)
!=
len
(
current
):
return
True
return
any
(
p
is
not
c
and
p
!=
c
for
p
,
c
in
zip
(
prev
,
current
))
def
_activate_effect
(
effect_fn
:
Callable
)
->
Any
:
"""Invoke an effect callback, running coroutine effects as tasks.
Synchronous effects return their cleanup directly. When the effect
is an ``async def`` (or returns an awaitable), the coroutine runs
as a task on the framework loop and the returned cleanup cancels
it; if the coroutine already finished and returned a callable, that
callable runs as the cleanup instead.
"""
result
=
effect_fn
()
if
not
inspect
.
isawaitable
(
result
):
return
result
from
.
runtime
import
run_async
future
=
run_async
(
result
)
def
_observe
(
fut
:
Any
)
->
None
:
# Surface unhandled async-effect crashes instead of letting the
# future's exception vanish unobserved: RedBox in dev mode,
# traceback in production.
if
fut
.
cancelled
():
return
exc
=
fut
.
exception
()
if
exc
is
None
or
isinstance
(
exc
,
asyncio
.
CancelledError
):
return
if
not
diagnostics
.
report_error
(
exc
,
phase
=
"async effect"
):
import
traceback
traceback
.
print_exception
(
type
(
exc
),
exc
,
exc
.
__traceback__
)
future
.
add_done_callback
(
_observe
)
def
_cleanup
()
->
None
:
if
future
.
cancelled
():
return
if
future
.
done
():
if
future
.
exception
()
is
None
:
returned
=
future
.
result
()
if
callable
(
returned
):
try
:
returned
()
except
Exception
:
pass
return
future
.
cancel
()
return
_cleanup
# ======================================================================
# Batching and transition scheduling
# ======================================================================
def
_schedule_trigger
(
trigger
:
Callable
[[],
None
])
->
None
:
"""Run ``trigger`` immediately, or defer it inside a `batch_updates` block."""
pending
=
_batch_pending
.
get
()
if
_batch_depth
.
get
()
>
0
and
pending
is
not
None
:
if
trigger
not
in
pending
:
pending
.
append
(
trigger
)
else
:
trigger
()
# Transition scheduling state. Deferred triggers (and the callbacks
# that flip ``is_pending`` back off) run together on a later loop turn.
_deferred_triggers
:
List
[
Callable
[[],
None
]]
=
[]
_post_transition_callbacks
:
List
[
Callable
[[],
None
]]
=
[]
_transition_flush_scheduled
=
False
def
_flush_transitions
()
->
None
:
"""Run every deferred transition render, then the completion callbacks."""
global
_transition_flush_scheduled
_transition_flush_scheduled
=
False
triggers
=
list
(
_deferred_triggers
)
_deferred_triggers
.
clear
()
callbacks
=
list
(
_post_transition_callbacks
)
_post_transition_callbacks
.
clear
()
for
trigger
in
triggers
:
try
:
trigger
()
except
Exception
as
exc
:
if
not
diagnostics
.
report_error
(
exc
,
phase
=
"transition"
):
raise
for
callback
in
callbacks
:
try
:
callback
()
except
Exception
as
exc
:
if
not
diagnostics
.
report_error
(
exc
,
phase
=
"transition"
):
raise
def
_schedule_transition_flush
()
->
None
:
"""Ensure a transition flush is queued on the framework loop."""
global
_transition_flush_scheduled
if
_transition_flush_scheduled
:
return
_transition_flush_scheduled
=
True
from
.
runtime
import
get_loop
get_loop
().
call_soon
(
_flush_transitions
)
def
_defer_transition_trigger
(
trigger
:
Callable
[[],
None
])
->
None
:
if
trigger
not
in
_deferred_triggers
:
_deferred_triggers
.
append
(
trigger
)
_schedule_transition_flush
()
def
_run_in_transition
(
fn
:
Callable
[[],
None
])
->
None
:
"""Run ``fn`` with its state updates marked as transitions."""
token
=
_transition_var
.
set
(
True
)
try
:
fn
()
finally
:
_transition_var
.
reset
(
token
)
def
_notify_state_changed
(
ctx
:
"HookState"
)
->
None
:
"""Mark ``ctx``'s component dirty and schedule a render after a state change.
Enqueuing the owning ``VNode`` in the reconciler's dirty set is what
makes the subsequent render *local*: the screen host's trigger calls
``flush_dirty``, which re-renders only the components marked here
rather than the whole app. The dirty mark is eager (so several
setters coalesce), while the render trigger respects
[`batch_updates`][pythonnative.batch_updates] and defers to a later
loop turn inside a transition (see
[`use_transition`][pythonnative.use_transition]).
"""
ctx
.
_dirty
=
True
reconciler
=
ctx
.
_reconciler
vnode
=
ctx
.
_vnode
if
reconciler
is
not
None
and
vnode
is
not
None
:
reconciler
.
mark_dirty
(
vnode
)
if
ctx
.
_trigger_render
:
if
_transition_var
.
get
():
_defer_transition_trigger
(
ctx
.
_trigger_render
)
else
:
_schedule_trigger
(
ctx
.
_trigger_render
)
@
contextmanager
def
batch_updates
()
->
Generator
[
None
,
None
,
None
]:
"""Coalesce multiple state updates into a single re-render.
State setters called inside the `with` block defer their
re-render trigger until the block exits, so any number of
`set_*` calls produce at most one render pass.
Yields:
None. The block executes normally; deferred renders fire on
exit.
Example:
```python
import pythonnative as pn
with pn.batch_updates():
set_count(1)
set_name("hello")
```
"""
depth
=
_batch_depth
.
get
()
depth_token
=
_batch_depth
.
set
(
depth
+
1
)
pending_token
=
None
if
depth
==
0
:
pending_token
=
_batch_pending
.
set
([])
try
:
yield
finally
:
_batch_depth
.
reset
(
depth_token
)
if
pending_token
is
not
None
:
triggers
=
_batch_pending
.
get
()
or
[]
_batch_pending
.
reset
(
pending_token
)
for
trigger
in
triggers
:
trigger
()
# ======================================================================
# Public hooks
# ======================================================================
def
use_state
(
initial
:
Any
=
None
)
->
Tuple
[
Any
,
Callable
]:
"""Return ``(value, setter)`` for component-local state.
State persists across re-renders of the same component instance.
The setter accepts a value or a ``current -> new`` callable; calling
it with an unchanged value is a no-op (no re-render).
Args:
initial: Initial state value. If callable, it is invoked once on
the first render (lazy initialization).
Returns:
A 2-tuple ``(value, setter)`` where ``value`` is the current
state and ``setter`` updates it (and triggers a re-render).
Raises:
RuntimeError: If called outside a `@component` function.
Example:
```python
import pythonnative as pn
@pn.component
def Counter():
count, set_count = pn.use_state(0)
return pn.Button(
f"Count: {count}",
on_press=lambda: set_count(count + 1),
)
```
"""
ctx
=
_get_hook_state
()
if
ctx
is
None
:
raise
RuntimeError
(
"use_state must be called inside a @component function"
)
ctx
.
record_hook
(
"use_state"
)
idx
=
ctx
.
state_index
ctx
.
state_index
+=
1
if
idx
>=
len
(
ctx
.
states
):
val
=
initial
()
if
callable
(
initial
)
else
initial
ctx
.
states
.
append
(
val
)
current
=
ctx
.
states
[
idx
]
def
setter
(
new_value
:
Any
)
->
None
:
if
callable
(
new_value
):
new_value
=
new_value
(
ctx
.
states
[
idx
])
if
ctx
.
states
[
idx
]
is
not
new_value
and
ctx
.
states
[
idx
]
!=
new_value
:
ctx
.
states
[
idx
]
=
new_value
_notify_state_changed
(
ctx
)
return
current
,
setter
def
use_reducer
(
reducer
:
Callable
[[
Any
,
Any
],
Any
],
initial_state
:
Any
)
->
Tuple
[
Any
,
Callable
]:
"""Return ``(state, dispatch)`` for reducer-based state management.
A reducer is a pure function that takes the current state and an
action and returns the next state. Use it instead of
[`use_state`][pythonnative.use_state] when state transitions are
complex enough that centralizing them in one function aids
readability and testing.
Args:
reducer: ``reducer(current_state, action) -> new_state``.
The component re-renders only when `reducer` returns a
value different from the current state.
initial_state: Initial state value, or a callable invoked once
on the first render.
Returns:
A 2-tuple ``(state, dispatch)`` where `dispatch` runs the
reducer with the supplied action.
Raises:
RuntimeError: If called outside a `@component` function.
Example:
```python
import pythonnative as pn
def reducer(state, action):
if action == "increment":
return state + 1
if action == "reset":
return 0
return state
@pn.component
def Counter():
count, dispatch = pn.use_reducer(reducer, 0)
return pn.Row(
pn.Button("+", on_press=lambda: dispatch("increment")),
pn.Button("Reset", on_press=lambda: dispatch("reset")),
)
```
"""
ctx
=
_get_hook_state
()
if
ctx
is
None
:
raise
RuntimeError
(
"use_reducer must be called inside a @component function"
)
ctx
.
record_hook
(
"use_reducer"
)
idx
=
ctx
.
state_index
ctx
.
state_index
+=
1
if
idx
>=
len
(
ctx
.
states
):
val
=
initial_state
()
if
callable
(
initial_state
)
else
initial_state
ctx
.
states
.
append
(
val
)
current
=
ctx
.
states
[
idx
]
def
dispatch
(
action
:
Any
)
->
None
:
new_state
=
reducer
(
ctx
.
states
[
idx
],
action
)
if
ctx
.
states
[
idx
]
is
not
new_state
and
ctx
.
states
[
idx
]
!=
new_state
:
ctx
.
states
[
idx
]
=
new_state
_notify_state_changed
(
ctx
)
return
current
,
dispatch
def
use_effect
(
effect
:
Callable
,
deps
:
Optional
[
list
]
=
None
)
->
None
:
"""Schedule a side effect to run after the native commit.
Effects are queued during the render pass and flushed once the
reconciler has finished applying all native-view mutations, which
means effect callbacks can safely measure layout or interact with
committed native views.
The `deps` argument controls when the effect re-runs:
- `None`: every render.
- `[]`: mount only.
- `[a, b]`: when `a` or `b` change (compared by identity, then `==`).
A synchronous `effect` may return a cleanup callable; the previous
cleanup runs before the next effect (and on unmount).
An **async** `effect` (an ``async def``) runs as a task on the
framework loop. When `deps` change or the component unmounts, the
in-flight task is cancelled (:class:`asyncio.CancelledError` is
raised at its current ``await``), giving async effects structured
cancellation for free. If the coroutine finishes and returns a
callable, that callable runs as the cleanup instead.
Args:
effect: A zero-arg callable invoked after commit: either a
synchronous function (optionally returning a cleanup
callable) or an ``async def``.
deps: Dependency list, or `None` to run on every render.
Raises:
RuntimeError: If called outside a `@component` function.
Example:
```python
import asyncio
import pythonnative as pn
@pn.component
def Clock():
now, set_now = pn.use_state("")
async def tick():
while True:
set_now(time.strftime("%H:%M:%S"))
await asyncio.sleep(1)
pn.use_effect(tick, [])
return pn.Text(now)
```
"""
ctx
=
_get_hook_state
()
if
ctx
is
None
:
raise
RuntimeError
(
"use_effect must be called inside a @component function"
)
ctx
.
record_hook
(
"use_effect"
)
idx
=
ctx
.
effect_index
ctx
.
effect_index
+=
1
if
idx
>=
len
(
ctx
.
effects
):
ctx
.
effects
.
append
((
_SENTINEL
,
None
))
ctx
.
_pending_effects
.
append
((
idx
,
effect
,
deps
))
return
prev_deps
,
_prev_cleanup
=
ctx
.
effects
[
idx
]
if
_deps_changed
(
prev_deps
,
deps
):
ctx
.
_pending_effects
.
append
((
idx
,
effect
,
deps
))
def
use_layout_effect
(
effect
:
Callable
,
deps
:
Optional
[
list
]
=
None
)
->
None
:
"""Schedule a side effect that runs synchronously inside the commit.
Like [`use_effect`][pythonnative.use_effect], but the callback
fires *before* passive effects, immediately after native mutations
and the layout pass are applied. Use it when you need to measure a
committed frame (via a [`Ref`][pythonnative.Ref]) or issue an
imperative view command before the user sees the new frame, for
example scrolling a list into position on mount.
Prefer `use_effect` for everything else; layout effects block the
commit, so heavy work here delays the frame.
Args:
effect: A zero-arg callable invoked during commit. Optionally
returns a cleanup callable.
deps: Dependency list, or `None` to run on every render.
Raises:
RuntimeError: If called outside a `@component` function.
Example:
```python
import pythonnative as pn
@pn.component
def AutoScrollList(items):
list_ref = pn.use_ref()
def scroll_to_bottom():
if list_ref.current is not None:
list_ref.current.scroll_to_end(animated=False)
pn.use_layout_effect(scroll_to_bottom, [len(items)])
return pn.FlatList(items, render_item=Row, ref=list_ref)
```
"""
ctx
=
_get_hook_state
()
if
ctx
is
None
:
raise
RuntimeError
(
"use_layout_effect must be called inside a @component function"
)
ctx
.
record_hook
(
"use_layout_effect"
)
idx
=
ctx
.
layout_effect_index
ctx
.
layout_effect_index
+=
1
if
idx
>=
len
(
ctx
.
layout_effects
):
ctx
.
layout_effects
.
append
((
_SENTINEL
,
None
))
ctx
.
_pending_layout_effects
.
append
((
idx
,
effect
,
deps
))
return
prev_deps
,
_prev_cleanup
=
ctx
.
layout_effects
[
idx
]
if
_deps_changed
(
prev_deps
,
deps
):
ctx
.
_pending_layout_effects
.
append
((
idx
,
effect
,
deps
))
def
use_memo
(
factory
:
Callable
[[],
T
],
deps
:
list
)
->
T
:
"""Return a memoized value that is recomputed only when `deps` change.
Use this for expensive computations whose inputs change rarely. For
cheap computations, plain inline code is faster (memoization itself
has overhead).
Args:
factory: Zero-arg callable returning the value.
deps: Dependency list. The value is recomputed when any element
differs from the previous render.
Returns:
The cached or freshly computed value.
Raises:
RuntimeError: If called outside a `@component` function.
"""
ctx
=
_get_hook_state
()
if
ctx
is
None
:
raise
RuntimeError
(
"use_memo must be called inside a @component function"
)
ctx
.
record_hook
(
"use_memo"
)
idx
=
ctx
.
memo_index
ctx
.
memo_index
+=
1
if
idx
>=
len
(
ctx
.
memos
):
value
=
factory
()
ctx
.
memos
.
append
((
list
(
deps
),
value
))
return
value
prev_deps
,
prev_value
=
ctx
.
memos
[
idx
]
if
not
_deps_changed
(
prev_deps
,
deps
):
return
prev_value
value
=
factory
()
ctx
.
memos
[
idx
]
=
(
list
(
deps
),
value
)
return
value
def
use_callback
(
callback
:
Callable
,
deps
:
list
)
->
Callable
:
"""Return a stable reference to ``callback``, refreshed when ``deps`` change.
Equivalent to `use_memo(lambda: callback, deps)`. Useful when passing
a function as a prop to a memoized child component, so the child
doesn't see a fresh function identity on every render.
Args:
callback: The callable to memoize.
deps: Dependency list controlling when the reference refreshes.
Returns:
A callable with stable identity across renders (until `deps` change).
"""
return
use_memo
(
lambda
:
callback
,
deps
)
def
use_ref
(
initial
:
Optional
[
T
]
=
None
)
->
Ref
[
T
]:
"""Return a [`Ref`][pythonnative.Ref] that persists across renders.
Refs are useful for storing values that must survive renders without
triggering them: timers, last-seen values, native handles, and so on.
``ref.current`` is also populated by the reconciler with the
underlying native view (`UIView` on iOS, `android.view.View` on
Android, a Tk widget on desktop) when the ref is passed via the
``ref=`` prop on a built-in element, and cleared to ``None`` when
that element unmounts. Composite components such as
[`FlatList`][pythonnative.FlatList] publish a typed controller
object instead (see
[`use_imperative_handle`][pythonnative.use_imperative_handle]).
Args:
initial: Value placed at ``ref.current`` on first render.
Returns:
A [`Ref`][pythonnative.Ref]. Mutations to ``ref.current`` do
*not* trigger re-renders.
Raises:
RuntimeError: If called outside a `@component` function.
"""
ctx
=
_get_hook_state
()
if
ctx
is
None
:
raise
RuntimeError
(
"use_ref must be called inside a @component function"
)
ctx
.
record_hook
(
"use_ref"
)
idx
=
ctx
.
ref_index
ctx
.
ref_index
+=
1
if
idx
>=
len
(
ctx
.
refs
):
ref
:
Ref
[
T
]
=
Ref
(
initial
)
ctx
.
refs
.
append
(
ref
)
return
ref
return
ctx
.
refs
[
idx
]
def
use_imperative_handle
(
ref
:
Optional
[
Ref
],
factory
:
Callable
[[],
Any
],
deps
:
Optional
[
list
]
=
None
,
)
->
None
:
"""Publish a controller object on ``ref.current``.
The composite-component counterpart to passing ``ref=`` to a
built-in element. Call it inside a component that accepts a
``ref`` prop to expose a curated imperative API (rather than the
raw native view) to the parent. The handle is installed during the
commit's layout-effect phase and cleared back to ``None`` on
unmount.
Args:
ref: The [`Ref`][pythonnative.Ref] received via the component's
``ref`` prop. ``None`` is allowed (the parent didn't
request a handle), in which case this is a no-op.
factory: Zero-arg callable returning the handle object.
deps: Dependency list controlling when the handle is rebuilt.
Defaults to ``[]`` semantics only if you pass ``[]``;
``None`` rebuilds on every render, matching effects.
Raises:
RuntimeError: If called outside a `@component` function.
Example:
```python
import pythonnative as pn
@pn.component
def VideoPlayer(source, ref=None):
pn.use_imperative_handle(ref, lambda: PlayerController(...), [source])
return pn.View(...)
```
"""
def
_install
()
->
Optional
[
Callable
[[],
None
]]:
if
ref
is
None
:
return
None
ref
.
current
=
factory
()
def
_clear
()
->
None
:
ref
.
current
=
None
return
_clear
use_layout_effect
(
_install
,
deps
)
# ======================================================================
# Async hooks
# ======================================================================
def
use_resource
(
fetcher
:
Callable
[[],
Any
],
deps
:
Optional
[
list
]
=
None
)
->
Resource
[
Any
]:
View remainder of file in raw view
Back
|
FazBrowse Home
|
New Git URL