flexablelib-components 3.5.5__tar.gz → 3.6.0__tar.gz
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.
- {flexablelib_components-3.5.5/flexablelib_components.egg-info → flexablelib_components-3.6.0}/PKG-INFO +3 -3
- {flexablelib_components-3.5.5 → flexablelib_components-3.6.0}/flexablelib_components/__init__.py +10 -7
- {flexablelib_components-3.5.5 → flexablelib_components-3.6.0}/flexablelib_components/data.py +267 -25
- {flexablelib_components-3.5.5 → flexablelib_components-3.6.0}/flexablelib_components/dates.py +160 -1
- {flexablelib_components-3.5.5 → flexablelib_components-3.6.0}/flexablelib_components/inputs.py +272 -7
- {flexablelib_components-3.5.5 → flexablelib_components-3.6.0}/flexablelib_components/media.py +39 -11
- {flexablelib_components-3.5.5 → flexablelib_components-3.6.0}/flexablelib_components/navigation.py +232 -1
- {flexablelib_components-3.5.5 → flexablelib_components-3.6.0/flexablelib_components.egg-info}/PKG-INFO +3 -3
- flexablelib_components-3.6.0/flexablelib_components.egg-info/requires.txt +2 -0
- flexablelib_components-3.5.5/flexablelib_components.egg-info/requires.txt +0 -2
- {flexablelib_components-3.5.5 → flexablelib_components-3.6.0}/LICENSE +0 -0
- {flexablelib_components-3.5.5 → flexablelib_components-3.6.0}/MANIFEST.in +0 -0
- {flexablelib_components-3.5.5 → flexablelib_components-3.6.0}/README.md +0 -0
- {flexablelib_components-3.5.5 → flexablelib_components-3.6.0}/flexablelib_components/base.py +0 -0
- {flexablelib_components-3.5.5 → flexablelib_components-3.6.0}/flexablelib_components/display.py +0 -0
- {flexablelib_components-3.5.5 → flexablelib_components-3.6.0}/flexablelib_components/overlays.py +0 -0
- {flexablelib_components-3.5.5 → flexablelib_components-3.6.0}/flexablelib_components/py.typed +0 -0
- {flexablelib_components-3.5.5 → flexablelib_components-3.6.0}/flexablelib_components.egg-info/SOURCES.txt +0 -0
- {flexablelib_components-3.5.5 → flexablelib_components-3.6.0}/flexablelib_components.egg-info/dependency_links.txt +0 -0
- {flexablelib_components-3.5.5 → flexablelib_components-3.6.0}/flexablelib_components.egg-info/top_level.txt +0 -0
- {flexablelib_components-3.5.5 → flexablelib_components-3.6.0}/setup.cfg +0 -0
- {flexablelib_components-3.5.5 → flexablelib_components-3.6.0}/setup.py +0 -0
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
Metadata-Version: 2.4
|
|
2
2
|
Name: flexablelib-components
|
|
3
|
-
Version: 3.
|
|
3
|
+
Version: 3.6.0
|
|
4
4
|
Summary: Interactive terminal components for flexablelib: inputs, dates, tables, forms, menus, tabs, dialogs and more.
|
|
5
5
|
Home-page: https://github.com/Opus-Perpetuus/flexablelib
|
|
6
6
|
Author: Benjamin Ramirez
|
|
@@ -17,8 +17,8 @@ Classifier: Topic :: Software Development :: User Interfaces
|
|
|
17
17
|
Requires-Python: >=3.8
|
|
18
18
|
Description-Content-Type: text/markdown
|
|
19
19
|
License-File: LICENSE
|
|
20
|
-
Requires-Dist: flexablelib>=3.
|
|
21
|
-
Requires-Dist: flexablelib-tui>=3.
|
|
20
|
+
Requires-Dist: flexablelib>=3.6.0
|
|
21
|
+
Requires-Dist: flexablelib-tui>=3.6.0
|
|
22
22
|
Dynamic: author
|
|
23
23
|
Dynamic: author-email
|
|
24
24
|
Dynamic: classifier
|
{flexablelib_components-3.5.5 → flexablelib_components-3.6.0}/flexablelib_components/__init__.py
RENAMED
|
@@ -4,7 +4,8 @@ Interactive terminal components for flexablelib
|
|
|
4
4
|
|
|
5
5
|
Form inputs (text, password, numbers, arithmetic, money, masks, multi-line,
|
|
6
6
|
JSON, code scanners, checkboxes, switches, radio and checkbox groups, selects,
|
|
7
|
-
autocomplete, colours, icons, coordinates, files), dates
|
|
7
|
+
autocomplete, colours, icons, coordinates, files, signatures), dates, times
|
|
8
|
+
and stopwatches, display
|
|
8
9
|
pieces (badges, alerts, links, breadcrumbs, code, Markdown/HTML, timelines,
|
|
9
10
|
steppers, comments, stats, charts), navigation (tabs, menus, pagination,
|
|
10
11
|
sidebar, wizard, accordion, tree, command palette, split panes, app shell),
|
|
@@ -17,17 +18,18 @@ keys to the focused component) and also renders on its own with
|
|
|
17
18
|
``render(width)``. See docs/COMPONENTS.md.
|
|
18
19
|
"""
|
|
19
20
|
|
|
20
|
-
__version__ = '3.
|
|
21
|
+
__version__ = '3.6.0'
|
|
21
22
|
|
|
22
23
|
from .base import Theme, DEFAULT_THEME, Input, Box, Button, frame
|
|
23
24
|
from .inputs import (TextInput, PasswordInput, NumberInput, ExpressionInput,
|
|
24
25
|
MoneyInput, MaskedInput, MASKS, TextArea, JsonInput,
|
|
25
26
|
ScanInput, Checkbox, Switch, RadioGroup, CheckboxGroup,
|
|
26
27
|
Select, Autocomplete, ColorInput, IconPicker,
|
|
27
|
-
CoordinatesInput, FileInput,
|
|
28
|
+
CoordinatesInput, FileInput, SignatureInput,
|
|
29
|
+
evaluate_expression, ICONS)
|
|
28
30
|
from .dates import (Calendar, DateInput, TimeInput, DateTimeInput, WeekInput,
|
|
29
31
|
MonthInput, YearInput, WeekdayInput, DateRangeInput,
|
|
30
|
-
Timer)
|
|
32
|
+
Timer, Stopwatch)
|
|
31
33
|
from .display import (Badge, Tag, StatusBadge, Alert, Link, Breadcrumbs,
|
|
32
34
|
EmptyState, ErrorPanel, Spinner, Skeleton, Code,
|
|
33
35
|
MarkdownView, HtmlView, DetailView, Timeline, Stepper,
|
|
@@ -36,7 +38,7 @@ from .display import (Badge, Tag, StatusBadge, Alert, Link, Breadcrumbs,
|
|
|
36
38
|
from .navigation import (Tabs, Menu, ContextMenu, MenuButton, Pagination,
|
|
37
39
|
Sidebar, TopBar, Toolbar, Wizard, Accordion,
|
|
38
40
|
Carousel, Tree, CommandPalette, Split, Stack,
|
|
39
|
-
AppShell, SortControl)
|
|
41
|
+
VStack, AppShell, SortControl)
|
|
40
42
|
from .data import (DataTable, FilterBar, EditableTable, CatalogGrid, Form,
|
|
41
43
|
ValidationSummary, LoginForm, FilePreview, parse_query)
|
|
42
44
|
from .media import Image, ImageViewer, IMAGE_EXTENSIONS
|
|
@@ -49,16 +51,17 @@ __all__ = [
|
|
|
49
51
|
'MoneyInput', 'MaskedInput', 'MASKS', 'TextArea', 'JsonInput',
|
|
50
52
|
'ScanInput', 'Checkbox', 'Switch', 'RadioGroup', 'CheckboxGroup',
|
|
51
53
|
'Select', 'Autocomplete', 'ColorInput', 'IconPicker', 'CoordinatesInput',
|
|
52
|
-
'FileInput', 'evaluate_expression', 'ICONS',
|
|
54
|
+
'FileInput', 'SignatureInput', 'evaluate_expression', 'ICONS',
|
|
53
55
|
'Calendar', 'DateInput', 'TimeInput', 'DateTimeInput', 'WeekInput',
|
|
54
56
|
'MonthInput', 'YearInput', 'WeekdayInput', 'DateRangeInput', 'Timer',
|
|
57
|
+
'Stopwatch',
|
|
55
58
|
'Badge', 'Tag', 'StatusBadge', 'Alert', 'Link', 'Breadcrumbs',
|
|
56
59
|
'EmptyState', 'ErrorPanel', 'Spinner', 'Skeleton', 'Code',
|
|
57
60
|
'MarkdownView', 'HtmlView', 'DetailView', 'Timeline', 'Stepper',
|
|
58
61
|
'CommentList', 'AttachmentList', 'Stat', 'LineChart', 'human_size',
|
|
59
62
|
'Tabs', 'Menu', 'ContextMenu', 'MenuButton', 'Pagination', 'Sidebar',
|
|
60
63
|
'TopBar', 'Toolbar', 'Wizard', 'Accordion', 'Carousel', 'Tree',
|
|
61
|
-
'CommandPalette', 'Split', 'Stack', 'AppShell', 'SortControl',
|
|
64
|
+
'CommandPalette', 'Split', 'Stack', 'VStack', 'AppShell', 'SortControl',
|
|
62
65
|
'DataTable', 'FilterBar', 'EditableTable', 'CatalogGrid', 'Form',
|
|
63
66
|
'ValidationSummary', 'LoginForm', 'FilePreview', 'parse_query',
|
|
64
67
|
'Modal', 'ConfirmDialog', 'PromptDialog', 'LoadingOverlay', 'Popover',
|
{flexablelib_components-3.5.5 → flexablelib_components-3.6.0}/flexablelib_components/data.py
RENAMED
|
@@ -406,8 +406,16 @@ class DataTable(_Themed):
|
|
|
406
406
|
self.top = self.cursor_row - rows_h + 1
|
|
407
407
|
shown = view[self.top:self.top + rows_h]
|
|
408
408
|
if not view:
|
|
409
|
-
|
|
410
|
-
|
|
409
|
+
if self.focused:
|
|
410
|
+
# Focus on an empty table: a marker and reverse video, not
|
|
411
|
+
# only the accent colour of the rule above.
|
|
412
|
+
mark = '▸ ' if self._active() else '> '
|
|
413
|
+
text = _fx.fit_line(mark + self.empty, width, 'c')
|
|
414
|
+
out.append(self.paint(text, 'reverse') if self._active()
|
|
415
|
+
else text)
|
|
416
|
+
else:
|
|
417
|
+
out.append(self.paint(_fx.fit_line(self.empty, width, 'c'),
|
|
418
|
+
self.theme.muted))
|
|
411
419
|
for n, i in enumerate(shown):
|
|
412
420
|
row = self.rows[i]
|
|
413
421
|
pick = (lambda x, n=n: self._click_row(self.top + n, x))
|
|
@@ -559,18 +567,35 @@ class EditableTable(DataTable):
|
|
|
559
567
|
A :class:`DataTable` whose cells are edited in place: Left/Right choose
|
|
560
568
|
the cell, Enter edits it (Enter saves, Escape cancels), Ctrl-N adds a
|
|
561
569
|
row, Ctrl-D deletes the current one. Column ``type`` ``'number'`` keeps
|
|
562
|
-
numbers. ``on_edit(row, key, value)`` runs after a change.
|
|
570
|
+
numbers. ``on_edit(row, key, value)`` runs after a change. With a
|
|
571
|
+
``name`` the table is a field of the :class:`Form` around it (also
|
|
572
|
+
inside containers): its ``value`` -- a copy of the rows -- goes into
|
|
573
|
+
``Form.values()`` under that name.
|
|
563
574
|
"""
|
|
564
575
|
|
|
565
|
-
|
|
576
|
+
form_field = True
|
|
577
|
+
|
|
578
|
+
def __init__(self, columns, rows=(), on_edit=None, name=None, **kwargs):
|
|
566
579
|
super(EditableTable, self).__init__(columns, rows, **kwargs)
|
|
567
580
|
self.on_edit = on_edit
|
|
581
|
+
self.name = name
|
|
568
582
|
self.cursor_col = 0
|
|
569
583
|
self.editor = None
|
|
570
584
|
|
|
571
585
|
def children(self):
|
|
572
586
|
return []
|
|
573
587
|
|
|
588
|
+
@property
|
|
589
|
+
def value(self):
|
|
590
|
+
"""The rows (a copy: each row a new dict or list)."""
|
|
591
|
+
return [dict(r) if isinstance(r, dict) else list(r)
|
|
592
|
+
for r in self.rows]
|
|
593
|
+
|
|
594
|
+
@value.setter
|
|
595
|
+
def value(self, rows):
|
|
596
|
+
self.rows = list(rows or [])
|
|
597
|
+
self.invalidate()
|
|
598
|
+
|
|
574
599
|
def _set(self, row, ci, value):
|
|
575
600
|
column = self.columns[ci]
|
|
576
601
|
if column.get('type') == 'number':
|
|
@@ -693,8 +718,15 @@ class EditableTable(DataTable):
|
|
|
693
718
|
class CatalogGrid(_Themed):
|
|
694
719
|
"""
|
|
695
720
|
Items as cards in a grid that reflows with the width: dicts with
|
|
696
|
-
``title``, ``subtitle``, ``price``, ``badge
|
|
697
|
-
|
|
721
|
+
``title``, ``subtitle``, ``price``, ``badge``, ``fields`` and
|
|
722
|
+
``image`` (a path, URL, bytes or bitmap; ``image_alt`` its text
|
|
723
|
+
alternative, the title by default). Arrows move, Enter (or a click on
|
|
724
|
+
the current card) selects: ``selected`` / ``value`` is the item and
|
|
725
|
+
``on_select(item)`` runs. Cards with pictures get ``image_height``
|
|
726
|
+
rows for them (6 by default when any item has one), drawn with
|
|
727
|
+
``image_method`` (see :class:`Image`); ``image_headers`` go with URL
|
|
728
|
+
downloads (e.g. an ``Authorization`` token). The current card has a
|
|
729
|
+
heavy border and a ``▸`` marker, not only a colour.
|
|
698
730
|
"""
|
|
699
731
|
|
|
700
732
|
focusable = True
|
|
@@ -712,21 +744,64 @@ class CatalogGrid(_Themed):
|
|
|
712
744
|
return text
|
|
713
745
|
|
|
714
746
|
def _click(self, i):
|
|
715
|
-
if i == self.index
|
|
716
|
-
self.
|
|
747
|
+
if i == self.index:
|
|
748
|
+
self.select(i)
|
|
717
749
|
self.index = i
|
|
718
750
|
return True
|
|
719
751
|
|
|
720
752
|
def __init__(self, items, min_width=24, on_select=None, card_height=6,
|
|
753
|
+
image_height=None, image_method=None, image_headers=None,
|
|
721
754
|
**kwargs):
|
|
722
755
|
super(CatalogGrid, self).__init__(**kwargs)
|
|
723
756
|
self.items = list(items)
|
|
724
757
|
self.min_width = min_width
|
|
725
758
|
self.on_select = on_select
|
|
726
759
|
self.card_height = card_height
|
|
760
|
+
self.image_height = image_height
|
|
761
|
+
self.image_method = image_method
|
|
762
|
+
self.image_headers = image_headers
|
|
763
|
+
self.selected = None
|
|
727
764
|
self.index = 0
|
|
728
765
|
self.top_row = 0
|
|
729
766
|
self._columns = 1
|
|
767
|
+
self._images = {}
|
|
768
|
+
|
|
769
|
+
@property
|
|
770
|
+
def value(self):
|
|
771
|
+
return self.selected
|
|
772
|
+
|
|
773
|
+
def select(self, i=None):
|
|
774
|
+
"""Select item ``i`` (default: the current one)."""
|
|
775
|
+
if not self.items:
|
|
776
|
+
return False
|
|
777
|
+
if i is not None:
|
|
778
|
+
self.index = max(0, min(i, len(self.items) - 1))
|
|
779
|
+
self.selected = self.items[self.index]
|
|
780
|
+
if self.on_select is not None:
|
|
781
|
+
self.on_select(self.selected)
|
|
782
|
+
self.refresh()
|
|
783
|
+
return True
|
|
784
|
+
|
|
785
|
+
def _picture_rows(self):
|
|
786
|
+
if not any(item.get('image') is not None for item in self.items):
|
|
787
|
+
return 0
|
|
788
|
+
return 6 if self.image_height is None else max(0, self.image_height)
|
|
789
|
+
|
|
790
|
+
def _picture(self, item, width, rows):
|
|
791
|
+
source = item.get('image')
|
|
792
|
+
key = id(item)
|
|
793
|
+
cached = self._images.get(key)
|
|
794
|
+
if cached is None or cached[0] is not source:
|
|
795
|
+
from .media import Image
|
|
796
|
+
img = Image(source, alt=item.get('image_alt') or
|
|
797
|
+
item.get('title'), method=self.image_method,
|
|
798
|
+
headers=self.image_headers, theme=self._theme,
|
|
799
|
+
use_colors=self.use_colors)
|
|
800
|
+
cached = self._images[key] = (source, img)
|
|
801
|
+
img = cached[1]
|
|
802
|
+
img.app = self.app
|
|
803
|
+
lines = img.render(width, rows).split('\n')
|
|
804
|
+
return lines[:rows] + [''] * (rows - len(lines))
|
|
730
805
|
|
|
731
806
|
def natural_width(self):
|
|
732
807
|
return self.min_width * 3 + 2
|
|
@@ -738,8 +813,8 @@ class CatalogGrid(_Themed):
|
|
|
738
813
|
'down': self._columns}
|
|
739
814
|
if k in moves and n:
|
|
740
815
|
self.index = max(0, min(n - 1, self.index + moves[k]))
|
|
741
|
-
elif k == 'enter' and n
|
|
742
|
-
self.
|
|
816
|
+
elif k == 'enter' and n:
|
|
817
|
+
self.select()
|
|
743
818
|
elif k == 'home':
|
|
744
819
|
self.index = 0
|
|
745
820
|
elif k == 'end':
|
|
@@ -762,8 +837,14 @@ class CatalogGrid(_Themed):
|
|
|
762
837
|
self.paint(' ' + str(badge) + ' ', 'black on ' +
|
|
763
838
|
self.theme.warning) if self._active() else \
|
|
764
839
|
head + ' [' + str(badge) + ']'
|
|
765
|
-
if selected
|
|
840
|
+
if selected:
|
|
766
841
|
head = ('▸ ' if self._active() else '> ') + head
|
|
842
|
+
pic_rows = self._picture_rows()
|
|
843
|
+
if pic_rows:
|
|
844
|
+
if item.get('image') is not None:
|
|
845
|
+
lines.extend(self._picture(item, inner, pic_rows))
|
|
846
|
+
else:
|
|
847
|
+
lines.extend([''] * pic_rows)
|
|
767
848
|
lines.append(head)
|
|
768
849
|
if item.get('subtitle'):
|
|
769
850
|
lines.append(self.paint(_fx.truncate(str(item['subtitle']), inner,
|
|
@@ -776,19 +857,23 @@ class CatalogGrid(_Themed):
|
|
|
776
857
|
text = '${0:,.2f}'.format(price) if isinstance(price, (int, float)) \
|
|
777
858
|
else str(price)
|
|
778
859
|
lines.append(self.paint(text, 'bold ' + self.theme.success))
|
|
779
|
-
rows = self.
|
|
860
|
+
rows = self._card_rows() - 2
|
|
780
861
|
lines = lines[:rows] + [''] * (rows - len(lines))
|
|
781
862
|
color = self.theme.accent if selected else self.theme.border
|
|
782
863
|
return frame([' ' + l for l in lines], width, None, color,
|
|
783
864
|
self.paint, style='heavy' if selected else 'rounded')
|
|
784
865
|
|
|
866
|
+
def _card_rows(self):
|
|
867
|
+
return self.card_height + self._picture_rows()
|
|
868
|
+
|
|
785
869
|
def draw(self, width, height):
|
|
870
|
+
card_rows = self._card_rows()
|
|
786
871
|
cols = max(1, (width + 1) // (self.min_width + 1))
|
|
787
872
|
self._columns = cols
|
|
788
873
|
card_w = (width - (cols - 1)) // cols
|
|
789
874
|
n_rows = int(math.ceil(len(self.items) / float(cols)))
|
|
790
875
|
visible_rows = n_rows if not height else max(1, height //
|
|
791
|
-
|
|
876
|
+
card_rows)
|
|
792
877
|
row_of = self.index // cols
|
|
793
878
|
if row_of < self.top_row:
|
|
794
879
|
self.top_row = row_of
|
|
@@ -804,7 +889,7 @@ class CatalogGrid(_Themed):
|
|
|
804
889
|
break
|
|
805
890
|
blocks.append(self._card(self.items[i], card_w,
|
|
806
891
|
self.focused and i == self.index))
|
|
807
|
-
for k in range(
|
|
892
|
+
for k in range(card_rows):
|
|
808
893
|
self.hot(len(out) + k, lambda i=i: self._click(i),
|
|
809
894
|
c * (card_w + 1), c * (card_w + 1) + card_w)
|
|
810
895
|
out.extend(join_columns(blocks, [card_w] * len(blocks)))
|
|
@@ -813,8 +898,41 @@ class CatalogGrid(_Themed):
|
|
|
813
898
|
return out
|
|
814
899
|
|
|
815
900
|
|
|
901
|
+
def _error_entries(errors):
|
|
902
|
+
"""``[(field or None, message)]`` from a dict, a list of messages,
|
|
903
|
+
``(field, message)`` pairs, dicts with ``field`` / ``message`` or
|
|
904
|
+
exceptions."""
|
|
905
|
+
if not errors:
|
|
906
|
+
return []
|
|
907
|
+
if isinstance(errors, dict):
|
|
908
|
+
return [(f, str(m)) for f, m in errors.items()]
|
|
909
|
+
if isinstance(errors, str):
|
|
910
|
+
return [(None, errors)]
|
|
911
|
+
out = []
|
|
912
|
+
for item in errors:
|
|
913
|
+
if isinstance(item, dict):
|
|
914
|
+
field = item.get('field', item.get('name'))
|
|
915
|
+
message = item.get('message', item.get('error', ''))
|
|
916
|
+
out.append((field, str(message)))
|
|
917
|
+
elif isinstance(item, (tuple, list)) and len(item) == 2:
|
|
918
|
+
out.append((item[0], str(item[1])))
|
|
919
|
+
else:
|
|
920
|
+
out.append((None, str(item)))
|
|
921
|
+
return out
|
|
922
|
+
|
|
923
|
+
|
|
816
924
|
class ValidationSummary(_Themed):
|
|
817
|
-
"""
|
|
925
|
+
"""
|
|
926
|
+
The list of errors of a form. ``errors``: a ``{field: message}`` dict or
|
|
927
|
+
a list -- of messages, ``(field, message)`` pairs, dicts with ``field``
|
|
928
|
+
and ``message`` (or ``name`` / ``error``) or exceptions. With
|
|
929
|
+
``fields`` (a :class:`Form` or a list of inputs) or ``on_select`` the
|
|
930
|
+
summary takes the focus: Up/Down choose an error and Enter (or a click)
|
|
931
|
+
moves the focus to its field (found by ``name`` or ``label``) and calls
|
|
932
|
+
``on_select(field, input)`` (``input`` None when not found). The
|
|
933
|
+
chosen error is shown with ``▸`` (``>`` without colour) as well as in
|
|
934
|
+
reverse video.
|
|
935
|
+
"""
|
|
818
936
|
|
|
819
937
|
role = 'alert'
|
|
820
938
|
|
|
@@ -822,20 +940,108 @@ class ValidationSummary(_Themed):
|
|
|
822
940
|
return self.a11y_label or self.title
|
|
823
941
|
|
|
824
942
|
def a11y_value(self):
|
|
825
|
-
return '; '.join('{0}: {1}'.format(f, m)
|
|
826
|
-
for f, m in self.
|
|
943
|
+
return '; '.join('{0}: {1}'.format(f, m) if f is not None else m
|
|
944
|
+
for f, m in self.entries)
|
|
827
945
|
|
|
828
|
-
def __init__(self, errors=None, title='Revisa estos campos',
|
|
946
|
+
def __init__(self, errors=None, title='Revisa estos campos',
|
|
947
|
+
fields=None, on_select=None, **kwargs):
|
|
829
948
|
super(ValidationSummary, self).__init__(**kwargs)
|
|
830
|
-
self.errors = dict(errors or {})
|
|
831
949
|
self.title = title
|
|
950
|
+
self.fields = fields
|
|
951
|
+
self.on_select = on_select
|
|
952
|
+
self.index = 0
|
|
953
|
+
self.errors = errors
|
|
954
|
+
|
|
955
|
+
@property
|
|
956
|
+
def errors(self):
|
|
957
|
+
"""``{field: message}`` of the errors tied to a field."""
|
|
958
|
+
return dict((f, m) for f, m in self.entries if f is not None)
|
|
959
|
+
|
|
960
|
+
@errors.setter
|
|
961
|
+
def errors(self, value):
|
|
962
|
+
self.entries = _error_entries(value)
|
|
963
|
+
self.index = max(0, min(getattr(self, 'index', 0),
|
|
964
|
+
len(self.entries) - 1))
|
|
965
|
+
|
|
966
|
+
@property
|
|
967
|
+
def messages(self):
|
|
968
|
+
"""Every message, in order."""
|
|
969
|
+
return [m for f, m in self.entries]
|
|
970
|
+
|
|
971
|
+
@property
|
|
972
|
+
def focusable(self):
|
|
973
|
+
return bool(self.entries) and (self.fields is not None or
|
|
974
|
+
self.on_select is not None)
|
|
975
|
+
|
|
976
|
+
def _inputs(self):
|
|
977
|
+
fields = self.fields
|
|
978
|
+
if fields is None:
|
|
979
|
+
return []
|
|
980
|
+
if hasattr(fields, 'fields') and callable(fields.fields):
|
|
981
|
+
return list(fields.fields())
|
|
982
|
+
return list(fields)
|
|
983
|
+
|
|
984
|
+
def find(self, field):
|
|
985
|
+
"""The input for ``field`` (by ``name``, then ``label``) or None."""
|
|
986
|
+
if field is None:
|
|
987
|
+
return None
|
|
988
|
+
for f in self._inputs():
|
|
989
|
+
if getattr(f, 'name', None) == field:
|
|
990
|
+
return f
|
|
991
|
+
for f in self._inputs():
|
|
992
|
+
if getattr(f, 'label', None) == field:
|
|
993
|
+
return f
|
|
994
|
+
return None
|
|
995
|
+
|
|
996
|
+
def activate(self, i=None):
|
|
997
|
+
"""Go to the field of error ``i`` (default: the current one)."""
|
|
998
|
+
if not self.entries:
|
|
999
|
+
return False
|
|
1000
|
+
if i is not None:
|
|
1001
|
+
self.index = max(0, min(i, len(self.entries) - 1))
|
|
1002
|
+
field = self.entries[self.index][0]
|
|
1003
|
+
target = self.find(field)
|
|
1004
|
+
if target is not None and self.app is not None:
|
|
1005
|
+
self.app.focus(target)
|
|
1006
|
+
if self.on_select is not None:
|
|
1007
|
+
self.on_select(field, target)
|
|
1008
|
+
self.refresh()
|
|
1009
|
+
return True
|
|
1010
|
+
|
|
1011
|
+
def on_key(self, key):
|
|
1012
|
+
k = str(key)
|
|
1013
|
+
n = len(self.entries)
|
|
1014
|
+
if not n:
|
|
1015
|
+
return False
|
|
1016
|
+
if k in ('up', 'down'):
|
|
1017
|
+
step = 1 if k == 'down' else -1
|
|
1018
|
+
self.index = max(0, min(n - 1, self.index + step))
|
|
1019
|
+
elif k == 'home':
|
|
1020
|
+
self.index = 0
|
|
1021
|
+
elif k == 'end':
|
|
1022
|
+
self.index = n - 1
|
|
1023
|
+
elif k in ('enter', 'space'):
|
|
1024
|
+
return self.activate()
|
|
1025
|
+
else:
|
|
1026
|
+
return False
|
|
1027
|
+
self.refresh()
|
|
1028
|
+
return True
|
|
832
1029
|
|
|
833
1030
|
def draw(self, width, height):
|
|
834
|
-
if not self.
|
|
1031
|
+
if not self.entries:
|
|
835
1032
|
return []
|
|
836
1033
|
lines = [self.paint('✖ ' + self.title, 'bold ' + self.theme.error)]
|
|
837
|
-
for field, message in self.
|
|
838
|
-
|
|
1034
|
+
for i, (field, message) in enumerate(self.entries):
|
|
1035
|
+
text = '{0}: {1}'.format(field, message) if field is not None \
|
|
1036
|
+
else message
|
|
1037
|
+
if self.focused and i == self.index:
|
|
1038
|
+
mark = '▸ ' if self._active() else '> '
|
|
1039
|
+
line = ' ' + mark + text
|
|
1040
|
+
line = self.paint(line, 'reverse') if self._active() else line
|
|
1041
|
+
else:
|
|
1042
|
+
line = ' • ' + text
|
|
1043
|
+
self.hot(len(lines) + 1, lambda i=i: self.activate(i))
|
|
1044
|
+
lines.append(line)
|
|
839
1045
|
return frame([' ' + l for l in lines], width, None, self.theme.error,
|
|
840
1046
|
self.paint)
|
|
841
1047
|
|
|
@@ -847,7 +1053,10 @@ class Form(_Themed):
|
|
|
847
1053
|
tuples of inputs for one row. Enter in a one-line field moves to the
|
|
848
1054
|
next; Ctrl-S (or the submit button) validates and calls
|
|
849
1055
|
``on_submit(values)``; Escape calls ``on_cancel()``. ``values()`` is the
|
|
850
|
-
``{name: value}`` dict
|
|
1056
|
+
``{name: value}`` dict -- every named input, also those inside
|
|
1057
|
+
containers (:class:`Stack`, :class:`VStack`, :class:`Tabs`, grids,
|
|
1058
|
+
cards...), and the rows of a named :class:`EditableTable`; ``errors``
|
|
1059
|
+
the last validation.
|
|
851
1060
|
"""
|
|
852
1061
|
|
|
853
1062
|
role = 'form'
|
|
@@ -897,8 +1106,40 @@ class Form(_Themed):
|
|
|
897
1106
|
self.app.focus_next()
|
|
898
1107
|
return advance
|
|
899
1108
|
|
|
1109
|
+
def _collect(self, node, out, depth=0):
|
|
1110
|
+
"""Inputs and named ``form_field`` components inside ``node``,
|
|
1111
|
+
through containers (stacks, tabs, grids, cards...)."""
|
|
1112
|
+
from flexablelib_tui.app import _child_nodes
|
|
1113
|
+
if depth > 64:
|
|
1114
|
+
return
|
|
1115
|
+
kids = node.form_children() if hasattr(node, 'form_children') \
|
|
1116
|
+
else _child_nodes(node)
|
|
1117
|
+
for child in kids:
|
|
1118
|
+
if isinstance(child, Input) or getattr(child, 'form_field',
|
|
1119
|
+
False):
|
|
1120
|
+
out.append(child)
|
|
1121
|
+
elif not isinstance(child, (Button, str)):
|
|
1122
|
+
self._collect(child, out, depth + 1)
|
|
1123
|
+
|
|
1124
|
+
def form_nodes(self):
|
|
1125
|
+
"""Every field of the form, nested ones included -- also those in
|
|
1126
|
+
hidden tabs, other wizard steps and closed accordion sections
|
|
1127
|
+
(containers list them in ``form_children()``)."""
|
|
1128
|
+
out = []
|
|
1129
|
+
for row in self.rows:
|
|
1130
|
+
for item in row:
|
|
1131
|
+
if isinstance(item, str):
|
|
1132
|
+
continue
|
|
1133
|
+
if isinstance(item, Input) or getattr(item, 'form_field',
|
|
1134
|
+
False):
|
|
1135
|
+
out.append(item)
|
|
1136
|
+
else:
|
|
1137
|
+
self._collect(item, out)
|
|
1138
|
+
return out
|
|
1139
|
+
|
|
900
1140
|
def fields(self):
|
|
901
|
-
|
|
1141
|
+
"""The inputs of the form, also those inside containers."""
|
|
1142
|
+
return [f for f in self.form_nodes() if isinstance(f, Input)]
|
|
902
1143
|
|
|
903
1144
|
def children(self):
|
|
904
1145
|
kids = [f for row in self.rows for f in row if not isinstance(f, str)]
|
|
@@ -912,7 +1153,8 @@ class Form(_Themed):
|
|
|
912
1153
|
return 60 if self.columns == 1 else 90
|
|
913
1154
|
|
|
914
1155
|
def values(self):
|
|
915
|
-
return {f.name: f.value for f in self.
|
|
1156
|
+
return {f.name: f.value for f in self.form_nodes()
|
|
1157
|
+
if getattr(f, 'name', None)}
|
|
916
1158
|
|
|
917
1159
|
def validate(self):
|
|
918
1160
|
self.errors = {}
|
{flexablelib_components-3.5.5 → flexablelib_components-3.6.0}/flexablelib_components/dates.py
RENAMED
|
@@ -4,6 +4,7 @@ month, year and weekday pickers, date ranges with presets, and a timer.
|
|
|
4
4
|
"""
|
|
5
5
|
|
|
6
6
|
import calendar as _calendar
|
|
7
|
+
import math
|
|
7
8
|
import datetime as _dt
|
|
8
9
|
import time
|
|
9
10
|
|
|
@@ -17,7 +18,7 @@ _ENTER = Key('enter')
|
|
|
17
18
|
|
|
18
19
|
__all__ = ['Calendar', 'DateInput', 'TimeInput', 'DateTimeInput',
|
|
19
20
|
'WeekInput', 'MonthInput', 'YearInput', 'WeekdayInput',
|
|
20
|
-
'DateRangeInput', 'Timer', 'LOCALES']
|
|
21
|
+
'DateRangeInput', 'Timer', 'Stopwatch', 'LOCALES']
|
|
21
22
|
|
|
22
23
|
LOCALES = {
|
|
23
24
|
'es': {
|
|
@@ -966,3 +967,161 @@ class Timer(_Themed):
|
|
|
966
967
|
else 'iniciar') + ' · r',
|
|
967
968
|
self.theme.muted)
|
|
968
969
|
return [text]
|
|
970
|
+
|
|
971
|
+
|
|
972
|
+
class Stopwatch(Input):
|
|
973
|
+
"""
|
|
974
|
+
A stopwatch for forms: Space (or Enter) starts and stops it, ``l``
|
|
975
|
+
records a lap, ``r`` resets. ``value`` is the elapsed time as a
|
|
976
|
+
:class:`datetime.timedelta` (live while it runs); setting it (a
|
|
977
|
+
``timedelta`` or seconds) stops the watch at that time. ``laps`` are the
|
|
978
|
+
split times (``timedelta``). :meth:`start`, :meth:`stop`,
|
|
979
|
+
:meth:`toggle`, :meth:`lap` and :meth:`reset` do the same from code;
|
|
980
|
+
``on_lap(split)`` runs on each lap and ``on_change(value)`` when it
|
|
981
|
+
stops or resets. ``clock`` returns seconds (``time.monotonic``).
|
|
982
|
+
``precision`` is the number of decimals of the seconds shown (0-3).
|
|
983
|
+
"""
|
|
984
|
+
|
|
985
|
+
role = 'timer'
|
|
986
|
+
|
|
987
|
+
def __init__(self, label=None, value=None, clock=time.monotonic,
|
|
988
|
+
on_lap=None, precision=1, max_laps=None, **kwargs):
|
|
989
|
+
self.clock = clock
|
|
990
|
+
self.on_lap = on_lap
|
|
991
|
+
self.precision = max(0, min(3, int(precision)))
|
|
992
|
+
self.max_laps = max_laps
|
|
993
|
+
self.laps = []
|
|
994
|
+
self._accum = 0.0
|
|
995
|
+
self._since = None
|
|
996
|
+
super(Stopwatch, self).__init__(label=label, value=value, **kwargs)
|
|
997
|
+
|
|
998
|
+
# -- value ----------------------------------------------------------------
|
|
999
|
+
|
|
1000
|
+
@property
|
|
1001
|
+
def value(self):
|
|
1002
|
+
return _dt.timedelta(seconds=self.elapsed())
|
|
1003
|
+
|
|
1004
|
+
@value.setter
|
|
1005
|
+
def value(self, new):
|
|
1006
|
+
if isinstance(new, _dt.timedelta):
|
|
1007
|
+
seconds = new.total_seconds()
|
|
1008
|
+
else:
|
|
1009
|
+
seconds = float(new or 0)
|
|
1010
|
+
self._accum = max(0.0, seconds)
|
|
1011
|
+
self._since = None
|
|
1012
|
+
|
|
1013
|
+
def is_empty(self):
|
|
1014
|
+
return not self.running and self._accum == 0.0
|
|
1015
|
+
|
|
1016
|
+
@property
|
|
1017
|
+
def running(self):
|
|
1018
|
+
return self._since is not None
|
|
1019
|
+
|
|
1020
|
+
def elapsed(self):
|
|
1021
|
+
"""Seconds elapsed."""
|
|
1022
|
+
extra = self.clock() - self._since if self._since is not None \
|
|
1023
|
+
else 0.0
|
|
1024
|
+
return self._accum + extra
|
|
1025
|
+
|
|
1026
|
+
# -- control --------------------------------------------------------------
|
|
1027
|
+
|
|
1028
|
+
def start(self):
|
|
1029
|
+
if self._since is None:
|
|
1030
|
+
self._since = self.clock()
|
|
1031
|
+
self.error = None
|
|
1032
|
+
self.refresh()
|
|
1033
|
+
return True
|
|
1034
|
+
|
|
1035
|
+
def stop(self):
|
|
1036
|
+
if self._since is not None:
|
|
1037
|
+
self._accum += self.clock() - self._since
|
|
1038
|
+
self._since = None
|
|
1039
|
+
if self.on_change is not None:
|
|
1040
|
+
self.on_change(self.value)
|
|
1041
|
+
self.refresh()
|
|
1042
|
+
return True
|
|
1043
|
+
|
|
1044
|
+
def toggle(self):
|
|
1045
|
+
return self.stop() if self.running else self.start()
|
|
1046
|
+
|
|
1047
|
+
def lap(self):
|
|
1048
|
+
"""Record the current time as a lap (only while running)."""
|
|
1049
|
+
if not self.running:
|
|
1050
|
+
return False
|
|
1051
|
+
split = self.value
|
|
1052
|
+
self.laps.append(split)
|
|
1053
|
+
if self.max_laps:
|
|
1054
|
+
del self.laps[:-int(self.max_laps)]
|
|
1055
|
+
if self.on_lap is not None:
|
|
1056
|
+
self.on_lap(split)
|
|
1057
|
+
self.refresh()
|
|
1058
|
+
return True
|
|
1059
|
+
|
|
1060
|
+
def reset(self):
|
|
1061
|
+
self._accum = 0.0
|
|
1062
|
+
self._since = self.clock() if self._since is not None else None
|
|
1063
|
+
self.laps = []
|
|
1064
|
+
if self.on_change is not None:
|
|
1065
|
+
self.on_change(self.value)
|
|
1066
|
+
self.refresh()
|
|
1067
|
+
return True
|
|
1068
|
+
|
|
1069
|
+
@staticmethod
|
|
1070
|
+
def format_duration(seconds, precision=1):
|
|
1071
|
+
"""``seconds`` as ``HH:MM:SS`` (with ``precision`` decimals)."""
|
|
1072
|
+
scale = 10 ** precision
|
|
1073
|
+
total = int(math.floor(max(0.0, seconds) * scale + 1e-9))
|
|
1074
|
+
whole, frac = divmod(total, scale)
|
|
1075
|
+
hours, rest = divmod(whole, 3600)
|
|
1076
|
+
minutes, secs = divmod(rest, 60)
|
|
1077
|
+
text = '{0:02d}:{1:02d}:{2:02d}'.format(hours, minutes, secs)
|
|
1078
|
+
if precision:
|
|
1079
|
+
text += '.{0:0{1}d}'.format(frac, precision)
|
|
1080
|
+
return text
|
|
1081
|
+
|
|
1082
|
+
def text(self):
|
|
1083
|
+
return self.format_duration(self.elapsed(), self.precision)
|
|
1084
|
+
|
|
1085
|
+
def a11y_value(self):
|
|
1086
|
+
text = '{0}, {1}'.format(self.text(), 'en marcha' if self.running
|
|
1087
|
+
else 'detenido')
|
|
1088
|
+
if self.laps:
|
|
1089
|
+
text += ', {0} vueltas'.format(len(self.laps))
|
|
1090
|
+
return text
|
|
1091
|
+
|
|
1092
|
+
def on_key(self, key):
|
|
1093
|
+
k = str(key)
|
|
1094
|
+
if k in ('space', 'enter'):
|
|
1095
|
+
return self.toggle()
|
|
1096
|
+
if k == 'l':
|
|
1097
|
+
self.lap()
|
|
1098
|
+
return True
|
|
1099
|
+
if k == 'r':
|
|
1100
|
+
return self.reset()
|
|
1101
|
+
return False
|
|
1102
|
+
|
|
1103
|
+
def on_mouse(self, event):
|
|
1104
|
+
if event.action == 'press' and event.button == 0:
|
|
1105
|
+
return self.toggle()
|
|
1106
|
+
return False
|
|
1107
|
+
|
|
1108
|
+
def natural_width(self):
|
|
1109
|
+
return max(Input.natural_width(self), 40)
|
|
1110
|
+
|
|
1111
|
+
def control(self, width, height):
|
|
1112
|
+
spec = self.theme.success if self.running else self.theme.muted
|
|
1113
|
+
state = '▶' if self.running else '■'
|
|
1114
|
+
if not self._active():
|
|
1115
|
+
state = '>' if self.running else '='
|
|
1116
|
+
line = self.marker() + ' ' + state + ' ' + \
|
|
1117
|
+
self.paint(self.text(), 'bold ' + spec)
|
|
1118
|
+
if self.focused:
|
|
1119
|
+
line += self.paint(' espacio: ' + ('parar' if self.running
|
|
1120
|
+
else 'iniciar') +
|
|
1121
|
+
' · l: vuelta · r: reiniciar',
|
|
1122
|
+
self.theme.muted)
|
|
1123
|
+
out = [line]
|
|
1124
|
+
for n, split in enumerate(self.laps[-5:], max(1, len(self.laps) - 4)):
|
|
1125
|
+
out.append(' {0:>2}. {1}'.format(n, self.format_duration(
|
|
1126
|
+
split.total_seconds(), self.precision)))
|
|
1127
|
+
return out
|