FazBrowse GitHub Viewer
|
Trending
|
URL:
|
Home
Tools:
[Download Repo ZIP]
[View Raw Code]
[Original HTTPS Page]
pythonnative/src/pythonnative/alerts.py at main · pythonnative/pythonnative · GitHub
pythonnative
/
pythonnative
Public
Notifications
You must be signed in to change notification settings
Fork
23
Star
131
Code
Issues
11
Pull requests
4
Actions
Projects
Security and quality
0
Insights
Additional navigation options
Code
Issues
Pull requests
Actions
Projects
Security and quality
Insights
Expand file tree
Breadcrumbs
pythonnative
/
src
/
pythonnative
/
alerts.py
Copy path
More file actions
More file actions
Latest commit
History
History
History
236 lines (198 loc) · 7.67 KB
Breadcrumbs
pythonnative
/
src
/
pythonnative
/
alerts.py
Copy path
File metadata and controls
236 lines (198 loc) · 7.67 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
"""Imperative, awaitable system alerts.
Inspired by React Native's ``Alert.alert()`` but designed around
``async`` / ``await`` instead of per-button callbacks. There are three
entry points:
- [`Alert.show`][pythonnative.alerts.Alert.show]: fire-and-forget
one-button notice (no return value).
- [`Alert.confirm`][pythonnative.alerts.Alert.confirm]: awaitable
two-button yes/no, resolves to a ``bool``.
- [`Alert.choose`][pythonnative.alerts.Alert.choose]: awaitable
multi-button picker / action sheet, resolves to the selected
label (or ``None`` if dismissed).
Example:
```python
import pythonnative as pn
async def maybe_delete():
if await pn.Alert.confirm(
title="Delete item?",
message="This action cannot be undone.",
confirm_label="Delete",
cancel_label="Keep",
):
await delete_item()
```
"""
from
__future__
import
annotations
from
typing
import
Any
,
Dict
,
List
,
Optional
,
Sequence
from
.
native_modules
.
registry
import
native_module
# ======================================================================
# Internal dispatch helpers
# ======================================================================
async
def
_present
(
*
,
title
:
str
,
message
:
Optional
[
str
],
buttons
:
List
[
Dict
[
str
,
Any
]],
style
:
str
,
)
->
int
:
"""Ask the native ``Alert`` module to present and await the chosen index.
``buttons`` is a list of ``{"label": str, "style":
"default"|"cancel"|"destructive"}`` dicts. The module resolves with
the index the user picked, or ``-1`` if the dialog was dismissed
without a selection. Off device the
[`FallbackAlert`][pythonnative.native_modules.fallback.FallbackAlert]
implementation records the call and answers from the queue set by
[`Alert.set_test_response`][pythonnative.alerts.Alert.set_test_response].
"""
result
=
await
native_module
(
"Alert"
).
call_async
(
"present"
,
title
=
title
,
message
=
message
,
buttons
=
buttons
,
style
=
style
)
try
:
return
int
(
result
)
except
(
TypeError
,
ValueError
):
return
-
1
# ======================================================================
# Public Alert API
# ======================================================================
class
Alert
:
"""Imperative alert / action-sheet helper.
All methods are static. Use [`show`][pythonnative.alerts.Alert.show]
for a fire-and-forget single-button notice,
[`confirm`][pythonnative.alerts.Alert.confirm] for an awaitable
yes/no dialog, and
[`choose`][pythonnative.alerts.Alert.choose] for a multi-option
picker.
"""
#: Records every alert call when running off-device. Tests reset
#: this between cases via ``Alert._test_log.clear()``. Each entry
#: contains ``title``, ``message``, ``buttons``, and ``style``.
_test_log
:
List
[
Dict
[
str
,
Any
]]
=
[]
#: Queue of indices to deliver to upcoming alerts in tests. Set via
#: [`Alert.set_test_response`][pythonnative.alerts.Alert.set_test_response].
#: A negative value (or empty queue) simulates a dismiss.
_test_responses
:
List
[
int
]
=
[]
@
staticmethod
def
set_test_response
(
*
indices
:
int
)
->
None
:
"""Queue indices to return from upcoming test alerts.
Use in async tests to script the user's choices: each pending
call to [`confirm`][pythonnative.alerts.Alert.confirm] or
[`choose`][pythonnative.alerts.Alert.choose] pops the next
queued index. Pass ``-1`` to simulate a dismiss.
Args:
*indices: Sequence of button indices to deliver, oldest
first. Calls beyond the queue length resolve to ``-1``.
"""
Alert
.
_test_responses
[:]
=
list
(
indices
)
@
staticmethod
def
_next_test_response
()
->
int
:
if
Alert
.
_test_responses
:
return
Alert
.
_test_responses
.
pop
(
0
)
return
-
1
@
staticmethod
def
show
(
title
:
str
,
message
:
Optional
[
str
]
=
None
,
*
,
button
:
str
=
"OK"
,
)
->
None
:
"""Display a simple, one-button alert and return immediately.
Args:
title: Dialog title.
message: Optional body text.
button: Label for the single dismiss button (default
``"OK"``).
This is fire-and-forget. To know what the user did, use
[`confirm`][pythonnative.alerts.Alert.confirm] or
[`choose`][pythonnative.alerts.Alert.choose] and ``await``
the result.
"""
native_module
(
"Alert"
).
call
(
"show"
,
title
=
title
,
message
=
message
,
buttons
=
[{
"label"
:
button
,
"style"
:
"default"
}],
style
=
"alert"
)
@
staticmethod
async
def
confirm
(
title
:
str
,
message
:
Optional
[
str
]
=
None
,
*
,
confirm_label
:
str
=
"OK"
,
cancel_label
:
str
=
"Cancel"
,
)
->
bool
:
"""Present a two-button yes/no dialog and wait for the choice.
Args:
title: Dialog title.
message: Optional body text.
confirm_label: Label for the "yes" button (default
``"OK"``).
cancel_label: Label for the "no" button (default
``"Cancel"``).
Returns:
``True`` if the user pressed the confirm button, ``False``
for the cancel button or a dismiss.
Example:
```python
if await pn.Alert.confirm("Save changes?"):
await save()
```
"""
index
=
await
_present
(
title
=
title
,
message
=
message
,
buttons
=
[
{
"label"
:
cancel_label
,
"style"
:
"cancel"
},
{
"label"
:
confirm_label
,
"style"
:
"default"
},
],
style
=
"alert"
,
)
return
index
==
1
@
staticmethod
async
def
choose
(
title
:
str
,
options
:
Sequence
[
str
],
*
,
message
:
Optional
[
str
]
=
None
,
cancel_label
:
Optional
[
str
]
=
None
,
style
:
str
=
"action_sheet"
,
destructive_labels
:
Sequence
[
str
]
=
(),
)
->
Optional
[
str
]:
"""Present a multi-option picker and wait for the user's choice.
Args:
title: Dialog title.
options: Sequence of option labels (in display order).
message: Optional body text.
cancel_label: If provided, adds a "cancel" button with
this label. Selecting it resolves to ``None``.
style: ``"action_sheet"`` (default) for an iOS-style
sheet, or ``"alert"`` for a stacked alert dialog.
destructive_labels: Labels in ``options`` that should be
styled destructively (red on iOS).
Returns:
The selected label, or ``None`` if the user dismissed or
tapped the cancel button.
Example:
```python
choice = await pn.Alert.choose(
"Photo source",
options=["Camera", "Gallery"],
cancel_label="Cancel",
)
if choice == "Camera":
...
```
"""
if
not
options
:
raise
ValueError
(
"Alert.choose requires at least one option"
)
destructive
=
set
(
destructive_labels
)
buttons
:
List
[
Dict
[
str
,
Any
]]
=
[
{
"label"
:
opt
,
"style"
:
"destructive"
if
opt
in
destructive
else
"default"
,
}
for
opt
in
options
]
if
cancel_label
is
not
None
:
buttons
.
append
({
"label"
:
cancel_label
,
"style"
:
"cancel"
})
index
=
await
_present
(
title
=
title
,
message
=
message
,
buttons
=
buttons
,
style
=
style
)
if
0
<=
index
<
len
(
options
):
return
options
[
index
]
return
None
__all__
=
[
"Alert"
]
Back
|
FazBrowse Home
|
New Git URL