readwebform 0.4.0__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.
readwebform/forms.py ADDED
@@ -0,0 +1,408 @@
1
+ """
2
+ Declarative form generation for readwebform.
3
+ """
4
+
5
+ import html as html_mod
6
+ import urllib.parse
7
+ from typing import Optional
8
+
9
+ from .parser import render_page
10
+
11
+ # Field types accepted by --field and the Python API
12
+ VALID_TYPES = frozenset({
13
+ 'text', 'email', 'password', 'number', 'date', 'url', 'tel', 'search',
14
+ 'time', 'datetime-local', 'month', 'week', 'range', 'color', 'hidden',
15
+ 'textarea', 'select', 'checkbox', 'radio', 'file',
16
+ })
17
+
18
+ # Options that take no value. Anything else without '=' continues the
19
+ # previous option's value, so accept=.pdf,.docx works as documented.
20
+ FLAG_OPTIONS = frozenset({'required', 'multiple', 'checked', 'readonly', 'disabled', 'autofocus'})
21
+
22
+ # Options copied verbatim onto <input> elements when present
23
+ _INPUT_PASSTHROUGH = ('placeholder', 'min', 'max', 'step', 'accept', 'pattern',
24
+ 'minlength', 'maxlength', 'autocomplete', 'list')
25
+
26
+
27
+ class FieldSpec:
28
+ """Represents a parsed field specification."""
29
+
30
+ def __init__(self, name: str, field_type: str, label: Optional[str] = None,
31
+ options: Optional[dict[str, str]] = None):
32
+ self.name = name
33
+ self.field_type = field_type
34
+ self.label = label or name
35
+ self.options = options or {}
36
+
37
+ @classmethod
38
+ def parse(cls, spec: str) -> 'FieldSpec':
39
+ """
40
+ Parse a field specification string.
41
+
42
+ Format: name:type[:label][:options]
43
+ Example: name:text:Full+Name:required,placeholder=Your+name
44
+
45
+ Labels and option values are URL-decoded (``+`` becomes a space,
46
+ ``%2C`` a comma). Options are comma-separated ``key=value`` pairs or
47
+ bare flags (``required``, ``multiple``, ``checked``...). A comma in a
48
+ value is allowed where the text after it is not a flag, so
49
+ ``accept=.pdf,.docx`` is a single option.
50
+
51
+ Raises:
52
+ ValueError: If the specification is invalid
53
+ """
54
+ parts = spec.split(':', 3)
55
+ if len(parts) < 2:
56
+ raise ValueError(f'Invalid field spec: {spec} (expected name:type[:label][:options])')
57
+
58
+ name = parts[0].strip()
59
+ field_type = parts[1].strip().lower()
60
+ label = None
61
+ options: dict[str, str] = {}
62
+
63
+ if not name:
64
+ raise ValueError(f'Invalid field spec: {spec} (field name is empty)')
65
+
66
+ if field_type not in VALID_TYPES:
67
+ raise ValueError(
68
+ f'Invalid field type: {field_type} (must be one of {", ".join(sorted(VALID_TYPES))})'
69
+ )
70
+
71
+ if len(parts) >= 3 and parts[2] != '':
72
+ label = urllib.parse.unquote_plus(parts[2])
73
+
74
+ if len(parts) >= 4:
75
+ options = cls._parse_options(parts[3])
76
+
77
+ return cls(name, field_type, label, options)
78
+
79
+ @staticmethod
80
+ def _parse_options(options_str: str) -> dict[str, str]:
81
+ """Parse an options string into a dictionary."""
82
+ options: dict[str, str] = {}
83
+ last_key: Optional[str] = None
84
+ for raw_segment in options_str.split(','):
85
+ segment = raw_segment.strip()
86
+ if not segment:
87
+ continue
88
+
89
+ if '=' in segment:
90
+ key, value = segment.split('=', 1)
91
+ key = key.strip().lower()
92
+ options[key] = urllib.parse.unquote_plus(value.strip())
93
+ last_key = key
94
+ elif segment.lower() in FLAG_OPTIONS:
95
+ options[segment.lower()] = 'true'
96
+ last_key = None
97
+ elif last_key is not None:
98
+ # Continuation of a value that contains a comma
99
+ options[last_key] += ',' + urllib.parse.unquote_plus(segment)
100
+ else:
101
+ raise ValueError(f'Unknown option: {segment}')
102
+
103
+ return options
104
+
105
+ def has_flag(self, name: str) -> bool:
106
+ return name in self.options
107
+
108
+
109
+ def generate_form_html(fields: list[FieldSpec], add_submit_button: bool = True,
110
+ add_cancel_button: bool = True, cancel_label: str = 'Cancel',
111
+ submit_label: str = 'Submit') -> str:
112
+ """
113
+ Generate an HTML form from field specifications.
114
+
115
+ Args:
116
+ fields: List of FieldSpec instances
117
+ add_submit_button: Whether to add a submit button
118
+ add_cancel_button: Whether to add a cancel button
119
+ cancel_label: Label text for the cancel button
120
+ submit_label: Label text for the submit button
121
+
122
+ Returns:
123
+ HTML form string
124
+ """
125
+ has_file_field = any(f.field_type == 'file' for f in fields)
126
+ enctype = ' enctype="multipart/form-data"' if has_file_field else ''
127
+
128
+ form_parts = [f'<form method="POST"{enctype}>']
129
+
130
+ for field in fields:
131
+ form_parts.append(generate_field_html(field))
132
+
133
+ if add_submit_button:
134
+ form_parts.append(f' <button type="submit">{escape_html(submit_label)}</button>')
135
+
136
+ if add_cancel_button:
137
+ form_parts.append(' <button type="submit" name="_cancel" value="1" class="cancel" '
138
+ f'formnovalidate>{escape_html(cancel_label)}</button>')
139
+
140
+ form_parts.append('</form>')
141
+
142
+ return '\n'.join(form_parts)
143
+
144
+
145
+ def generate_field_html(field: FieldSpec) -> str:
146
+ """
147
+ Generate HTML for a single form field.
148
+
149
+ Args:
150
+ field: FieldSpec instance
151
+
152
+ Returns:
153
+ HTML string for the field
154
+ """
155
+ label_html = f' <label for="{escape_attr(field.name)}">{escape_html(field.label)}</label>'
156
+
157
+ if field.field_type == 'textarea':
158
+ return label_html + '\n' + _generate_textarea(field)
159
+ if field.field_type == 'select':
160
+ return label_html + '\n' + _generate_select(field)
161
+ if field.field_type == 'checkbox':
162
+ return _generate_checkbox(field)
163
+ if field.field_type == 'radio':
164
+ return _generate_radio_group(field)
165
+ if field.field_type == 'hidden':
166
+ return _generate_input(field)
167
+ return label_html + '\n' + _generate_input(field)
168
+
169
+
170
+ def _common_attrs(field: FieldSpec) -> dict[str, Optional[str]]:
171
+ attrs: dict[str, Optional[str]] = {}
172
+ for flag in ('required', 'readonly', 'disabled', 'autofocus'):
173
+ if field.has_flag(flag):
174
+ attrs[flag] = None
175
+ return attrs
176
+
177
+
178
+ def _generate_input(field: FieldSpec) -> str:
179
+ """Generate HTML for <input> elements."""
180
+ attrs: dict[str, Optional[str]] = {
181
+ 'type': field.field_type,
182
+ 'name': field.name,
183
+ 'id': field.name,
184
+ }
185
+
186
+ for key in _INPUT_PASSTHROUGH:
187
+ if key in field.options:
188
+ attrs[key] = field.options[key]
189
+
190
+ if 'value' in field.options and field.field_type != 'file':
191
+ attrs['value'] = field.options['value']
192
+
193
+ attrs.update(_common_attrs(field))
194
+
195
+ if field.has_flag('multiple') and field.field_type in ('file', 'email'):
196
+ attrs['multiple'] = None
197
+
198
+ return ' ' + build_tag('input', attrs)
199
+
200
+
201
+ def _generate_textarea(field: FieldSpec) -> str:
202
+ """Generate HTML for <textarea> elements."""
203
+ attrs: dict[str, Optional[str]] = {
204
+ 'name': field.name,
205
+ 'id': field.name,
206
+ }
207
+
208
+ for key in ('rows', 'cols', 'placeholder', 'minlength', 'maxlength'):
209
+ if key in field.options:
210
+ attrs[key] = field.options[key]
211
+
212
+ attrs.update(_common_attrs(field))
213
+
214
+ content = escape_html(field.options.get('value', ''))
215
+ return ' ' + build_tag('textarea', attrs) + content + '</textarea>'
216
+
217
+
218
+ def _option_values(field: FieldSpec) -> list[str]:
219
+ raw = field.options.get('options', '')
220
+ return [o.strip() for o in raw.split('|')] if raw else []
221
+
222
+
223
+ def _selected_values(field: FieldSpec) -> list[str]:
224
+ value = field.options.get('value')
225
+ if value is None:
226
+ return []
227
+ if field.has_flag('multiple'):
228
+ return [v.strip() for v in value.split('|')]
229
+ return [value]
230
+
231
+
232
+ def _generate_select(field: FieldSpec) -> str:
233
+ """Generate HTML for <select> elements."""
234
+ attrs: dict[str, Optional[str]] = {
235
+ 'name': field.name,
236
+ 'id': field.name,
237
+ }
238
+ attrs.update(_common_attrs(field))
239
+ if field.has_flag('multiple'):
240
+ attrs['multiple'] = None
241
+
242
+ selected = _selected_values(field)
243
+ lines = [' ' + build_tag('select', attrs)]
244
+ for option in _option_values(field):
245
+ flag = ' selected' if option in selected else ''
246
+ lines.append(f' <option value="{escape_attr(option)}"{flag}>{escape_html(option)}</option>')
247
+ lines.append(' </select>')
248
+ return '\n'.join(lines)
249
+
250
+
251
+ def _generate_checkbox(field: FieldSpec) -> str:
252
+ """Generate HTML for a checkbox with a trailing label."""
253
+ attrs: dict[str, Optional[str]] = {
254
+ 'type': 'checkbox',
255
+ 'name': field.name,
256
+ 'id': field.name,
257
+ 'value': field.options.get('value', 'on'),
258
+ }
259
+ if field.has_flag('checked'):
260
+ attrs['checked'] = None
261
+ attrs.update(_common_attrs(field))
262
+
263
+ checkbox_html = ' ' + build_tag('input', attrs)
264
+ label_html = f' <label for="{escape_attr(field.name)}">{escape_html(field.label)}</label>'
265
+ return checkbox_html + label_html
266
+
267
+
268
+ def _generate_radio_group(field: FieldSpec) -> str:
269
+ """Generate HTML for a group of radio buttons inside a fieldset."""
270
+ selected = field.options.get('value')
271
+ lines = [' <fieldset>', f' <legend>{escape_html(field.label)}</legend>']
272
+ for i, option in enumerate(_option_values(field)):
273
+ option_id = f'{field.name}_{i}'
274
+ attrs: dict[str, Optional[str]] = {
275
+ 'type': 'radio',
276
+ 'name': field.name,
277
+ 'id': option_id,
278
+ 'value': option,
279
+ }
280
+ if option == selected:
281
+ attrs['checked'] = None
282
+ if field.has_flag('required'):
283
+ attrs['required'] = None
284
+ if field.has_flag('disabled'):
285
+ attrs['disabled'] = None
286
+ lines.append(' ' + build_tag('input', attrs)
287
+ + f' <label for="{escape_attr(option_id)}">{escape_html(option)}</label>')
288
+ lines.append(' </fieldset>')
289
+ return '\n'.join(lines)
290
+
291
+
292
+ def build_tag(tag: str, attrs: dict[str, Optional[str]]) -> str:
293
+ """
294
+ Build an HTML start tag with attributes.
295
+
296
+ Args:
297
+ tag: Tag name
298
+ attrs: Dictionary of attributes (value=None for boolean attributes)
299
+
300
+ Returns:
301
+ HTML start tag string
302
+ """
303
+ attr_parts = []
304
+ for key, value in attrs.items():
305
+ if value is None:
306
+ attr_parts.append(key)
307
+ else:
308
+ attr_parts.append(f'{key}="{escape_attr(value)}"')
309
+
310
+ attr_str = ' ' + ' '.join(attr_parts) if attr_parts else ''
311
+ return f'<{tag}{attr_str}>'
312
+
313
+
314
+ def escape_html(text: Optional[str]) -> str:
315
+ """Escape HTML special characters in text content."""
316
+ if not text:
317
+ return ''
318
+ return html_mod.escape(text, quote=True)
319
+
320
+
321
+ def escape_attr(text: Optional[str]) -> str:
322
+ """Escape HTML special characters in an attribute value."""
323
+ if not text:
324
+ return ''
325
+ return html_mod.escape(text, quote=True)
326
+
327
+
328
+ def dict_to_fieldspec(field_dict: dict) -> FieldSpec:
329
+ """
330
+ Convert a field dictionary (as used by the Python API) to a FieldSpec.
331
+
332
+ Args:
333
+ field_dict: Dictionary with field properties (name, type, label, etc.)
334
+
335
+ Returns:
336
+ FieldSpec instance
337
+
338
+ Raises:
339
+ ValueError: If the name or type is missing or invalid
340
+ """
341
+ name = field_dict.get('name')
342
+ field_type = str(field_dict.get('type', '')).lower()
343
+ if not name:
344
+ raise ValueError('Field is missing a name')
345
+ if field_type not in VALID_TYPES:
346
+ raise ValueError(f'Invalid field type: {field_type!r} for field {name!r} '
347
+ f'(must be one of {", ".join(sorted(VALID_TYPES))})')
348
+
349
+ label = field_dict.get('label')
350
+
351
+ options: dict[str, str] = {}
352
+ for key in ('placeholder', 'min', 'max', 'step', 'accept', 'pattern',
353
+ 'rows', 'cols', 'minlength', 'maxlength', 'autocomplete'):
354
+ if field_dict.get(key) is not None:
355
+ options[key] = str(field_dict[key])
356
+
357
+ for flag in FLAG_OPTIONS:
358
+ if field_dict.get(flag):
359
+ options[flag] = 'true'
360
+
361
+ value = field_dict.get('value')
362
+ if value is not None:
363
+ if isinstance(value, (list, tuple)):
364
+ options['value'] = '|'.join(str(v) for v in value)
365
+ else:
366
+ options['value'] = str(value)
367
+
368
+ opts = field_dict.get('options')
369
+ if opts:
370
+ if isinstance(opts, (list, tuple)):
371
+ options['options'] = '|'.join(str(o) for o in opts)
372
+ else:
373
+ options['options'] = str(opts)
374
+
375
+ return FieldSpec(name, field_type, label, options)
376
+
377
+
378
+ def generate_form_html_from_dicts(
379
+ fields: list[dict],
380
+ title: Optional[str] = None,
381
+ text: Optional[str] = None,
382
+ add_submit: bool = True,
383
+ add_cancel: bool = True,
384
+ cancel_label: str = 'Cancel',
385
+ submit_label: str = 'Submit'
386
+ ) -> str:
387
+ """
388
+ Generate a complete HTML document from field dictionaries.
389
+
390
+ This is the entry point for the Python API.
391
+
392
+ Args:
393
+ fields: List of field dictionaries
394
+ title: Page title
395
+ text: Instructional text above the form
396
+ add_submit: Whether to add a submit button
397
+ add_cancel: Whether to add a cancel button
398
+ cancel_label: Label text for the cancel button
399
+ submit_label: Label text for the submit button
400
+
401
+ Returns:
402
+ Complete HTML document string
403
+ """
404
+ field_specs = [dict_to_fieldspec(f) for f in fields]
405
+ form_html = generate_form_html(field_specs, add_submit_button=add_submit,
406
+ add_cancel_button=add_cancel, cancel_label=cancel_label,
407
+ submit_label=submit_label)
408
+ return render_page(form_html, title=title, text=text)