wizard-ui-bridge 1.1__py3-none-any.whl
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- wizard_ui_bridge/__init__.py +71 -0
- wizard_ui_bridge/_calendar.py +183 -0
- wizard_ui_bridge/_fake.py +140 -0
- wizard_ui_bridge/_form_prefill.py +78 -0
- wizard_ui_bridge/_parse.py +303 -0
- wizard_ui_bridge/_path.py +170 -0
- wizard_ui_bridge/_table.py +215 -0
- wizard_ui_bridge/_textual_widgets.py +227 -0
- wizard_ui_bridge/arg_types.py +149 -0
- wizard_ui_bridge/bridge.py +740 -0
- wizard_ui_bridge/bridge_helpers.py +436 -0
- wizard_ui_bridge/console.py +208 -0
- wizard_ui_bridge/factory.py +109 -0
- wizard_ui_bridge/form_defs.py +663 -0
- wizard_ui_bridge/form_helpers.py +235 -0
- wizard_ui_bridge/py.typed +1 -0
- wizard_ui_bridge/textual_bridge.py +917 -0
- wizard_ui_bridge-1.1.dist-info/METADATA +222 -0
- wizard_ui_bridge-1.1.dist-info/RECORD +22 -0
- wizard_ui_bridge-1.1.dist-info/WHEEL +5 -0
- wizard_ui_bridge-1.1.dist-info/licenses/LICENSE.txt +21 -0
- wizard_ui_bridge-1.1.dist-info/top_level.txt +1 -0
|
@@ -0,0 +1,71 @@
|
|
|
1
|
+
#! /usr/local/bin/python3
|
|
2
|
+
"""Public API for the wizard user interface bridge.
|
|
3
|
+
|
|
4
|
+
A wizard asks a user a series of questions. WizardUiBridge is the
|
|
5
|
+
user-interface-independent way to ask them, so that one wizard can run
|
|
6
|
+
on a plain console, on a full-screen Textual user interface, or on any
|
|
7
|
+
other bridge an application implements.
|
|
8
|
+
|
|
9
|
+
The Textual bridge needs the optional textual package, installed with
|
|
10
|
+
the extra `wizard-ui-bridge[textual]`. Textual is imported only when
|
|
11
|
+
the Textual bridge is actually used, so importing this package, or
|
|
12
|
+
asking for WizardUiBridgeConsole, never imports Textual. Asking for
|
|
13
|
+
WizardUiBridgeTextual without textual installed raises ImportError
|
|
14
|
+
naming the extra to install.
|
|
15
|
+
|
|
16
|
+
Helpers for implementing a bridge of your own are in the modules
|
|
17
|
+
wizard_ui_bridge.bridge_helpers and wizard_ui_bridge.form_helpers.
|
|
18
|
+
"""
|
|
19
|
+
|
|
20
|
+
# Copyright (c) 2026 Tom Björkholm
|
|
21
|
+
# MIT License
|
|
22
|
+
|
|
23
|
+
from typing import TYPE_CHECKING
|
|
24
|
+
from wizard_ui_bridge.bridge import WizardUiBridge
|
|
25
|
+
from wizard_ui_bridge.arg_types import PartialCheck, TableCell, \
|
|
26
|
+
PathAskOptions, TableColumn, WizardAbort, WizardBack, WizardCancelLevel, \
|
|
27
|
+
WizardNavigation, WizardPathKind
|
|
28
|
+
from wizard_ui_bridge.console import WizardUiBridgeConsole
|
|
29
|
+
from wizard_ui_bridge.form_defs import AskField, AskFields, AnswerField, \
|
|
30
|
+
AnswerFields, PartialFormValidator, PartFormValidationResult, \
|
|
31
|
+
PrefillValues, PrefillValueType, AskTextField, AskIntField, \
|
|
32
|
+
AskPathField, AskYesNoField, AskChoiceField, AskMultiChoiceField, \
|
|
33
|
+
AskFloatField, AskDateField, AskTimeField, AskDateTimeField, \
|
|
34
|
+
AskDurationField, AnswerTextField, AnswerIntField, AnswerPathField, \
|
|
35
|
+
AnswerYesNoField, AnswerChoiceField, AnswerMultiChoiceField, \
|
|
36
|
+
AnswerFloatField, AnswerDateField, AnswerTimeField, AnswerDateTimeField, \
|
|
37
|
+
AnswerDurationField
|
|
38
|
+
from wizard_ui_bridge.factory import make_text_ui_bridge, UiBridgeType, \
|
|
39
|
+
textual_installed, load_textual_bridge
|
|
40
|
+
if TYPE_CHECKING:
|
|
41
|
+
from wizard_ui_bridge.textual_bridge import WizardUiBridgeTextual
|
|
42
|
+
|
|
43
|
+
|
|
44
|
+
def __getattr__(name: str) -> object:
|
|
45
|
+
"""Return the Textual bridge class, imported on first use.
|
|
46
|
+
|
|
47
|
+
Textual is an optional dependency, so the Textual bridge is not
|
|
48
|
+
imported when this package is imported. Asking for it without
|
|
49
|
+
textual installed raises ImportError naming the extra to install.
|
|
50
|
+
"""
|
|
51
|
+
if name == 'WizardUiBridgeTextual':
|
|
52
|
+
return load_textual_bridge()
|
|
53
|
+
raise AttributeError(f'module {__name__!r} has no attribute {name!r}')
|
|
54
|
+
|
|
55
|
+
|
|
56
|
+
__all__ = ['WizardUiBridge', 'WizardUiBridgeConsole', 'WizardUiBridgeTextual',
|
|
57
|
+
'WizardNavigation', 'WizardBack', 'WizardCancelLevel',
|
|
58
|
+
'WizardAbort', 'TableColumn', 'TableCell', 'PartialCheck',
|
|
59
|
+
'make_text_ui_bridge', 'UiBridgeType', 'textual_installed',
|
|
60
|
+
'load_textual_bridge', 'PathAskOptions', 'WizardPathKind',
|
|
61
|
+
'AskField', 'AskFields', 'AnswerField', 'AnswerFields',
|
|
62
|
+
'PartialFormValidator', 'PartFormValidationResult',
|
|
63
|
+
'PrefillValues', 'PrefillValueType',
|
|
64
|
+
'AskTextField', 'AskIntField', 'AskPathField', 'AskYesNoField',
|
|
65
|
+
'AskChoiceField', 'AskMultiChoiceField', 'AskFloatField',
|
|
66
|
+
'AskDateField', 'AskTimeField', 'AskDateTimeField',
|
|
67
|
+
'AskDurationField', 'AnswerTextField',
|
|
68
|
+
'AnswerIntField', 'AnswerPathField', 'AnswerYesNoField',
|
|
69
|
+
'AnswerChoiceField', 'AnswerMultiChoiceField', 'AnswerFloatField',
|
|
70
|
+
'AnswerDateField', 'AnswerTimeField', 'AnswerDateTimeField',
|
|
71
|
+
'AnswerDurationField']
|
|
@@ -0,0 +1,183 @@
|
|
|
1
|
+
#! /usr/local/bin/python3
|
|
2
|
+
"""A modal month calendar for the Textual date and date-time fields.
|
|
3
|
+
|
|
4
|
+
A date field, and the date part of a date-time field, are shown in the
|
|
5
|
+
Textual form as a text input paired with a Pick button. Pressing that
|
|
6
|
+
button, or typing the '?' token into the input, opens this modal
|
|
7
|
+
calendar. The user steps between months and years, moves between the
|
|
8
|
+
days of the shown month with the arrow keys, and clicks a day to return
|
|
9
|
+
it; Escape or the Cancel button returns nothing so the input is left
|
|
10
|
+
unchanged. Days outside a field's inclusive bounds are shown disabled,
|
|
11
|
+
so the calendar only offers acceptable dates.
|
|
12
|
+
"""
|
|
13
|
+
|
|
14
|
+
# Copyright (c) 2026 Tom Björkholm
|
|
15
|
+
# MIT License
|
|
16
|
+
|
|
17
|
+
from __future__ import annotations
|
|
18
|
+
import calendar
|
|
19
|
+
from datetime import date
|
|
20
|
+
from typing import ClassVar, Iterator, Optional
|
|
21
|
+
from textual import on
|
|
22
|
+
from textual.app import ComposeResult
|
|
23
|
+
from textual.binding import BindingType
|
|
24
|
+
from textual.containers import Grid, Horizontal
|
|
25
|
+
from textual.screen import ModalScreen
|
|
26
|
+
from textual.widget import Widget
|
|
27
|
+
from textual.widgets import Button, Footer, Static
|
|
28
|
+
from wizard_ui_bridge.form_defs import value_out_of_range
|
|
29
|
+
|
|
30
|
+
_WEEKDAYS = ('Mo', 'Tu', 'We', 'Th', 'Fr', 'Sa', 'Su')
|
|
31
|
+
_NAV = ('prev_year', 'prev_month', 'next_month', 'next_year')
|
|
32
|
+
|
|
33
|
+
|
|
34
|
+
def _shift(year: int, month: int, action: str) -> tuple[int, int]:
|
|
35
|
+
"""Return the year and month reached by one navigation action."""
|
|
36
|
+
if action == 'prev_year':
|
|
37
|
+
year -= 1
|
|
38
|
+
elif action == 'next_year':
|
|
39
|
+
year += 1
|
|
40
|
+
elif action == 'prev_month':
|
|
41
|
+
year, month = (year, month - 1) if month > 1 else (year - 1, 12)
|
|
42
|
+
else:
|
|
43
|
+
year, month = (year, month + 1) if month < 12 else (year + 1, 1)
|
|
44
|
+
return (min(max(year, date.min.year), date.max.year), month)
|
|
45
|
+
|
|
46
|
+
|
|
47
|
+
class _CalendarScreen(ModalScreen[Optional[date]]):
|
|
48
|
+
"""Modal month calendar returning the date the user clicks.
|
|
49
|
+
|
|
50
|
+
The screen opens on a seed month and offers day buttons for that
|
|
51
|
+
month, greying the days outside the inclusive minimum and maximum.
|
|
52
|
+
Month and year buttons move the view, a day button returns its date,
|
|
53
|
+
and Escape or Cancel returns None so the field keeps its value. The
|
|
54
|
+
seed day is focused on opening and the arrow keys move the focus
|
|
55
|
+
between the enabled days of the shown month, so a day can be picked
|
|
56
|
+
without the mouse.
|
|
57
|
+
"""
|
|
58
|
+
|
|
59
|
+
BINDINGS: ClassVar[list[BindingType]] = [
|
|
60
|
+
('escape', 'cancel', 'Cancel'),
|
|
61
|
+
('left', 'step_day(-1)', 'Prev day'),
|
|
62
|
+
('right', 'step_day(1)', 'Next day'),
|
|
63
|
+
('up', 'step_day(-7)', 'Prev week'),
|
|
64
|
+
('down', 'step_day(7)', 'Next week')]
|
|
65
|
+
CSS = '#cal_grid { height: auto; grid-size: 7; }'
|
|
66
|
+
|
|
67
|
+
def __init__(self, seed: date, minimum: Optional[date],
|
|
68
|
+
maximum: Optional[date]) -> None:
|
|
69
|
+
"""Store the seed month, its day and the inclusive day bounds."""
|
|
70
|
+
super().__init__()
|
|
71
|
+
self._year = seed.year
|
|
72
|
+
self._month = seed.month
|
|
73
|
+
self._seed_day = seed.day
|
|
74
|
+
self._minimum = minimum
|
|
75
|
+
self._maximum = maximum
|
|
76
|
+
|
|
77
|
+
def compose(self) -> ComposeResult:
|
|
78
|
+
"""Lay out the title, the navigation, the day grid and footer."""
|
|
79
|
+
yield Static(id='cal_title')
|
|
80
|
+
with Horizontal(id='cal_nav'):
|
|
81
|
+
yield Button('<< year', id='prev_year')
|
|
82
|
+
yield Button('< month', id='prev_month')
|
|
83
|
+
yield Button('month >', id='next_month')
|
|
84
|
+
yield Button('year >>', id='next_year')
|
|
85
|
+
yield Grid(id='cal_grid')
|
|
86
|
+
yield Button('Cancel', id='cancel')
|
|
87
|
+
yield Footer()
|
|
88
|
+
|
|
89
|
+
async def on_mount(self) -> None:
|
|
90
|
+
"""Fill the day grid and focus the seed month's starting day."""
|
|
91
|
+
await self._show_month()
|
|
92
|
+
self._focus_start_day()
|
|
93
|
+
|
|
94
|
+
async def _show_month(self) -> None:
|
|
95
|
+
"""Show the current month's title and rebuild the day grid.
|
|
96
|
+
|
|
97
|
+
The old day widgets are removed before the new ones are mounted,
|
|
98
|
+
so navigating to another month never leaves two cells sharing a
|
|
99
|
+
day id.
|
|
100
|
+
"""
|
|
101
|
+
title = f'{calendar.month_name[self._month]} {self._year}'
|
|
102
|
+
self.query_one('#cal_title', Static).update(title)
|
|
103
|
+
grid = self.query_one('#cal_grid', Grid)
|
|
104
|
+
await grid.remove_children()
|
|
105
|
+
await grid.mount(*self._grid_widgets())
|
|
106
|
+
|
|
107
|
+
def _grid_widgets(self) -> Iterator[Widget]:
|
|
108
|
+
"""Yield the weekday headers and then one widget per day cell."""
|
|
109
|
+
for name in _WEEKDAYS:
|
|
110
|
+
yield Static(name)
|
|
111
|
+
weeks = calendar.Calendar().monthdayscalendar(self._year, self._month)
|
|
112
|
+
for week in weeks:
|
|
113
|
+
for day in week:
|
|
114
|
+
yield self._day_widget(day)
|
|
115
|
+
|
|
116
|
+
def _day_widget(self, day: int) -> Widget:
|
|
117
|
+
"""Return a blank cell for a padding day, else a day button."""
|
|
118
|
+
if day == 0:
|
|
119
|
+
return Static('')
|
|
120
|
+
return Button(str(day), id=f'day_{day}',
|
|
121
|
+
disabled=self._day_disabled(day))
|
|
122
|
+
|
|
123
|
+
def _day_disabled(self, day: int) -> bool:
|
|
124
|
+
"""Return whether a day of the shown month is out of bounds."""
|
|
125
|
+
in_month = date(self._year, self._month, day)
|
|
126
|
+
return value_out_of_range(in_month, self._minimum, self._maximum)
|
|
127
|
+
|
|
128
|
+
@on(Button.Pressed)
|
|
129
|
+
async def _pressed(self, event: Button.Pressed) -> None:
|
|
130
|
+
"""Route a button press to navigation, a day, or cancel."""
|
|
131
|
+
button_id = event.button.id
|
|
132
|
+
if button_id == 'cancel':
|
|
133
|
+
self.action_cancel()
|
|
134
|
+
elif button_id in _NAV:
|
|
135
|
+
self._year, self._month = _shift(self._year, self._month,
|
|
136
|
+
button_id)
|
|
137
|
+
await self._show_month()
|
|
138
|
+
elif button_id is not None and button_id.startswith('day_'):
|
|
139
|
+
self.dismiss(date(self._year, self._month, int(button_id[4:])))
|
|
140
|
+
|
|
141
|
+
def action_cancel(self) -> None:
|
|
142
|
+
"""Close the calendar without returning a date."""
|
|
143
|
+
self.dismiss(None)
|
|
144
|
+
|
|
145
|
+
def action_step_day(self, delta: int) -> None:
|
|
146
|
+
"""Move focus by delta days within the shown month, if possible.
|
|
147
|
+
|
|
148
|
+
The arrow keys step one day left or right and one week up or
|
|
149
|
+
down. A step off the month, or onto a disabled day, is ignored,
|
|
150
|
+
so the focus stays on a selectable day of the shown month.
|
|
151
|
+
"""
|
|
152
|
+
current = self._focused_day()
|
|
153
|
+
if current is not None:
|
|
154
|
+
self._focus_day(current + delta)
|
|
155
|
+
|
|
156
|
+
def _focus_start_day(self) -> None:
|
|
157
|
+
"""Focus the seed day, or the nearest enabled day of the month."""
|
|
158
|
+
day = self._nearest_enabled(self._seed_day)
|
|
159
|
+
if day is not None:
|
|
160
|
+
self._focus_day(day)
|
|
161
|
+
|
|
162
|
+
def _focused_day(self) -> Optional[int]:
|
|
163
|
+
"""Return the day number of the focused day button, or None."""
|
|
164
|
+
focused = self.focused
|
|
165
|
+
if isinstance(focused, Button) and focused.id is not None \
|
|
166
|
+
and focused.id.startswith('day_'):
|
|
167
|
+
return int(focused.id[4:])
|
|
168
|
+
return None
|
|
169
|
+
|
|
170
|
+
def _focus_day(self, day: int) -> None:
|
|
171
|
+
"""Focus a day's button when it is in the month and enabled."""
|
|
172
|
+
last = calendar.monthrange(self._year, self._month)[1]
|
|
173
|
+
if 1 <= day <= last and not self._day_disabled(day):
|
|
174
|
+
self.query_one(f'#day_{day}', Button).focus()
|
|
175
|
+
|
|
176
|
+
def _nearest_enabled(self, target: int) -> Optional[int]:
|
|
177
|
+
"""Return the enabled day nearest target, or None when none are."""
|
|
178
|
+
last = calendar.monthrange(self._year, self._month)[1]
|
|
179
|
+
enabled = [day for day in range(1, last + 1)
|
|
180
|
+
if not self._day_disabled(day)]
|
|
181
|
+
if not enabled:
|
|
182
|
+
return None
|
|
183
|
+
return min(enabled, key=lambda day: abs(day - target))
|
|
@@ -0,0 +1,140 @@
|
|
|
1
|
+
#! /usr/local/bin/python3
|
|
2
|
+
"""Fake unsupported typed form fields as text fields.
|
|
3
|
+
|
|
4
|
+
A wizard may use the float, date, time, date-time or duration form
|
|
5
|
+
fields with a bridge that overrides ask_form() but was written before
|
|
6
|
+
those field types existed. Such a bridge reports through
|
|
7
|
+
supports_form_field() that it cannot show them. This module lets the
|
|
8
|
+
wizard still use one form: each unsupported field is shown as a text
|
|
9
|
+
field, a wrapping validator parses the text and guides the user to a
|
|
10
|
+
convertible value, and the text answers are converted back to the
|
|
11
|
+
requested typed answers.
|
|
12
|
+
|
|
13
|
+
The whole form is shown once by the bridge's own ask_form(), so the user
|
|
14
|
+
still sees and edits every field together. The parsing, formatting and
|
|
15
|
+
range messages are shared with the console and Textual forms through the
|
|
16
|
+
_wizard_ui_bridge_parse module, so the faked fields accept exactly the
|
|
17
|
+
same text.
|
|
18
|
+
"""
|
|
19
|
+
|
|
20
|
+
# Copyright (c) 2026 Tom Björkholm
|
|
21
|
+
# MIT License
|
|
22
|
+
|
|
23
|
+
from typing import Optional, Protocol
|
|
24
|
+
from wizard_ui_bridge.form_defs import AskField, AskFields, \
|
|
25
|
+
AnswerField, AnswerFields, AnswerTextField, PartialFormValidator, \
|
|
26
|
+
PartFormValidationResult, PrefillValues, PrefillValueType
|
|
27
|
+
from wizard_ui_bridge._parse import NEW_FIELD_TYPES, \
|
|
28
|
+
fake_field, format_new_value, new_answer, resolve_new
|
|
29
|
+
|
|
30
|
+
|
|
31
|
+
class _FakeableBridge(Protocol):
|
|
32
|
+
"""The bridge methods ask_form_faking() relies on."""
|
|
33
|
+
|
|
34
|
+
def supports_form_field(self, field: AskField) -> bool:
|
|
35
|
+
"""Return whether the bridge can show the field directly."""
|
|
36
|
+
|
|
37
|
+
def ask_form(self, long_question: str, ask_fields: AskFields, *,
|
|
38
|
+
re_ask_reason: Optional[str] = None,
|
|
39
|
+
partial_validator: Optional[PartialFormValidator] = None
|
|
40
|
+
) -> AnswerFields:
|
|
41
|
+
"""Show the whole form and return one answer per field."""
|
|
42
|
+
|
|
43
|
+
|
|
44
|
+
def ask_form_faking(bridge: _FakeableBridge, long_question: str,
|
|
45
|
+
ask_fields: AskFields, *, re_ask_reason: Optional[str],
|
|
46
|
+
partial_validator: Optional[PartialFormValidator]
|
|
47
|
+
) -> AnswerFields:
|
|
48
|
+
"""Show a form, faking the fields the bridge cannot show as text.
|
|
49
|
+
|
|
50
|
+
Raises RuntimeError when a field is unsupported and cannot be faked.
|
|
51
|
+
"""
|
|
52
|
+
fields = list(ask_fields)
|
|
53
|
+
plans = [_plan(bridge, field) for field in fields]
|
|
54
|
+
is_fake = [faked for _, faked in plans]
|
|
55
|
+
if not any(is_fake):
|
|
56
|
+
return bridge.ask_form(long_question, fields,
|
|
57
|
+
re_ask_reason=re_ask_reason,
|
|
58
|
+
partial_validator=partial_validator)
|
|
59
|
+
shown = [field for field, _ in plans]
|
|
60
|
+
validator = _wrap_validator(fields, is_fake, partial_validator)
|
|
61
|
+
answers = bridge.ask_form(long_question, shown,
|
|
62
|
+
re_ask_reason=re_ask_reason,
|
|
63
|
+
partial_validator=validator)
|
|
64
|
+
return [_real_answer(fields[index], is_fake[index], answers[index])
|
|
65
|
+
for index in range(len(fields))]
|
|
66
|
+
|
|
67
|
+
|
|
68
|
+
def _plan(bridge: _FakeableBridge, field: AskField) -> tuple[AskField, bool]:
|
|
69
|
+
"""Return the field to show and whether it is a faked text field."""
|
|
70
|
+
if bridge.supports_form_field(field):
|
|
71
|
+
return (field, False)
|
|
72
|
+
if isinstance(field, NEW_FIELD_TYPES):
|
|
73
|
+
faked = fake_field(field)
|
|
74
|
+
if bridge.supports_form_field(faked):
|
|
75
|
+
return (faked, True)
|
|
76
|
+
raise RuntimeError('the bridge cannot show a required form field type')
|
|
77
|
+
|
|
78
|
+
|
|
79
|
+
def _real_answer(field: AskField, is_fake: bool,
|
|
80
|
+
answer: AnswerField) -> AnswerField:
|
|
81
|
+
"""Return the answer of a field, converting a faked text answer."""
|
|
82
|
+
if not is_fake:
|
|
83
|
+
return answer
|
|
84
|
+
assert isinstance(answer, AnswerTextField)
|
|
85
|
+
value, _ = resolve_new(field, answer.value)
|
|
86
|
+
return new_answer(field, value)
|
|
87
|
+
|
|
88
|
+
|
|
89
|
+
def _wrap_validator(fields: list[AskField], is_fake: list[bool],
|
|
90
|
+
caller: Optional[PartialFormValidator]
|
|
91
|
+
) -> PartialFormValidator:
|
|
92
|
+
"""Return a validator over faked answers wrapping the caller's one.
|
|
93
|
+
|
|
94
|
+
It converts the faked text answers back to typed answers for the
|
|
95
|
+
caller, converts the caller's typed prefills to text for the faked
|
|
96
|
+
rows, and blocks submit while any enabled faked field holds text that
|
|
97
|
+
cannot be converted.
|
|
98
|
+
"""
|
|
99
|
+
def validator(answers: AnswerFields, changed: int
|
|
100
|
+
) -> PartFormValidationResult:
|
|
101
|
+
real = [_real_answer(fields[i], is_fake[i], answers[i])
|
|
102
|
+
for i in range(len(fields))]
|
|
103
|
+
base = PartFormValidationResult(True, '') if caller is None \
|
|
104
|
+
else caller(real, changed)
|
|
105
|
+
prefills = _convert_prefills(is_fake, base.prefill_values)
|
|
106
|
+
if not base.is_valid:
|
|
107
|
+
return PartFormValidationResult(False, base.message,
|
|
108
|
+
base.disable_row_idxs, prefills)
|
|
109
|
+
guide = _fake_guidance(fields, is_fake, answers,
|
|
110
|
+
set(base.disable_row_idxs))
|
|
111
|
+
return PartFormValidationResult(
|
|
112
|
+
guide is None, base.message if guide is None else guide,
|
|
113
|
+
base.disable_row_idxs, prefills)
|
|
114
|
+
return validator
|
|
115
|
+
|
|
116
|
+
|
|
117
|
+
def _convert_prefills(is_fake: list[bool],
|
|
118
|
+
prefills: PrefillValues) -> PrefillValues:
|
|
119
|
+
"""Return prefills with faked rows' typed values turned into text."""
|
|
120
|
+
converted: list[tuple[int, PrefillValueType]] = []
|
|
121
|
+
for index, value in prefills:
|
|
122
|
+
if 0 <= index < len(is_fake) and is_fake[index]:
|
|
123
|
+
converted.append((index, format_new_value(value)))
|
|
124
|
+
else:
|
|
125
|
+
converted.append((index, value))
|
|
126
|
+
return tuple(converted)
|
|
127
|
+
|
|
128
|
+
|
|
129
|
+
def _fake_guidance(fields: list[AskField], is_fake: list[bool],
|
|
130
|
+
answers: AnswerFields, disabled: set[int]) -> Optional[str]:
|
|
131
|
+
"""Return the first enabled faked field's parse error, or None."""
|
|
132
|
+
for index, field in enumerate(fields):
|
|
133
|
+
if not is_fake[index] or index in disabled:
|
|
134
|
+
continue
|
|
135
|
+
answer = answers[index]
|
|
136
|
+
assert isinstance(answer, AnswerTextField)
|
|
137
|
+
_, error = resolve_new(field, answer.value)
|
|
138
|
+
if error is not None:
|
|
139
|
+
return error
|
|
140
|
+
return None
|
|
@@ -0,0 +1,78 @@
|
|
|
1
|
+
#! /usr/local/bin/python3
|
|
2
|
+
"""Apply a partial validator's prefills to a Textual form's widgets.
|
|
3
|
+
|
|
4
|
+
The Textual form bridge asks the partial validator after every change and
|
|
5
|
+
then places the prefill values it returns into the matching field widgets,
|
|
6
|
+
exactly as if the user had typed them. This module holds that write-back,
|
|
7
|
+
kept apart from the large Textual bridge module.
|
|
8
|
+
"""
|
|
9
|
+
|
|
10
|
+
# Copyright (c) 2026 Tom Björkholm
|
|
11
|
+
# MIT License
|
|
12
|
+
|
|
13
|
+
from pathlib import Path
|
|
14
|
+
from typing import Sequence
|
|
15
|
+
from textual.dom import DOMNode
|
|
16
|
+
from textual.widgets import Checkbox, Input, Select, SelectionList
|
|
17
|
+
from wizard_ui_bridge.form_defs import AskField, \
|
|
18
|
+
AskTextField, AskIntField, AskPathField, AskYesNoField, AskChoiceField, \
|
|
19
|
+
AskMultiChoiceField, PrefillValues, PrefillValueType
|
|
20
|
+
from wizard_ui_bridge.form_helpers import valid_prefills
|
|
21
|
+
from wizard_ui_bridge._parse import NEW_FIELD_TYPES, \
|
|
22
|
+
format_new_value
|
|
23
|
+
|
|
24
|
+
|
|
25
|
+
def apply_prefills(form: DOMNode, fields: Sequence[AskField], changed: int,
|
|
26
|
+
prefill_values: PrefillValues) -> None:
|
|
27
|
+
"""Write each valid prefill into its row's widget in form.
|
|
28
|
+
|
|
29
|
+
A disabled row is written too, so the value shows greyed and takes
|
|
30
|
+
effect if the row is later enabled. Writing a value equal to the one
|
|
31
|
+
already there is a no-op, so a stable validator does not loop.
|
|
32
|
+
"""
|
|
33
|
+
for index, value in valid_prefills(fields, changed, prefill_values):
|
|
34
|
+
_set_field(form, fields[index], index, value)
|
|
35
|
+
|
|
36
|
+
|
|
37
|
+
def _set_field(form: DOMNode, field: AskField, index: int,
|
|
38
|
+
value: PrefillValueType) -> None:
|
|
39
|
+
"""Write a prefill value into one field's widget, by field type.
|
|
40
|
+
|
|
41
|
+
Setting the widget value raises the framework's change event, so the
|
|
42
|
+
answer, the disabled set and any own-field error refresh as if the
|
|
43
|
+
user had typed it, exactly like the directory picker write-back.
|
|
44
|
+
"""
|
|
45
|
+
widget_id = f'#field_{index}'
|
|
46
|
+
if isinstance(field, NEW_FIELD_TYPES):
|
|
47
|
+
form.query_one(widget_id, Input).value = format_new_value(value)
|
|
48
|
+
elif isinstance(field, AskTextField):
|
|
49
|
+
assert isinstance(value, str)
|
|
50
|
+
form.query_one(widget_id, Input).value = value
|
|
51
|
+
elif isinstance(field, AskIntField):
|
|
52
|
+
assert isinstance(value, int)
|
|
53
|
+
form.query_one(widget_id, Input).value = str(value)
|
|
54
|
+
elif isinstance(field, AskPathField):
|
|
55
|
+
assert isinstance(value, Path)
|
|
56
|
+
form.query_one(widget_id, Input).value = str(value)
|
|
57
|
+
elif isinstance(field, AskYesNoField):
|
|
58
|
+
assert isinstance(value, bool)
|
|
59
|
+
form.query_one(widget_id, Checkbox).value = value
|
|
60
|
+
elif isinstance(field, AskChoiceField):
|
|
61
|
+
assert isinstance(value, str)
|
|
62
|
+
form.query_one(widget_id, Select).value = value
|
|
63
|
+
else:
|
|
64
|
+
assert isinstance(field, AskMultiChoiceField)
|
|
65
|
+
assert isinstance(value, list)
|
|
66
|
+
_set_multi(form, index, field, value)
|
|
67
|
+
|
|
68
|
+
|
|
69
|
+
def _set_multi(form: DOMNode, index: int, field: AskMultiChoiceField,
|
|
70
|
+
members: Sequence[str]) -> None:
|
|
71
|
+
"""Select exactly the given members in a multi-choice widget."""
|
|
72
|
+
selection = form.query_one(f'#field_{index}', SelectionList)
|
|
73
|
+
wanted = {field.choices.index(member) for member in members}
|
|
74
|
+
current = set(selection.selected)
|
|
75
|
+
for value in wanted - current:
|
|
76
|
+
selection.select(value)
|
|
77
|
+
for value in current - wanted:
|
|
78
|
+
selection.deselect(value)
|