transcript 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.
- transcript/__init__.py +112 -0
- transcript/builders/__init__.py +1 -0
- transcript/builders/html/__init__.py +6 -0
- transcript/builders/html/__init__.pyi +796 -0
- transcript/builders/html/args.py +25 -0
- transcript/builders/html/attrs.py +189 -0
- transcript/builders/html/html.py +81 -0
- transcript/builders/jinja.py +228 -0
- transcript/builders/js.py +280 -0
- transcript/builders/scss.py +393 -0
- transcript/builders/xml.py +166 -0
- transcript/core/__init__.py +14 -0
- transcript/core/ai.py +116 -0
- transcript/core/config.py +29 -0
- transcript/core/container.py +120 -0
- transcript/core/factory.py +180 -0
- transcript/core/fingerprint.py +265 -0
- transcript/core/meta.py +41 -0
- transcript/core/registers.py +53 -0
- transcript/core/stubs.py +19 -0
- transcript/io/__init__.py +12 -0
- transcript/io/file.py +40 -0
- transcript/io/hub.py +191 -0
- transcript/io/json_data.py +185 -0
- transcript/io/load.py +154 -0
- transcript/io/renderer.py +49 -0
- transcript/presets/__init__.py +63 -0
- transcript/presets/forms.py +108 -0
- transcript/presets/html.py +247 -0
- transcript/presets/jinja.py +119 -0
- transcript/presets/scss.py +221 -0
- transcript/presets/tailwind.py +392 -0
- transcript/project.py +223 -0
- transcript/purge.py +171 -0
- transcript/py.typed +0 -0
- transcript-0.4.0.dist-info/METADATA +201 -0
- transcript-0.4.0.dist-info/RECORD +40 -0
- transcript-0.4.0.dist-info/WHEEL +5 -0
- transcript-0.4.0.dist-info/licenses/LICENSE +21 -0
- transcript-0.4.0.dist-info/top_level.txt +1 -0
|
@@ -0,0 +1,185 @@
|
|
|
1
|
+
from __future__ import annotations
|
|
2
|
+
|
|
3
|
+
import json
|
|
4
|
+
from pathlib import Path
|
|
5
|
+
from typing import TYPE_CHECKING, Any, Mapping, Sequence
|
|
6
|
+
|
|
7
|
+
if TYPE_CHECKING:
|
|
8
|
+
from transcript.core.container import ContainerBase
|
|
9
|
+
|
|
10
|
+
CONTENT_KEYS = frozenset({'content', 'children', 'body', '$content'})
|
|
11
|
+
TAG_KEYS = frozenset({'tag', '$tag'})
|
|
12
|
+
TAG_ALIASES = frozenset({'tag', '$tag', 'name'})
|
|
13
|
+
ATTRS_KEYS = frozenset({'attrs', 'attributes', '$attrs'})
|
|
14
|
+
META_KEYS = frozenset({'type', 'code', 'selector', 'props'})
|
|
15
|
+
|
|
16
|
+
|
|
17
|
+
class JsonData:
|
|
18
|
+
"""Dane JSON jako źródło atrybutów/treści albo cel eksportu struktury.
|
|
19
|
+
|
|
20
|
+
``container << JsonData({...})`` — ustawia atrybuty znacznika i/lub ciało.
|
|
21
|
+
``container >> JsonData()`` — serializuje kontener do JSON i zapisuje w obiekcie.
|
|
22
|
+
"""
|
|
23
|
+
|
|
24
|
+
def __init__(
|
|
25
|
+
self,
|
|
26
|
+
data: Mapping[str, Any] | Sequence[Any] | str | Path | None = None,
|
|
27
|
+
*,
|
|
28
|
+
path: str | Path | None = None,
|
|
29
|
+
indent: int | None = 2,
|
|
30
|
+
):
|
|
31
|
+
self.indent = indent
|
|
32
|
+
self.path = Path(path) if path is not None else None
|
|
33
|
+
self.data: Any = {}
|
|
34
|
+
if data is not None:
|
|
35
|
+
self.data = self._coerce(data)
|
|
36
|
+
elif self.path is not None and self.path.exists():
|
|
37
|
+
self.data = self._coerce(self.path)
|
|
38
|
+
|
|
39
|
+
def _coerce(self, raw: Any) -> Any:
|
|
40
|
+
if isinstance(raw, Path):
|
|
41
|
+
return json.loads(raw.read_text(encoding='utf-8'))
|
|
42
|
+
if isinstance(raw, str):
|
|
43
|
+
stripped = raw.strip()
|
|
44
|
+
if stripped.startswith(('{', '[')):
|
|
45
|
+
return json.loads(stripped)
|
|
46
|
+
path = Path(raw)
|
|
47
|
+
if path.exists() and path.suffix.lower() in {'.json', '.jsonc'}:
|
|
48
|
+
return json.loads(path.read_text(encoding='utf-8'))
|
|
49
|
+
return raw
|
|
50
|
+
if isinstance(raw, (dict, list)):
|
|
51
|
+
return raw
|
|
52
|
+
return raw
|
|
53
|
+
|
|
54
|
+
def dumps(self) -> str:
|
|
55
|
+
return json.dumps(self.data, ensure_ascii=False, indent=self.indent)
|
|
56
|
+
|
|
57
|
+
def inject_into(self, container: ContainerBase) -> None:
|
|
58
|
+
self._apply(container, self.data)
|
|
59
|
+
|
|
60
|
+
def _apply(self, container: ContainerBase, data: Any) -> None:
|
|
61
|
+
if data is None:
|
|
62
|
+
return
|
|
63
|
+
if isinstance(data, list):
|
|
64
|
+
for item in data:
|
|
65
|
+
self._inject_item(container, item)
|
|
66
|
+
return
|
|
67
|
+
if isinstance(data, dict):
|
|
68
|
+
if any(key in data for key in TAG_KEYS):
|
|
69
|
+
child = self._build_tag(data)
|
|
70
|
+
if child is not None:
|
|
71
|
+
container._inject(child)
|
|
72
|
+
return
|
|
73
|
+
attrs: dict[str, Any] = {}
|
|
74
|
+
content: Any = None
|
|
75
|
+
for key, value in data.items():
|
|
76
|
+
if key in CONTENT_KEYS:
|
|
77
|
+
content = value
|
|
78
|
+
elif key in ATTRS_KEYS and isinstance(value, dict):
|
|
79
|
+
attrs.update(value)
|
|
80
|
+
elif key in TAG_KEYS or key in META_KEYS:
|
|
81
|
+
continue
|
|
82
|
+
else:
|
|
83
|
+
attrs[key] = value
|
|
84
|
+
if attrs:
|
|
85
|
+
container._inject(attrs)
|
|
86
|
+
if content is not None:
|
|
87
|
+
self._apply(container, content)
|
|
88
|
+
return
|
|
89
|
+
container._inject(data)
|
|
90
|
+
|
|
91
|
+
def _inject_item(self, container: ContainerBase, item: Any) -> None:
|
|
92
|
+
if isinstance(item, dict) and any(key in item for key in TAG_KEYS):
|
|
93
|
+
child = self._build_tag(item)
|
|
94
|
+
if child is not None:
|
|
95
|
+
container._inject(child)
|
|
96
|
+
return
|
|
97
|
+
if isinstance(item, dict) and any(key in item for key in CONTENT_KEYS | ATTRS_KEYS):
|
|
98
|
+
# anonimowy fragment atrybutów/treści względem bieżącego kontenera
|
|
99
|
+
self._apply(container, item)
|
|
100
|
+
return
|
|
101
|
+
container._inject(item)
|
|
102
|
+
|
|
103
|
+
def _build_tag(self, spec: Mapping[str, Any]) -> ContainerBase | None:
|
|
104
|
+
tag_value = next((spec[key] for key in ('tag', '$tag', 'name') if key in spec), None)
|
|
105
|
+
if not isinstance(tag_value, str) or not tag_value:
|
|
106
|
+
return None
|
|
107
|
+
|
|
108
|
+
from transcript.core.container import Fragment
|
|
109
|
+
from transcript.builders.html.html import Comment, Doctype, TAGS
|
|
110
|
+
from transcript.builders.xml import XMLTag
|
|
111
|
+
|
|
112
|
+
lowered = tag_value.lower()
|
|
113
|
+
if lowered == 'fragment':
|
|
114
|
+
node: ContainerBase = Fragment()
|
|
115
|
+
elif lowered == 'doctype':
|
|
116
|
+
return Doctype()
|
|
117
|
+
elif lowered == 'comment':
|
|
118
|
+
text = spec.get('content', '')
|
|
119
|
+
return Comment(text if isinstance(text, str) else '')
|
|
120
|
+
else:
|
|
121
|
+
class_name = ''.join(part.capitalize() for part in tag_value.split('-'))
|
|
122
|
+
tag_cls = TAGS.get(class_name)
|
|
123
|
+
node = tag_cls() if tag_cls is not None else XMLTag()
|
|
124
|
+
if tag_cls is None:
|
|
125
|
+
node.name = tag_value
|
|
126
|
+
|
|
127
|
+
attrs: dict[str, Any] = {}
|
|
128
|
+
content: Any = None
|
|
129
|
+
for key, value in spec.items():
|
|
130
|
+
if key in TAG_ALIASES or key in META_KEYS:
|
|
131
|
+
continue
|
|
132
|
+
if key in CONTENT_KEYS:
|
|
133
|
+
content = value
|
|
134
|
+
elif key in ATTRS_KEYS and isinstance(value, dict):
|
|
135
|
+
attrs.update(value)
|
|
136
|
+
else:
|
|
137
|
+
attrs[key] = value
|
|
138
|
+
if attrs:
|
|
139
|
+
node._inject(attrs)
|
|
140
|
+
if content is not None:
|
|
141
|
+
self._apply(node, content)
|
|
142
|
+
return node
|
|
143
|
+
|
|
144
|
+
def export_from(self, container: ContainerBase, code: str) -> str:
|
|
145
|
+
self.data = self._serialize(container)
|
|
146
|
+
payload = self.dumps()
|
|
147
|
+
if self.path is not None:
|
|
148
|
+
if self.path.parent.as_posix() not in ('', '.'):
|
|
149
|
+
self.path.parent.mkdir(parents=True, exist_ok=True)
|
|
150
|
+
self.path.write_text(payload, encoding='utf-8')
|
|
151
|
+
return payload
|
|
152
|
+
|
|
153
|
+
def _serialize(self, container: ContainerBase) -> dict[str, Any]:
|
|
154
|
+
payload: dict[str, Any] = {
|
|
155
|
+
'tag': getattr(container, 'name', container.__class__.__name__),
|
|
156
|
+
'type': container.__class__.__name__,
|
|
157
|
+
}
|
|
158
|
+
attrs = getattr(container, 'attrs', None)
|
|
159
|
+
if attrs:
|
|
160
|
+
payload['attrs'] = {
|
|
161
|
+
attr.name: True if attr._boolean or attr.values == [True] else attr.value
|
|
162
|
+
for attr in attrs
|
|
163
|
+
if attr
|
|
164
|
+
}
|
|
165
|
+
props = getattr(container, 'props', None)
|
|
166
|
+
if props:
|
|
167
|
+
payload['props'] = {prop.name: prop.value for prop in props if prop}
|
|
168
|
+
if getattr(container, 'selector', None):
|
|
169
|
+
payload['selector'] = container.selector
|
|
170
|
+
children = []
|
|
171
|
+
for child in getattr(container, 'content', []):
|
|
172
|
+
if hasattr(child, 'build') and hasattr(child, 'content'):
|
|
173
|
+
children.append(self._serialize(child))
|
|
174
|
+
else:
|
|
175
|
+
children.append(child if isinstance(child, (str, int, float, bool)) else str(child))
|
|
176
|
+
if children:
|
|
177
|
+
payload['content'] = children
|
|
178
|
+
payload['code'] = container.build()
|
|
179
|
+
return payload
|
|
180
|
+
|
|
181
|
+
def __repr__(self) -> str:
|
|
182
|
+
preview = repr(self.data)
|
|
183
|
+
if len(preview) > 60:
|
|
184
|
+
preview = preview[:57] + '...'
|
|
185
|
+
return f'{self.__class__.__name__}({preview})'
|
transcript/io/load.py
ADDED
|
@@ -0,0 +1,154 @@
|
|
|
1
|
+
from __future__ import annotations
|
|
2
|
+
|
|
3
|
+
import re
|
|
4
|
+
from html.parser import HTMLParser
|
|
5
|
+
from pathlib import Path
|
|
6
|
+
from typing import Any
|
|
7
|
+
|
|
8
|
+
from transcript.core.container import ContainerBase, Fragment
|
|
9
|
+
from transcript.io.file import File
|
|
10
|
+
from transcript.io.json_data import JsonData
|
|
11
|
+
|
|
12
|
+
VOID_TAGS = frozenset({
|
|
13
|
+
'area', 'base', 'br', 'col', 'embed', 'hr', 'img', 'input', 'link',
|
|
14
|
+
'meta', 'param', 'source', 'track', 'wbr',
|
|
15
|
+
})
|
|
16
|
+
|
|
17
|
+
|
|
18
|
+
class _HTMLToJsonParser(HTMLParser):
|
|
19
|
+
"""Parsuje HTML do drzewa dict zgodnego z ``JsonData``."""
|
|
20
|
+
|
|
21
|
+
def __init__(self):
|
|
22
|
+
super().__init__(convert_charrefs=True)
|
|
23
|
+
self.root: dict[str, Any] = {'tag': 'fragment', 'content': []}
|
|
24
|
+
self._stack: list[dict[str, Any]] = [self.root]
|
|
25
|
+
|
|
26
|
+
def handle_starttag(self, tag: str, attrs: list[tuple[str, str | None]]) -> None:
|
|
27
|
+
node: dict[str, Any] = {'tag': tag.lower()}
|
|
28
|
+
attr_map = {name: (True if value is None else value) for name, value in attrs}
|
|
29
|
+
if attr_map:
|
|
30
|
+
node['attrs'] = attr_map
|
|
31
|
+
self._stack[-1].setdefault('content', []).append(node)
|
|
32
|
+
if tag.lower() not in VOID_TAGS:
|
|
33
|
+
node['content'] = []
|
|
34
|
+
self._stack.append(node)
|
|
35
|
+
|
|
36
|
+
def handle_startendtag(self, tag: str, attrs: list[tuple[str, str | None]]) -> None:
|
|
37
|
+
node: dict[str, Any] = {'tag': tag.lower()}
|
|
38
|
+
attr_map = {name: (True if value is None else value) for name, value in attrs}
|
|
39
|
+
if attr_map:
|
|
40
|
+
node['attrs'] = attr_map
|
|
41
|
+
self._stack[-1].setdefault('content', []).append(node)
|
|
42
|
+
|
|
43
|
+
def handle_endtag(self, tag: str) -> None:
|
|
44
|
+
tag = tag.lower()
|
|
45
|
+
if tag in VOID_TAGS:
|
|
46
|
+
return
|
|
47
|
+
while len(self._stack) > 1:
|
|
48
|
+
closed = self._stack.pop()
|
|
49
|
+
if closed.get('tag') == tag:
|
|
50
|
+
content = closed.get('content')
|
|
51
|
+
if isinstance(content, list):
|
|
52
|
+
if not content:
|
|
53
|
+
closed.pop('content', None)
|
|
54
|
+
elif len(content) == 1 and isinstance(content[0], str):
|
|
55
|
+
closed['content'] = content[0]
|
|
56
|
+
break
|
|
57
|
+
|
|
58
|
+
def handle_data(self, data: str) -> None:
|
|
59
|
+
text = data.strip()
|
|
60
|
+
if not text:
|
|
61
|
+
return
|
|
62
|
+
self._stack[-1].setdefault('content', []).append(text)
|
|
63
|
+
|
|
64
|
+
def handle_comment(self, data: str) -> None:
|
|
65
|
+
self._stack[-1].setdefault('content', []).append({
|
|
66
|
+
'tag': 'comment',
|
|
67
|
+
'content': data.strip(),
|
|
68
|
+
})
|
|
69
|
+
|
|
70
|
+
def handle_decl(self, decl: str) -> None:
|
|
71
|
+
if decl.lower().startswith('doctype'):
|
|
72
|
+
self._stack[-1].setdefault('content', []).append({'tag': 'doctype'})
|
|
73
|
+
|
|
74
|
+
|
|
75
|
+
def _read_source(source: str | Path | File) -> tuple[str, str]:
|
|
76
|
+
"""Zwraca ``(tekst, kind)`` gdzie kind to ``html`` | ``json`` | ``text``."""
|
|
77
|
+
if isinstance(source, File):
|
|
78
|
+
text = source.read()
|
|
79
|
+
suffix = source.path.suffix.lower()
|
|
80
|
+
elif isinstance(source, Path):
|
|
81
|
+
text = source.read_text(encoding='utf-8')
|
|
82
|
+
suffix = source.suffix.lower()
|
|
83
|
+
else:
|
|
84
|
+
text = source
|
|
85
|
+
path = Path(source)
|
|
86
|
+
if len(source) < 512 and path.is_file():
|
|
87
|
+
text = path.read_text(encoding='utf-8')
|
|
88
|
+
suffix = path.suffix.lower()
|
|
89
|
+
else:
|
|
90
|
+
suffix = ''
|
|
91
|
+
|
|
92
|
+
stripped = text.lstrip()
|
|
93
|
+
if suffix in {'.json', '.jsonc'} or stripped.startswith(('{', '[')):
|
|
94
|
+
return text, 'json'
|
|
95
|
+
if suffix in {'.html', '.htm', '.xhtml'} or re.match(
|
|
96
|
+
r'(?is)<(!doctype\s+html|html\b|[a-zA-Z][\w:-]*)\b',
|
|
97
|
+
stripped,
|
|
98
|
+
):
|
|
99
|
+
return text, 'html'
|
|
100
|
+
return text, 'text'
|
|
101
|
+
|
|
102
|
+
|
|
103
|
+
def html_to_data(html: str) -> Any:
|
|
104
|
+
"""Konwertuje znaczniki HTML na strukturę JSON (dict/list)."""
|
|
105
|
+
parser = _HTMLToJsonParser()
|
|
106
|
+
parser.feed(html)
|
|
107
|
+
parser.close()
|
|
108
|
+
content = parser.root.get('content', [])
|
|
109
|
+
if len(content) == 1:
|
|
110
|
+
return content[0]
|
|
111
|
+
return {'tag': 'fragment', 'content': content}
|
|
112
|
+
|
|
113
|
+
|
|
114
|
+
def data_to_container(data: Any) -> ContainerBase:
|
|
115
|
+
"""Buduje drzewo kontenerów z struktury JSON (odwrotność eksportu)."""
|
|
116
|
+
if isinstance(data, JsonData):
|
|
117
|
+
data = data.data
|
|
118
|
+
|
|
119
|
+
wrapper = Fragment()
|
|
120
|
+
JsonData(data).inject_into(wrapper)
|
|
121
|
+
if len(wrapper.content) == 1 and isinstance(wrapper.content[0], ContainerBase):
|
|
122
|
+
return wrapper.content[0]
|
|
123
|
+
return wrapper
|
|
124
|
+
|
|
125
|
+
|
|
126
|
+
def load(
|
|
127
|
+
source: str | Path | File | JsonData | dict | list,
|
|
128
|
+
*,
|
|
129
|
+
as_container: bool = False,
|
|
130
|
+
) -> JsonData | ContainerBase:
|
|
131
|
+
"""Ładuje HTML/JSON do ``JsonData`` (albo kontenera) w celu ponownego generowania.
|
|
132
|
+
|
|
133
|
+
Przykłady::
|
|
134
|
+
|
|
135
|
+
data = load('templates/index.html') # JsonData
|
|
136
|
+
page = load('templates/index.html', as_container=True)
|
|
137
|
+
regenerated = Div() << load('card.html')
|
|
138
|
+
"""
|
|
139
|
+
if isinstance(source, JsonData):
|
|
140
|
+
data = source
|
|
141
|
+
elif isinstance(source, (dict, list)):
|
|
142
|
+
data = JsonData(source)
|
|
143
|
+
else:
|
|
144
|
+
text, kind = _read_source(source)
|
|
145
|
+
if kind == 'json':
|
|
146
|
+
data = JsonData(text)
|
|
147
|
+
elif kind == 'html':
|
|
148
|
+
data = JsonData(html_to_data(text))
|
|
149
|
+
else:
|
|
150
|
+
data = JsonData(html_to_data(text) if '<' in text else {'tag': 'fragment', 'content': [text]})
|
|
151
|
+
|
|
152
|
+
if as_container:
|
|
153
|
+
return data_to_container(data)
|
|
154
|
+
return data
|
|
@@ -0,0 +1,49 @@
|
|
|
1
|
+
from __future__ import annotations
|
|
2
|
+
|
|
3
|
+
from typing import TYPE_CHECKING, Dict, Optional
|
|
4
|
+
|
|
5
|
+
if TYPE_CHECKING:
|
|
6
|
+
from transcript.core.container import ContainerBase
|
|
7
|
+
|
|
8
|
+
|
|
9
|
+
class Renderer:
|
|
10
|
+
"""Cel eksportu — przechowuje wygenerowany kod do podglądu lub dalszego pipeline'u.
|
|
11
|
+
|
|
12
|
+
``container >> Renderer()`` — przekazuje wynik ``build()`` do renderera.
|
|
13
|
+
"""
|
|
14
|
+
|
|
15
|
+
def __init__(self, name: str = 'default', kind: str = 'html'):
|
|
16
|
+
self.name = name
|
|
17
|
+
self.kind = kind
|
|
18
|
+
self.outputs: Dict[str, str] = {}
|
|
19
|
+
self.last: str = ''
|
|
20
|
+
|
|
21
|
+
def export_from(self, container: ContainerBase, code: str) -> str:
|
|
22
|
+
key = self.name or getattr(container, 'name', None) or self.kind
|
|
23
|
+
self.outputs[key] = code
|
|
24
|
+
self.last = code
|
|
25
|
+
return code
|
|
26
|
+
|
|
27
|
+
def get(self, name: Optional[str] = None) -> str:
|
|
28
|
+
if name is not None:
|
|
29
|
+
return self.outputs.get(name, '')
|
|
30
|
+
return self.last
|
|
31
|
+
|
|
32
|
+
def clear(self, name: Optional[str] = None) -> None:
|
|
33
|
+
if name is not None:
|
|
34
|
+
removed = self.outputs.pop(name, None)
|
|
35
|
+
if removed is not None and self.last == removed:
|
|
36
|
+
self.last = next(reversed(self.outputs.values()), '')
|
|
37
|
+
return
|
|
38
|
+
self.outputs.clear()
|
|
39
|
+
self.last = ''
|
|
40
|
+
|
|
41
|
+
def __bool__(self) -> bool:
|
|
42
|
+
return bool(self.last or self.outputs)
|
|
43
|
+
|
|
44
|
+
def __str__(self) -> str:
|
|
45
|
+
return self.last
|
|
46
|
+
|
|
47
|
+
def __repr__(self) -> str:
|
|
48
|
+
keys = ', '.join(sorted(self.outputs))
|
|
49
|
+
return f'{self.__class__.__name__}(name={self.name!r}, outputs=[{keys}])'
|
|
@@ -0,0 +1,63 @@
|
|
|
1
|
+
from transcript.presets.forms import (
|
|
2
|
+
CheckboxField,
|
|
3
|
+
ContactForm,
|
|
4
|
+
FormField,
|
|
5
|
+
FormGroup,
|
|
6
|
+
HiddenCsrf,
|
|
7
|
+
LoginForm,
|
|
8
|
+
SearchForm,
|
|
9
|
+
)
|
|
10
|
+
from transcript.presets.html import (
|
|
11
|
+
Alert,
|
|
12
|
+
Breadcrumbs,
|
|
13
|
+
Card,
|
|
14
|
+
DataTable,
|
|
15
|
+
FigureImage,
|
|
16
|
+
Hero,
|
|
17
|
+
HTML5Document,
|
|
18
|
+
Modal,
|
|
19
|
+
Navbar,
|
|
20
|
+
PageFooter,
|
|
21
|
+
Pagination,
|
|
22
|
+
SidebarLayout,
|
|
23
|
+
SiteHeader,
|
|
24
|
+
SiteLayout,
|
|
25
|
+
SkipLink,
|
|
26
|
+
)
|
|
27
|
+
from transcript.presets.jinja import (
|
|
28
|
+
JinjaBaseTemplate,
|
|
29
|
+
JinjaCsrf,
|
|
30
|
+
JinjaEmptyState,
|
|
31
|
+
JinjaFlashedMessages,
|
|
32
|
+
JinjaIncludeNav,
|
|
33
|
+
JinjaInputMacro,
|
|
34
|
+
JinjaLoopList,
|
|
35
|
+
JinjaPage,
|
|
36
|
+
JinjaPagination,
|
|
37
|
+
JinjaUrl,
|
|
38
|
+
)
|
|
39
|
+
from transcript.presets import scss as scss_presets
|
|
40
|
+
from transcript.presets.tailwind import (
|
|
41
|
+
COLORS,
|
|
42
|
+
SPACING,
|
|
43
|
+
Tailwind,
|
|
44
|
+
TailwindPreflight,
|
|
45
|
+
TailwindUtilities,
|
|
46
|
+
TailwindVariables,
|
|
47
|
+
tw,
|
|
48
|
+
utility,
|
|
49
|
+
)
|
|
50
|
+
|
|
51
|
+
__all__ = [
|
|
52
|
+
'HTML5Document', 'Navbar', 'Breadcrumbs', 'Card', 'Hero', 'PageFooter',
|
|
53
|
+
'Alert', 'Modal', 'FigureImage', 'DataTable', 'Pagination', 'SkipLink',
|
|
54
|
+
'SiteHeader', 'SiteLayout', 'SidebarLayout',
|
|
55
|
+
'FormField', 'FormGroup', 'LoginForm', 'SearchForm', 'ContactForm',
|
|
56
|
+
'CheckboxField', 'HiddenCsrf',
|
|
57
|
+
'JinjaBaseTemplate', 'JinjaPage', 'JinjaLoopList', 'JinjaEmptyState',
|
|
58
|
+
'JinjaFlashedMessages', 'JinjaPagination', 'JinjaUrl', 'JinjaCsrf',
|
|
59
|
+
'JinjaInputMacro', 'JinjaIncludeNav',
|
|
60
|
+
'scss_presets',
|
|
61
|
+
'Tailwind', 'TailwindPreflight', 'TailwindUtilities', 'TailwindVariables',
|
|
62
|
+
'tw', 'utility', 'SPACING', 'COLORS',
|
|
63
|
+
]
|
|
@@ -0,0 +1,108 @@
|
|
|
1
|
+
from __future__ import annotations
|
|
2
|
+
|
|
3
|
+
from typing import Iterable
|
|
4
|
+
|
|
5
|
+
from transcript.builders.html.html import (
|
|
6
|
+
Button,
|
|
7
|
+
Div,
|
|
8
|
+
Fieldset,
|
|
9
|
+
Form,
|
|
10
|
+
Input,
|
|
11
|
+
Label,
|
|
12
|
+
Legend,
|
|
13
|
+
Option,
|
|
14
|
+
Select,
|
|
15
|
+
Span,
|
|
16
|
+
Textarea,
|
|
17
|
+
)
|
|
18
|
+
|
|
19
|
+
|
|
20
|
+
class FormField(Div):
|
|
21
|
+
"""Pole formularza: etykieta + kontrolka + opcjonalny komunikat błędu."""
|
|
22
|
+
|
|
23
|
+
def __init__(
|
|
24
|
+
self,
|
|
25
|
+
name: str,
|
|
26
|
+
label: str,
|
|
27
|
+
control: str = 'text',
|
|
28
|
+
value: str = '',
|
|
29
|
+
required: bool = False,
|
|
30
|
+
placeholder: str = '',
|
|
31
|
+
options: Iterable[tuple[str, str]] | None = None,
|
|
32
|
+
error: str = '',
|
|
33
|
+
):
|
|
34
|
+
super().__init__(class_='form-field')
|
|
35
|
+
field_id = f'field-{name}'
|
|
36
|
+
self << Label(label, **{'for': field_id})
|
|
37
|
+
attrs = {'name': name, 'id': field_id}
|
|
38
|
+
if required:
|
|
39
|
+
attrs['required'] = True
|
|
40
|
+
if placeholder:
|
|
41
|
+
attrs['placeholder'] = placeholder
|
|
42
|
+
if control == 'textarea':
|
|
43
|
+
self << Textarea(value, **attrs)
|
|
44
|
+
elif control == 'select':
|
|
45
|
+
select = Select(**attrs)
|
|
46
|
+
for option_value, option_label in options or ():
|
|
47
|
+
select << Option(option_label, value=option_value)
|
|
48
|
+
self << select
|
|
49
|
+
else:
|
|
50
|
+
attrs['type'] = control
|
|
51
|
+
if value:
|
|
52
|
+
attrs['value'] = value
|
|
53
|
+
self << Input(**attrs)
|
|
54
|
+
if error:
|
|
55
|
+
self << Span(error, class_='form-field__error')
|
|
56
|
+
|
|
57
|
+
|
|
58
|
+
class FormGroup(Fieldset):
|
|
59
|
+
def __init__(self, legend: str = '', *contents):
|
|
60
|
+
super().__init__(*contents, class_='form-group')
|
|
61
|
+
if legend:
|
|
62
|
+
self.content.insert(0, Legend(legend))
|
|
63
|
+
|
|
64
|
+
|
|
65
|
+
class LoginForm(Form):
|
|
66
|
+
def __init__(self, action: str = '/login', method: str = 'post'):
|
|
67
|
+
super().__init__(action=action, method=method, class_='form form--login')
|
|
68
|
+
self << FormField('email', 'E-mail', control='email', required=True)
|
|
69
|
+
self << FormField('password', 'Hasło', control='password', required=True)
|
|
70
|
+
self << Button('Zaloguj', type='submit', class_='btn btn--primary')
|
|
71
|
+
|
|
72
|
+
|
|
73
|
+
class SearchForm(Form):
|
|
74
|
+
def __init__(self, action: str = '/search', name: str = 'q', placeholder: str = 'Szukaj…'):
|
|
75
|
+
super().__init__(action=action, method='get', class_='form form--search', role='search')
|
|
76
|
+
self << Input(type='search', name=name, placeholder=placeholder, class_='form--search__input')
|
|
77
|
+
self << Button('Szukaj', type='submit', class_='btn')
|
|
78
|
+
|
|
79
|
+
|
|
80
|
+
class ContactForm(Form):
|
|
81
|
+
def __init__(self, action: str = '/contact'):
|
|
82
|
+
super().__init__(action=action, method='post', class_='form form--contact')
|
|
83
|
+
self << FormField('name', 'Imię i nazwisko', required=True)
|
|
84
|
+
self << FormField('email', 'E-mail', control='email', required=True)
|
|
85
|
+
self << FormField('message', 'Wiadomość', control='textarea', required=True)
|
|
86
|
+
self << Button('Wyślij', type='submit', class_='btn btn--primary')
|
|
87
|
+
|
|
88
|
+
|
|
89
|
+
class CheckboxField(Div):
|
|
90
|
+
def __init__(self, name: str, label: str, checked: bool = False, value: str = '1'):
|
|
91
|
+
super().__init__(class_='form-field form-field--checkbox')
|
|
92
|
+
field_id = f'field-{name}'
|
|
93
|
+
attrs = {'type': 'checkbox', 'name': name, 'id': field_id, 'value': value}
|
|
94
|
+
if checked:
|
|
95
|
+
attrs['checked'] = True
|
|
96
|
+
self << Input(**attrs)
|
|
97
|
+
self << Label(label, **{'for': field_id})
|
|
98
|
+
|
|
99
|
+
|
|
100
|
+
class HiddenCsrf(Input):
|
|
101
|
+
def __init__(self, token_expr: str = '{{ csrf_token }}'):
|
|
102
|
+
super().__init__(type='hidden', name='csrf_token', value=token_expr)
|
|
103
|
+
|
|
104
|
+
|
|
105
|
+
__all__ = [
|
|
106
|
+
'FormField', 'FormGroup', 'LoginForm', 'SearchForm', 'ContactForm',
|
|
107
|
+
'CheckboxField', 'HiddenCsrf',
|
|
108
|
+
]
|