Skip to content

Commit 7f6c857

Browse files
committed
HidingCheckBox: normalize mapping for truth values
Necessary to hide stuff if the checkbox is unchecked. Allows using True and False as keys in mappings.
1 parent 697af9d commit 7f6c857

File tree

1 file changed

+32
-1
lines changed

1 file changed

+32
-1
lines changed

tw2/dynforms/widgets.py

Lines changed: 32 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -79,6 +79,35 @@ class HidingCheckBox(HidingComponentMixin, twf.CheckBox):
7979
__doc__ = HidingComponentMixin.__doc__.replace('$$', 'CheckBox')
8080
attrs = {'onclick': 'twd_hiding_onchange(this)'}
8181

82+
_falsevals = (0, False, 'false')
83+
_truevals = (1, True, 'true')
84+
_truthvals = _falsevals + _truevals
85+
86+
@classmethod
87+
def normalize_bool(cls, value):
88+
if value in cls._truevals:
89+
return cls._truevals[0]
90+
elif value in cls._falsevals:
91+
return cls._falsevals[0]
92+
else:
93+
raise ValueError("Can't normalize {!r} to boolean".format(value))
94+
95+
@classmethod
96+
def post_define(cls):
97+
if not hasattr(cls, 'mapping'):
98+
return
99+
new_mapping = {}
100+
for k, v in cls.mapping.items():
101+
if k not in cls._truthvals:
102+
raise twc.ParameterError(
103+
"mapping key for {} must be a truth value".format(cls))
104+
new_k = cls.normalize_bool(k)
105+
if new_k in new_mapping:
106+
raise twc.ParameterError(
107+
"duplicate normalited mapping key: {}".format(k))
108+
new_mapping[new_k] = v
109+
cls.mapping = new_mapping
110+
82111
class HidingSelectionList(HidingComponentMixin, twf.widgets.SelectionList):
83112
def prepare(self):
84113
super(HidingSelectionList, self).prepare()
@@ -119,7 +148,9 @@ def prepare(self):
119148
show = set()
120149
for c in self.children:
121150
if isinstance(c, HidingComponentMixin):
122-
if isinstance(c.value, list):
151+
if isinstance(c, HidingCheckBox):
152+
show.update(c.mapping.get(c.normalize_bool(c.value), []))
153+
elif isinstance(c.value, list):
123154
for v in c.value:
124155
show.update(c.mapping.get(v, []))
125156
else:

0 commit comments

Comments
 (0)