-
Notifications
You must be signed in to change notification settings - Fork 7
/
Copy pathListBox.py
139 lines (120 loc) · 4.27 KB
/
ListBox.py
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
from .ExamplePage import ExamplePage
debug = False
class ListBox(ExamplePage):
"""List box example.
This page provides a list box interface with controls
for changing its size and adding and removing items.
The source is a good example of how to use awake() and actions.
It also shows how to avoid repeated execution on refresh/reload.
"""
def awake(self, transaction):
ExamplePage.awake(self, transaction)
session = self.session()
if session.hasValue('vars'):
self._vars = session.value('vars')
else:
self._vars = {
'items': [], 'height': 10, 'width': 250,
'newCount': 1, 'formCount': 1
}
session.setValue('vars', self._vars)
self._error = None
def writeContent(self):
enc, wr = self.htmlEncode, self.writeln
wr('<div style="text-align:center">')
if debug:
wr(f'<p>fields = {enc(str(self.request().fields()))}</p>')
wr(f'<p>vars = {enc(str(self._vars))}</p>')
# Intro text is provided by our class' doc string:
intro = self.__class__.__doc__.strip().split('\n\n')
wr(f'<h2>{intro.pop(0)}</h2>')
for s in intro:
s = '<br>'.join(s.strip() for s in s.splitlines())
wr(f'<p>{s}</p>')
s = self._error or ' '
wr(f'<p style="color:red">{s}</p>')
wr('''
<form action="ListBox" method="post">
<input name="formCount" type="hidden" value="{formCount}">
<select multiple name="items" size="{height}"
style="width:{width}pt;text-align:center">
'''.format(**self._vars))
index = 0
for item in self._vars['items']:
name = enc(item['name'])
wr(f'<option value="{index}">{name}</option>')
index += 1
if not index:
wr('<option value="" disabled>--- empty ---</option>')
wr('''
</select>
<p>
<input name="_action_new" type="submit" value="New">
<input name="_action_delete" type="submit" value="Delete">
<input name="_action_taller" type="submit" value="Taller">
<input name="_action_shorter" type="submit" value="Shorter">
<input name="_action_wider" type="submit" value="Wider">
<input name="_action_narrower" type="submit" value="Narrower">
</p>
</form>
</div>
''')
@staticmethod
def heightChange():
return 1
@staticmethod
def widthChange():
return 30
# Commands
def new(self):
"""Add a new item to the list box."""
newCount = self._vars['newCount']
self._vars['items'].append({'name': f'New item {newCount}'})
self._vars['newCount'] += 1
self.writeBody()
def delete(self):
"""Delete the selected items in the list box."""
req = self.request()
if req.hasField('items'):
indices = req.field('items')
if not isinstance(indices, list):
indices = [indices]
try:
indices = list(map(int, indices)) # convert strings to ints
except ValueError:
indices = []
# remove the objects:
for index in sorted(indices, reverse=True):
del self._vars['items'][index]
else:
self._error = 'You must select a row to delete.'
self.writeBody()
def taller(self):
self._vars['height'] += self.heightChange()
self.writeBody()
def shorter(self):
if self._vars['height'] > 2:
self._vars['height'] -= self.heightChange()
self.writeBody()
def wider(self):
self._vars['width'] += self.widthChange()
self.writeBody()
def narrower(self):
if self._vars['width'] >= 60:
self._vars['width'] -= self.widthChange()
self.writeBody()
# Actions
def actions(self):
acts = ExamplePage.actions(self)
# check whether form is valid (no repeated execution)
try:
formCount = int(self.request().field('formCount'))
except (KeyError, ValueError):
formCount = 0
if formCount == self._vars['formCount']:
acts.extend([
'new', 'delete', 'taller', 'shorter', 'wider', 'narrower'])
self._vars['formCount'] += 1
return acts