janelkit 0.1.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.
- janelkit/__init__.py +107 -0
- janelkit/cli/__init__.py +0 -0
- janelkit/cli/build.py +84 -0
- janelkit/cli/dev.py +101 -0
- janelkit/cli/main.py +182 -0
- janelkit/cli/scaffolding.py +87 -0
- janelkit/compiler/__init__.py +251 -0
- janelkit/compiler/ast_nodes.py +204 -0
- janelkit/compiler/cascade.py +224 -0
- janelkit/compiler/expressions.py +206 -0
- janelkit/compiler/ir.py +286 -0
- janelkit/compiler/layout_choice.py +282 -0
- janelkit/compiler/lowering.py +1543 -0
- janelkit/compiler/qml_generator.py +97 -0
- janelkit/compiler/qml_interface.py +125 -0
- janelkit/compiler/script_analysis.py +302 -0
- janelkit/compiler/sfc_parser.py +80 -0
- janelkit/compiler/template_parser.py +480 -0
- janelkit/diagnostics.py +65 -0
- janelkit/events.py +106 -0
- janelkit/ext.py +32 -0
- janelkit/inspect.py +588 -0
- janelkit/lifecycle.py +199 -0
- janelkit/locale.py +46 -0
- janelkit/pages.py +441 -0
- janelkit/qml/DevError.qml +27 -0
- janelkit/qml/Janel/JkBlocker.qml +18 -0
- janelkit/qml/Janel/JkBox.qml +220 -0
- janelkit/qml/Janel/JkButton.qml +68 -0
- janelkit/qml/Janel/JkCheckBox.qml +64 -0
- janelkit/qml/Janel/JkColumn.qml +10 -0
- janelkit/qml/Janel/JkContext.qml +18 -0
- janelkit/qml/Janel/JkFlex.qml +44 -0
- janelkit/qml/Janel/JkFlexColumn.qml +9 -0
- janelkit/qml/Janel/JkFlexRow.qml +8 -0
- janelkit/qml/Janel/JkHover.qml +10 -0
- janelkit/qml/Janel/JkImage.qml +43 -0
- janelkit/qml/Janel/JkList.qml +199 -0
- janelkit/qml/Janel/JkOutline.qml +19 -0
- janelkit/qml/Janel/JkPages.qml +101 -0
- janelkit/qml/Janel/JkProgressBar.qml +68 -0
- janelkit/qml/Janel/JkQtBox.qml +51 -0
- janelkit/qml/Janel/JkRadioGroup.qml +92 -0
- janelkit/qml/Janel/JkRemote.qml +13 -0
- janelkit/qml/Janel/JkRole.qml +72 -0
- janelkit/qml/Janel/JkRow.qml +9 -0
- janelkit/qml/Janel/JkScroll.qml +57 -0
- janelkit/qml/Janel/JkScroller.qml +24 -0
- janelkit/qml/Janel/JkSelect.qml +121 -0
- janelkit/qml/Janel/JkShadow.qml +40 -0
- janelkit/qml/Janel/JkShortcut.qml +20 -0
- janelkit/qml/Janel/JkSides.qml +38 -0
- janelkit/qml/Janel/JkSlider.qml +64 -0
- janelkit/qml/Janel/JkSpacer.qml +25 -0
- janelkit/qml/Janel/JkSwitch.qml +65 -0
- janelkit/qml/Janel/JkTabs.qml +93 -0
- janelkit/qml/Janel/JkTap.qml +15 -0
- janelkit/qml/Janel/JkText.qml +68 -0
- janelkit/qml/Janel/JkTextArea.qml +68 -0
- janelkit/qml/Janel/JkTextBox.qml +14 -0
- janelkit/qml/Janel/JkTextField.qml +60 -0
- janelkit/qml/Janel/JkTextInherit.qml +17 -0
- janelkit/qml/Janel/JkTextLinks.qml +9 -0
- janelkit/qml/Janel/JkTextSelect.qml +54 -0
- janelkit/qml/Janel/JkTransition.qml +84 -0
- janelkit/qml/Janel/JkTranslate.qml +8 -0
- janelkit/qml/Janel/JkVideo.qml +66 -0
- janelkit/qml/Janel/JkWindow.qml +34 -0
- janelkit/qml/Janel/flex.js +844 -0
- janelkit/qml/Janel/jk.js +317 -0
- janelkit/qml/Janel/qmldir +31 -0
- janelkit/qt_backend/__init__.py +0 -0
- janelkit/qt_backend/application.py +536 -0
- janelkit/qt_backend/controls.py +302 -0
- janelkit/qt_backend/events.py +665 -0
- janelkit/qt_backend/polish.py +35 -0
- janelkit/reactivity/__init__.py +24 -0
- janelkit/reactivity/collections.py +294 -0
- janelkit/reactivity/computed.py +71 -0
- janelkit/reactivity/effects.py +334 -0
- janelkit/reactivity/history.py +248 -0
- janelkit/reactivity/props.py +91 -0
- janelkit/reactivity/state.py +74 -0
- janelkit/runtime/__init__.py +3 -0
- janelkit/runtime/component.py +1409 -0
- janelkit/runtime/list_model.py +183 -0
- janelkit/runtime/qt_bridge.py +119 -0
- janelkit/storage.py +175 -0
- janelkit/styling/__init__.py +0 -0
- janelkit/styling/compiler.py +799 -0
- janelkit/styling/parser.py +166 -0
- janelkit/styling/theme.py +160 -0
- janelkit/tasks.py +180 -0
- janelkit/templates/starter/README.md.tmpl +25 -0
- janelkit/templates/starter/assets/dot-gitkeep.tmpl +0 -0
- janelkit/templates/starter/dot-gitignore.tmpl +6 -0
- janelkit/templates/starter/main.py.tmpl +6 -0
- janelkit/templates/starter/pyproject.toml.tmpl +5 -0
- janelkit/templates/starter/src/App.janel.tmpl +39 -0
- janelkit/templates/starter/src/components/Counter.janel.tmpl +28 -0
- janelkit/templates/starter/src/pages/dot-gitkeep.tmpl +0 -0
- janelkit/templates/starter/src/services/users.py.tmpl +6 -0
- janelkit/testing.py +115 -0
- janelkit/timers.py +133 -0
- janelkit/video.py +240 -0
- janelkit/windows.py +120 -0
- janelkit-0.1.0.dist-info/METADATA +179 -0
- janelkit-0.1.0.dist-info/RECORD +112 -0
- janelkit-0.1.0.dist-info/WHEEL +5 -0
- janelkit-0.1.0.dist-info/entry_points.txt +2 -0
- janelkit-0.1.0.dist-info/licenses/LICENSE +21 -0
- janelkit-0.1.0.dist-info/top_level.txt +1 -0
|
@@ -0,0 +1,251 @@
|
|
|
1
|
+
"""Compilador .janel: SFC -> AST -> IR -> QML + tablas para el runtime Python.
|
|
2
|
+
|
|
3
|
+
`compile_file` compila el componente raíz y, recursivamente, los componentes
|
|
4
|
+
`.janel` que importa. Todos comparten un registro (`registry`) indexado por
|
|
5
|
+
ruta, de modo que cada archivo se compila una sola vez y los componentes
|
|
6
|
+
recursivos funcionan.
|
|
7
|
+
|
|
8
|
+
API pública (ver docs/api.md): `compile_file`, `compile_source`,
|
|
9
|
+
`check_file`, `check_source`, `CompiledComponent` y `FORMAT_VERSION`. El
|
|
10
|
+
resto de este paquete es interno.
|
|
11
|
+
"""
|
|
12
|
+
from __future__ import annotations
|
|
13
|
+
|
|
14
|
+
from dataclasses import dataclass, field
|
|
15
|
+
from pathlib import Path
|
|
16
|
+
|
|
17
|
+
from ..diagnostics import Diagnostic, JanelError, SourceLocation
|
|
18
|
+
from .ast_nodes import SFC, EachBlock, Element, IfBlock, KeyBlock, Node
|
|
19
|
+
from .ir import IRComponent
|
|
20
|
+
from .layout_choice import root_features
|
|
21
|
+
from .lowering import ComponentInterface, lower
|
|
22
|
+
from .qml_generator import SourceMap, generate_qml, lookup
|
|
23
|
+
from .script_analysis import ScriptInfo, analyze_script
|
|
24
|
+
from .sfc_parser import parse_file, parse_sfc
|
|
25
|
+
|
|
26
|
+
# Versión del formato .janel que entiende este compilador. Cambia solo cuando
|
|
27
|
+
# un archivo válido deja de compilar o cambia de significado (ver docs/api.md).
|
|
28
|
+
FORMAT_VERSION = 1
|
|
29
|
+
|
|
30
|
+
|
|
31
|
+
@dataclass
|
|
32
|
+
class QmlDocument:
|
|
33
|
+
"""QML generado para el contenido de un slot (se muestra dentro de otro componente)."""
|
|
34
|
+
|
|
35
|
+
file: str
|
|
36
|
+
qml: str
|
|
37
|
+
source_map: SourceMap
|
|
38
|
+
source: str
|
|
39
|
+
|
|
40
|
+
def janel_location(self, qml_line: int) -> SourceLocation | None:
|
|
41
|
+
return lookup(self.source_map, qml_line)
|
|
42
|
+
|
|
43
|
+
|
|
44
|
+
@dataclass
|
|
45
|
+
class CompiledComponent:
|
|
46
|
+
ir: IRComponent
|
|
47
|
+
qml: str
|
|
48
|
+
source_map: SourceMap
|
|
49
|
+
# id de plantilla -> QML del contenido de slot escrito en este componente
|
|
50
|
+
fragments: dict[str, QmlDocument] = field(default_factory=dict, repr=False, compare=False)
|
|
51
|
+
# carpetas desde las que se resolvieron los imports (para compilar más tarde otros componentes)
|
|
52
|
+
roots: list[Path] = field(default_factory=list, repr=False, compare=False)
|
|
53
|
+
# ruta -> componente compilado; compartido por todos los de una misma compilación
|
|
54
|
+
registry: dict[str, "CompiledComponent"] = field(default_factory=dict, repr=False, compare=False)
|
|
55
|
+
# Objetos derivados que el runtime calcula una sola vez (código compilado, clases puente).
|
|
56
|
+
cache: dict = field(default_factory=dict, repr=False, compare=False)
|
|
57
|
+
|
|
58
|
+
@property
|
|
59
|
+
def file(self) -> str:
|
|
60
|
+
return self.ir.file
|
|
61
|
+
|
|
62
|
+
@property
|
|
63
|
+
def source(self) -> str:
|
|
64
|
+
return self.ir.source
|
|
65
|
+
|
|
66
|
+
@property
|
|
67
|
+
def warnings(self) -> list[Diagnostic]:
|
|
68
|
+
return self.ir.warnings
|
|
69
|
+
|
|
70
|
+
@property
|
|
71
|
+
def all_warnings(self) -> list[Diagnostic]:
|
|
72
|
+
"""Advertencias de este componente y de todos los que usa."""
|
|
73
|
+
seen = [self] + [c for c in self.registry.values() if c is not self]
|
|
74
|
+
return [w for c in seen for w in c.warnings]
|
|
75
|
+
|
|
76
|
+
@property
|
|
77
|
+
def files(self) -> list[str]:
|
|
78
|
+
"""Archivos .janel (y .qml propios) que forman la aplicación, para observar cambios."""
|
|
79
|
+
comps = [self, *self.registry.values()]
|
|
80
|
+
return list(dict.fromkeys([self.file, *(c.file for c in comps), *(q for c in comps for q in c.ir.qml_files)]))
|
|
81
|
+
|
|
82
|
+
def component(self, path: str) -> "CompiledComponent":
|
|
83
|
+
return self.registry[path]
|
|
84
|
+
|
|
85
|
+
def janel_location(self, qml_line: int) -> SourceLocation | None:
|
|
86
|
+
return lookup(self.source_map, qml_line)
|
|
87
|
+
|
|
88
|
+
|
|
89
|
+
class CompileSession:
|
|
90
|
+
"""Compila un árbol de componentes resolviendo imports respecto a `roots`."""
|
|
91
|
+
|
|
92
|
+
def __init__(self, roots: list[Path]):
|
|
93
|
+
self.roots = [Path(r).resolve() for r in roots]
|
|
94
|
+
self.registry: dict[str, CompiledComponent] = {}
|
|
95
|
+
self._loaded: dict[str, tuple[SFC, ScriptInfo]] = {}
|
|
96
|
+
self._roots: dict[str, frozenset[str] | None] = {}
|
|
97
|
+
# Componentes cuya raíz va dentro de una caja con el motor de <flex>: su raíz usa
|
|
98
|
+
# también el motor (layout_choice.py). Los anota el padre, que se compila antes.
|
|
99
|
+
self._engine_roots: set[str] = set()
|
|
100
|
+
|
|
101
|
+
def compile(self, path: Path, as_window: bool) -> CompiledComponent:
|
|
102
|
+
key = _key(path)
|
|
103
|
+
if key in self.registry:
|
|
104
|
+
return self.registry[key]
|
|
105
|
+
sfc, info = self.load(path)
|
|
106
|
+
return self._compile_loaded(key, sfc, info, as_window)
|
|
107
|
+
|
|
108
|
+
def compile_source(self, source: str, file: str, as_window: bool = True) -> CompiledComponent:
|
|
109
|
+
sfc = parse_sfc(source, file)
|
|
110
|
+
info = analyze_script(sfc.script, file, sfc.source, self._resolver(Path(file)))
|
|
111
|
+
return self._compile_loaded(file, sfc, info, as_window)
|
|
112
|
+
|
|
113
|
+
def _compile_loaded(self, key: str, sfc: SFC, info: ScriptInfo, as_window: bool) -> CompiledComponent:
|
|
114
|
+
ir = lower(sfc, info, as_window=as_window, interface=self.interface, root_in_engine=key in self._engine_roots)
|
|
115
|
+
self._engine_roots.update(_key(Path(p)) for p in ir.engine_children)
|
|
116
|
+
qml, source_map = generate_qml(ir)
|
|
117
|
+
fragments = {}
|
|
118
|
+
for frag in ir.slot_fragments:
|
|
119
|
+
frag_qml, frag_map = generate_qml(ir, frag.root)
|
|
120
|
+
fragments[frag.template.id] = QmlDocument(ir.file, frag_qml, frag_map, ir.source)
|
|
121
|
+
compiled = CompiledComponent(ir, qml, source_map, fragments, list(self.roots), registry=self.registry)
|
|
122
|
+
self.registry[key] = compiled
|
|
123
|
+
for child in ir.component_paths:
|
|
124
|
+
self.compile(Path(child), as_window=False)
|
|
125
|
+
return compiled
|
|
126
|
+
|
|
127
|
+
def load(self, path: Path) -> tuple[SFC, ScriptInfo]:
|
|
128
|
+
key = _key(path)
|
|
129
|
+
if key not in self._loaded:
|
|
130
|
+
sfc = parse_file(path)
|
|
131
|
+
info = analyze_script(sfc.script, sfc.file, sfc.source, self._resolver(Path(path)))
|
|
132
|
+
self._loaded[key] = (sfc, info)
|
|
133
|
+
return self._loaded[key]
|
|
134
|
+
|
|
135
|
+
def interface(self, path: Path) -> ComponentInterface:
|
|
136
|
+
sfc, info = self.load(path)
|
|
137
|
+
roots = sfc.root_elements
|
|
138
|
+
root = roots[0].tag if len(roots) == 1 and isinstance(roots[0], Element) else None
|
|
139
|
+
key = _key(path)
|
|
140
|
+
if key not in self._roots:
|
|
141
|
+
self._roots[key] = root_features(sfc)
|
|
142
|
+
return ComponentInterface(
|
|
143
|
+
dict(info.props), dict(info.events), frozenset(_slot_names(sfc.template)),
|
|
144
|
+
root_box=root in ("flex", "Column", "Row") and info.inherit_attrs, inherit_attrs=info.inherit_attrs,
|
|
145
|
+
root_items=self._roots[key],
|
|
146
|
+
) # fmt: skip
|
|
147
|
+
|
|
148
|
+
def _resolver(self, file: Path):
|
|
149
|
+
here = file.resolve().parent # en memoria: el directorio actual
|
|
150
|
+
|
|
151
|
+
def resolve(module: str | None, name: str, level: int) -> Path | None:
|
|
152
|
+
if level:
|
|
153
|
+
base = here
|
|
154
|
+
for _ in range(level - 1):
|
|
155
|
+
base = base.parent
|
|
156
|
+
bases = [base]
|
|
157
|
+
else:
|
|
158
|
+
bases = self.roots
|
|
159
|
+
parts = module.split(".") if module else []
|
|
160
|
+
for base in bases:
|
|
161
|
+
folder = base.joinpath(*parts)
|
|
162
|
+
for suffix in (".janel", ".qml"):
|
|
163
|
+
# from components import TodoItem -> components/TodoItem.janel
|
|
164
|
+
candidate = folder / f"{name}{suffix}"
|
|
165
|
+
if candidate.is_file():
|
|
166
|
+
return candidate.resolve()
|
|
167
|
+
# from components.TodoItem import TodoItem -> components/TodoItem.janel
|
|
168
|
+
if parts and folder.name == name:
|
|
169
|
+
candidate = folder.with_suffix(suffix)
|
|
170
|
+
if candidate.is_file():
|
|
171
|
+
return candidate.resolve()
|
|
172
|
+
return None
|
|
173
|
+
|
|
174
|
+
return resolve
|
|
175
|
+
|
|
176
|
+
|
|
177
|
+
def _slot_names(nodes: list[Node]) -> set[str]:
|
|
178
|
+
"""Nombres de los <Slot> de una plantilla ("default" para el que no tiene nombre)."""
|
|
179
|
+
names: set[str] = set()
|
|
180
|
+
for node in nodes:
|
|
181
|
+
children: list[Node] = []
|
|
182
|
+
if isinstance(node, Element):
|
|
183
|
+
if node.tag == "Slot":
|
|
184
|
+
attr = node.attribute("name")
|
|
185
|
+
names.add(attr.value if attr is not None and isinstance(attr.value, str) else "default")
|
|
186
|
+
children = node.children
|
|
187
|
+
elif isinstance(node, IfBlock):
|
|
188
|
+
children = [n for b in node.branches for n in b.children]
|
|
189
|
+
elif isinstance(node, EachBlock):
|
|
190
|
+
children = [*node.children, *(node.else_children or [])]
|
|
191
|
+
elif isinstance(node, KeyBlock):
|
|
192
|
+
children = [*node.children, *(node.else_children or [])]
|
|
193
|
+
names |= _slot_names(children)
|
|
194
|
+
return names
|
|
195
|
+
|
|
196
|
+
|
|
197
|
+
def _key(path: Path | str) -> str:
|
|
198
|
+
return str(Path(path).resolve())
|
|
199
|
+
|
|
200
|
+
|
|
201
|
+
def compile_source(source: str, file: str = "<memoria>", roots: list[Path] | None = None) -> CompiledComponent:
|
|
202
|
+
"""Compila un componente raíz desde texto. Los imports se resuelven respecto a la carpeta de `file`."""
|
|
203
|
+
base = Path(file).resolve().parent if file != "<memoria>" else Path.cwd()
|
|
204
|
+
session = CompileSession(roots or [base])
|
|
205
|
+
return session.compile_source(source, file)
|
|
206
|
+
|
|
207
|
+
|
|
208
|
+
def compile_file(path: str | Path, roots: list[Path] | None = None, as_window: bool = True) -> CompiledComponent:
|
|
209
|
+
"""Compila el componente `path` y los componentes que importa.
|
|
210
|
+
|
|
211
|
+
`roots` son las carpetas desde las que se resuelven los imports absolutos
|
|
212
|
+
(`from components.X import X`); por defecto, la carpeta de `path`.
|
|
213
|
+
"""
|
|
214
|
+
path = Path(path)
|
|
215
|
+
if not path.is_file():
|
|
216
|
+
raise JanelError(Diagnostic(f"no se encontró el archivo {path}"))
|
|
217
|
+
session = CompileSession(roots or [path.resolve().parent])
|
|
218
|
+
return session.compile(path, as_window=as_window)
|
|
219
|
+
|
|
220
|
+
|
|
221
|
+
def check_source(source: str, file: str = "<memoria>", roots: list[Path] | None = None) -> list[Diagnostic]:
|
|
222
|
+
"""Errores y advertencias de un componente y de los que importa, sin ejecutar su script ni lanzar excepciones.
|
|
223
|
+
|
|
224
|
+
Pensado para editores y herramientas: una lista vacía significa que compila sin avisos.
|
|
225
|
+
"""
|
|
226
|
+
try:
|
|
227
|
+
return compile_source(source, file, roots).all_warnings
|
|
228
|
+
except JanelError as e:
|
|
229
|
+
return list(e.diagnostics)
|
|
230
|
+
|
|
231
|
+
|
|
232
|
+
def check_file(path: str | Path, roots: list[Path] | None = None, as_window: bool = True) -> list[Diagnostic]:
|
|
233
|
+
"""Como `check_source`, para un archivo."""
|
|
234
|
+
try:
|
|
235
|
+
return compile_file(path, roots, as_window).all_warnings
|
|
236
|
+
except JanelError as e:
|
|
237
|
+
return list(e.diagnostics)
|
|
238
|
+
|
|
239
|
+
|
|
240
|
+
__all__ = [
|
|
241
|
+
"FORMAT_VERSION",
|
|
242
|
+
"check_file",
|
|
243
|
+
"check_source",
|
|
244
|
+
"CompileSession",
|
|
245
|
+
"CompiledComponent",
|
|
246
|
+
"ComponentInterface",
|
|
247
|
+
"compile_file",
|
|
248
|
+
"compile_source",
|
|
249
|
+
"parse_file",
|
|
250
|
+
"parse_sfc",
|
|
251
|
+
]
|
|
@@ -0,0 +1,204 @@
|
|
|
1
|
+
"""Nodos del AST de un archivo .janel. Todos conservan su ubicación de origen."""
|
|
2
|
+
from __future__ import annotations
|
|
3
|
+
|
|
4
|
+
from dataclasses import dataclass, field
|
|
5
|
+
from typing import Union
|
|
6
|
+
|
|
7
|
+
from ..diagnostics import SourceLocation
|
|
8
|
+
|
|
9
|
+
|
|
10
|
+
@dataclass
|
|
11
|
+
class Expression:
|
|
12
|
+
"""Expresión Python tal como aparece entre llaves."""
|
|
13
|
+
|
|
14
|
+
code: str
|
|
15
|
+
loc: SourceLocation
|
|
16
|
+
|
|
17
|
+
|
|
18
|
+
@dataclass
|
|
19
|
+
class FormattedExpression(Expression):
|
|
20
|
+
"""`{valor:.1f}` o `{valor!r}` en el texto: conversión y formato como en un f-string."""
|
|
21
|
+
|
|
22
|
+
conversion: str = "" # "", "r", "s" o "a"
|
|
23
|
+
spec: str = "" # especificación de formato (sin los dos puntos)
|
|
24
|
+
|
|
25
|
+
|
|
26
|
+
@dataclass
|
|
27
|
+
class Attribute:
|
|
28
|
+
name: str
|
|
29
|
+
# str = literal entre comillas, Expression = {expr}, True = atributo booleano sin valor
|
|
30
|
+
value: Union[str, Expression, bool]
|
|
31
|
+
loc: SourceLocation
|
|
32
|
+
|
|
33
|
+
@property
|
|
34
|
+
def directive(self) -> str | None:
|
|
35
|
+
"""Prefijo de directiva (`on`, `bind`) o None para atributos normales."""
|
|
36
|
+
return self.name.split(":", 1)[0] if ":" in self.name else None
|
|
37
|
+
|
|
38
|
+
@property
|
|
39
|
+
def argument(self) -> str:
|
|
40
|
+
return self.name.split(":", 1)[1] if ":" in self.name else self.name
|
|
41
|
+
|
|
42
|
+
|
|
43
|
+
@dataclass
|
|
44
|
+
class Element:
|
|
45
|
+
tag: str
|
|
46
|
+
attributes: list[Attribute]
|
|
47
|
+
children: list["Node"]
|
|
48
|
+
loc: SourceLocation
|
|
49
|
+
|
|
50
|
+
def attribute(self, name: str) -> Attribute | None:
|
|
51
|
+
return next((a for a in self.attributes if a.name == name), None)
|
|
52
|
+
|
|
53
|
+
|
|
54
|
+
@dataclass
|
|
55
|
+
class Text:
|
|
56
|
+
value: str
|
|
57
|
+
loc: SourceLocation
|
|
58
|
+
|
|
59
|
+
|
|
60
|
+
@dataclass
|
|
61
|
+
class Interpolation:
|
|
62
|
+
expression: Expression
|
|
63
|
+
loc: SourceLocation
|
|
64
|
+
|
|
65
|
+
|
|
66
|
+
@dataclass
|
|
67
|
+
class IfBranch:
|
|
68
|
+
condition: Expression | None # None = {:else}
|
|
69
|
+
children: list["Node"]
|
|
70
|
+
loc: SourceLocation
|
|
71
|
+
|
|
72
|
+
|
|
73
|
+
@dataclass
|
|
74
|
+
class IfBlock:
|
|
75
|
+
branches: list[IfBranch]
|
|
76
|
+
loc: SourceLocation
|
|
77
|
+
|
|
78
|
+
|
|
79
|
+
@dataclass
|
|
80
|
+
class EachBlock:
|
|
81
|
+
iterable: Expression
|
|
82
|
+
item: str
|
|
83
|
+
index: str | None
|
|
84
|
+
key: Expression | None
|
|
85
|
+
children: list["Node"]
|
|
86
|
+
loc: SourceLocation
|
|
87
|
+
else_children: list["Node"] | None = None # {:else}: se muestra si la lista está vacía
|
|
88
|
+
|
|
89
|
+
|
|
90
|
+
@dataclass
|
|
91
|
+
class KeyBlock:
|
|
92
|
+
"""`{#key expr}...{/key}`: recrea el contenido cuando cambia `expr`.
|
|
93
|
+
|
|
94
|
+
Con `hidden`, es `{#hidden expr}...{/hidden}`: el contenido se crea la primera vez
|
|
95
|
+
que `expr` es falso y después solo se oculta (conserva su estado). Su `{:else}` es
|
|
96
|
+
lo contrario: se muestra mientras `expr` es verdadero, y también se conserva."""
|
|
97
|
+
|
|
98
|
+
expression: Expression
|
|
99
|
+
children: list["Node"]
|
|
100
|
+
loc: SourceLocation
|
|
101
|
+
hidden: bool = False
|
|
102
|
+
else_children: list["Node"] | None = None
|
|
103
|
+
|
|
104
|
+
|
|
105
|
+
Node = Union[Element, Text, Interpolation, IfBlock, EachBlock, KeyBlock]
|
|
106
|
+
|
|
107
|
+
|
|
108
|
+
@dataclass
|
|
109
|
+
class ScriptBlock:
|
|
110
|
+
content: str
|
|
111
|
+
lang: str
|
|
112
|
+
loc: SourceLocation # ubicación del primer carácter del contenido
|
|
113
|
+
|
|
114
|
+
|
|
115
|
+
@dataclass
|
|
116
|
+
class StyleBlock:
|
|
117
|
+
content: str
|
|
118
|
+
loc: SourceLocation
|
|
119
|
+
|
|
120
|
+
|
|
121
|
+
@dataclass
|
|
122
|
+
class SFC:
|
|
123
|
+
file: str
|
|
124
|
+
source: str
|
|
125
|
+
script: ScriptBlock | None
|
|
126
|
+
style: StyleBlock | None
|
|
127
|
+
template: list[Node] = field(default_factory=list)
|
|
128
|
+
|
|
129
|
+
@property
|
|
130
|
+
def root_elements(self) -> list[Element]:
|
|
131
|
+
return [n for n in self.template if not (isinstance(n, Text) and not n.value.strip())]
|
|
132
|
+
|
|
133
|
+
|
|
134
|
+
def dump(sfc: SFC) -> str:
|
|
135
|
+
"""Representación legible del AST (usada por `janel parse`)."""
|
|
136
|
+
out: list[str] = [f"SFC {sfc.file}"]
|
|
137
|
+
if sfc.script:
|
|
138
|
+
n = len(sfc.script.content.strip().splitlines())
|
|
139
|
+
out.append(f" Script lang={sfc.script.lang} @{_lc(sfc.script.loc)} ({n} líneas)")
|
|
140
|
+
if sfc.style:
|
|
141
|
+
n = len(sfc.style.content.strip().splitlines())
|
|
142
|
+
out.append(f" Style @{_lc(sfc.style.loc)} ({n} líneas)")
|
|
143
|
+
out.append(" Template")
|
|
144
|
+
for node in sfc.template:
|
|
145
|
+
_dump_node(node, 2, out)
|
|
146
|
+
return "\n".join(out)
|
|
147
|
+
|
|
148
|
+
|
|
149
|
+
def _lc(loc: SourceLocation) -> str:
|
|
150
|
+
return f"{loc.line}:{loc.column}"
|
|
151
|
+
|
|
152
|
+
|
|
153
|
+
def _dump_node(node: Node, depth: int, out: list[str]) -> None:
|
|
154
|
+
pad = " " * depth
|
|
155
|
+
if isinstance(node, Element):
|
|
156
|
+
attrs = " ".join(_fmt_attr(a) for a in node.attributes)
|
|
157
|
+
out.append(f"{pad}<{node.tag}{' ' + attrs if attrs else ''}> @{_lc(node.loc)}")
|
|
158
|
+
for child in node.children:
|
|
159
|
+
_dump_node(child, depth + 1, out)
|
|
160
|
+
elif isinstance(node, Text):
|
|
161
|
+
if node.value.strip():
|
|
162
|
+
out.append(f"{pad}Text {node.value.strip()!r} @{_lc(node.loc)}")
|
|
163
|
+
elif isinstance(node, Interpolation):
|
|
164
|
+
expr = node.expression
|
|
165
|
+
fmt = (f"!{expr.conversion}" if getattr(expr, "conversion", "") else "") + (f":{expr.spec}" if getattr(expr, "spec", "") else "")
|
|
166
|
+
out.append(f"{pad}{{{expr.code.strip()}{fmt}}} @{_lc(node.loc)}")
|
|
167
|
+
elif isinstance(node, IfBlock):
|
|
168
|
+
for i, branch in enumerate(node.branches):
|
|
169
|
+
if i == 0:
|
|
170
|
+
label = f"#if {branch.condition.code.strip()}"
|
|
171
|
+
elif branch.condition:
|
|
172
|
+
label = f":else if {branch.condition.code.strip()}"
|
|
173
|
+
else:
|
|
174
|
+
label = ":else"
|
|
175
|
+
out.append(f"{pad}{{{label}}} @{_lc(branch.loc)}")
|
|
176
|
+
for child in branch.children:
|
|
177
|
+
_dump_node(child, depth + 1, out)
|
|
178
|
+
elif isinstance(node, KeyBlock):
|
|
179
|
+
word = "hidden" if node.hidden else "key"
|
|
180
|
+
out.append(f"{pad}{{#{word} {node.expression.code.strip()}}} @{_lc(node.loc)}")
|
|
181
|
+
for child in node.children:
|
|
182
|
+
_dump_node(child, depth + 1, out)
|
|
183
|
+
if node.else_children is not None:
|
|
184
|
+
out.append(f"{pad}{{:else}}")
|
|
185
|
+
for child in node.else_children:
|
|
186
|
+
_dump_node(child, depth + 1, out)
|
|
187
|
+
elif isinstance(node, EachBlock):
|
|
188
|
+
key = f" ({node.key.code.strip()})" if node.key else ""
|
|
189
|
+
idx = f", {node.index}" if node.index else ""
|
|
190
|
+
out.append(f"{pad}{{#each {node.iterable.code.strip()} as {node.item}{idx}{key}}} @{_lc(node.loc)}")
|
|
191
|
+
for child in node.children:
|
|
192
|
+
_dump_node(child, depth + 1, out)
|
|
193
|
+
if node.else_children is not None:
|
|
194
|
+
out.append(f"{pad}{{:else}}")
|
|
195
|
+
for child in node.else_children:
|
|
196
|
+
_dump_node(child, depth + 1, out)
|
|
197
|
+
|
|
198
|
+
|
|
199
|
+
def _fmt_attr(attr: Attribute) -> str:
|
|
200
|
+
if attr.value is True:
|
|
201
|
+
return attr.name
|
|
202
|
+
if isinstance(attr.value, Expression):
|
|
203
|
+
return f"{attr.name}={{{attr.value.code.strip()}}}"
|
|
204
|
+
return f'{attr.name}="{attr.value}"'
|
|
@@ -0,0 +1,224 @@
|
|
|
1
|
+
"""La cascada de `<style>`: qué reglas aplican a cada elemento y bajo qué condición.
|
|
2
|
+
|
|
3
|
+
Todo se resuelve al compilar, porque los estilos tienen ámbito y la plantilla se
|
|
4
|
+
conoce entera. Lo que depende del estado (pseudo-clases, `class:x={...}`,
|
|
5
|
+
`class={...}`) se convierte en una condición QML que la vista evalúa sola:
|
|
6
|
+
pasar el ratón por encima no llama a Python.
|
|
7
|
+
|
|
8
|
+
Precedencia (docs/estilos.md), como en CSS: gana la regla más específica (más
|
|
9
|
+
clases y pseudo-clases; después, más elementos) y, a igualdad, la última del
|
|
10
|
+
archivo. Por encima de todas, las que dependen de una clase condicional o dinámica
|
|
11
|
+
del propio elemento (`class:x`, `class={...}`), como antes de los selectores
|
|
12
|
+
compuestos.
|
|
13
|
+
"""
|
|
14
|
+
from __future__ import annotations
|
|
15
|
+
|
|
16
|
+
import re
|
|
17
|
+
from dataclasses import dataclass, field
|
|
18
|
+
from typing import Callable
|
|
19
|
+
|
|
20
|
+
from ..styling.parser import Compound, Declaration, Rule, Selector
|
|
21
|
+
from .ir import IRElement, Literal
|
|
22
|
+
|
|
23
|
+
ALWAYS = "true"
|
|
24
|
+
_BOXES = ("JkColumn", "JkRow", "JkFlex", "JkFlexColumn", "JkFlexRow", "JkQtBox")
|
|
25
|
+
|
|
26
|
+
|
|
27
|
+
@dataclass
|
|
28
|
+
class StyleNode:
|
|
29
|
+
"""Un elemento de la plantilla tal como lo ven los selectores."""
|
|
30
|
+
|
|
31
|
+
tag: str # etiqueta escrita (en la caja exterior de un componente, la del componente)
|
|
32
|
+
classes: frozenset[str] = frozenset() # class="a b"
|
|
33
|
+
toggles: dict[str, str] = field(default_factory=dict) # class:x={...} -> id del binding
|
|
34
|
+
dynamic: str | None = None # class={expr} -> id del binding (vale " a b ")
|
|
35
|
+
ir: IRElement | None = None # None: etiqueta de un componente sin caja exterior
|
|
36
|
+
doc: int = 0 # documento QML: el contenido de un slot es otro y no ve los ids de fuera
|
|
37
|
+
passed: bool = False # raíz de un componente: recibe clases de su etiqueta (jkInClass)
|
|
38
|
+
|
|
39
|
+
|
|
40
|
+
@dataclass
|
|
41
|
+
class Match:
|
|
42
|
+
rank: tuple[int, int, int] # (sobre las demás, clases y pseudo-clases, elementos)
|
|
43
|
+
order: int
|
|
44
|
+
cond: str # ALWAYS o una expresión QML
|
|
45
|
+
decls: list[Declaration]
|
|
46
|
+
quiet: bool # class={expr}: no se sabe qué clases dará; sin avisos de propiedades que no aplican
|
|
47
|
+
|
|
48
|
+
|
|
49
|
+
def and_(conds: list[str]) -> str:
|
|
50
|
+
conds = [c for c in dict.fromkeys(conds) if c != ALWAYS]
|
|
51
|
+
if not conds:
|
|
52
|
+
return ALWAYS
|
|
53
|
+
return " && ".join(f"({c})" if "||" in c else c for c in conds)
|
|
54
|
+
|
|
55
|
+
|
|
56
|
+
def or_(conds: list[str]) -> str:
|
|
57
|
+
conds = list(dict.fromkeys(conds))
|
|
58
|
+
if ALWAYS in conds:
|
|
59
|
+
return ALWAYS
|
|
60
|
+
return conds[0] if len(conds) == 1 else " || ".join(f"({c})" if " " in c else c for c in conds)
|
|
61
|
+
|
|
62
|
+
|
|
63
|
+
def _prop_name(cls: str) -> str:
|
|
64
|
+
return "jkc_" + re.sub(r"\W", "_", cls)
|
|
65
|
+
|
|
66
|
+
|
|
67
|
+
class Cascade:
|
|
68
|
+
def __init__(self, rules: list[Rule], new_id: Callable[[], str], warn: Callable[[str, Rule], None]):
|
|
69
|
+
self.rules = rules
|
|
70
|
+
self.new_id = new_id
|
|
71
|
+
self.warn = warn
|
|
72
|
+
self._warned: set[str] = set()
|
|
73
|
+
|
|
74
|
+
# -- reglas que aplican --------------------------------------------------
|
|
75
|
+
def matches(self, chain: list[StyleNode]) -> list[Match]:
|
|
76
|
+
"""Reglas que aplican al último nodo de `chain` (los anteriores son sus antecesores)."""
|
|
77
|
+
node = chain[-1]
|
|
78
|
+
out: list[Match] = []
|
|
79
|
+
for order, rule in enumerate(self.rules):
|
|
80
|
+
conds: list[str] = []
|
|
81
|
+
rank = (-1, -1, -1)
|
|
82
|
+
quiet = True
|
|
83
|
+
for sel in rule.parsed:
|
|
84
|
+
if self._match(sel, chain, len(sel.parts) - 1, len(chain) - 1, build=False, rule=rule) is None:
|
|
85
|
+
continue
|
|
86
|
+
conds.append(self._match(sel, chain, len(sel.parts) - 1, len(chain) - 1, build=True, rule=rule))
|
|
87
|
+
rank = max(rank, self._rank(sel, node))
|
|
88
|
+
quiet = quiet and (node.dynamic is not None or node.passed) and any(
|
|
89
|
+
c not in node.classes and c not in node.toggles for c in sel.subject.classes
|
|
90
|
+
)
|
|
91
|
+
if conds:
|
|
92
|
+
out.append(Match(rank, order, or_(conds), rule.declarations, quiet))
|
|
93
|
+
out.sort(key=lambda m: (m.rank, m.order))
|
|
94
|
+
return out
|
|
95
|
+
|
|
96
|
+
@staticmethod
|
|
97
|
+
def _rank(sel: Selector, node: StyleNode) -> tuple[int, int, int]:
|
|
98
|
+
# Depende de class:x o class={...} del propio elemento: gana a las demás reglas.
|
|
99
|
+
toggled = int(any(c not in node.classes for c in sel.subject.classes))
|
|
100
|
+
return (toggled, *sel.specificity)
|
|
101
|
+
|
|
102
|
+
def _match(self, sel: Selector, chain: list[StyleNode], i: int, j: int, build: bool, rule: Rule) -> str | None:
|
|
103
|
+
"""Condición para que la parte `i` del selector (y las anteriores) case con chain[j]."""
|
|
104
|
+
here = self._compound(sel.parts[i], chain[j], chain[-1], build, sel, rule)
|
|
105
|
+
if here is None:
|
|
106
|
+
return None
|
|
107
|
+
if i == 0:
|
|
108
|
+
return here
|
|
109
|
+
if sel.combinators[i - 1] == ">":
|
|
110
|
+
if j == 0:
|
|
111
|
+
return None
|
|
112
|
+
up = self._match(sel, chain, i - 1, j - 1, build, rule)
|
|
113
|
+
return None if up is None else and_([here, up])
|
|
114
|
+
alts = []
|
|
115
|
+
for k in range(j - 1, -1, -1):
|
|
116
|
+
# Primero se comprueba sin efectos (handlers, ids) y solo se construye lo que casa.
|
|
117
|
+
if self._match(sel, chain, i - 1, k, False, rule) is not None:
|
|
118
|
+
alts.append(self._match(sel, chain, i - 1, k, build, rule))
|
|
119
|
+
return or_(alts) if alts else None
|
|
120
|
+
|
|
121
|
+
def _compound(
|
|
122
|
+
self, comp: Compound, node: StyleNode, subject: StyleNode, build: bool, sel: Selector, rule: Rule
|
|
123
|
+
) -> str | None:
|
|
124
|
+
if comp.tag is not None and comp.tag != node.tag:
|
|
125
|
+
return None
|
|
126
|
+
is_self = node is subject
|
|
127
|
+
needs: list[tuple[str, str]] = [] # (tipo, nombre): lo que se decide en la vista
|
|
128
|
+
for cls in comp.classes:
|
|
129
|
+
if cls in node.classes:
|
|
130
|
+
continue
|
|
131
|
+
if cls in node.toggles:
|
|
132
|
+
needs.append(("toggle", cls))
|
|
133
|
+
elif node.dynamic is not None:
|
|
134
|
+
needs.append(("dynamic", cls))
|
|
135
|
+
elif node.passed and (comp.tag == node.tag or any(c in node.classes for c in comp.classes)):
|
|
136
|
+
# .boton.primary en la raíz de Boton: la activa <Boton class="primary">.
|
|
137
|
+
needs.append(("passed", cls))
|
|
138
|
+
else:
|
|
139
|
+
return None
|
|
140
|
+
needs.extend(("pseudo", p) for p in comp.pseudos)
|
|
141
|
+
if not needs:
|
|
142
|
+
return ALWAYS
|
|
143
|
+
if node.ir is None or (not is_self and node.doc != subject.doc):
|
|
144
|
+
if not build and sel.text not in self._warned:
|
|
145
|
+
self._warned.add(sel.text)
|
|
146
|
+
where = "la etiqueta de un componente" if node.ir is None else "un elemento fuera del slot"
|
|
147
|
+
self.warn(
|
|
148
|
+
f"'{sel.text}': el estado o la clase condicional de {where} no se puede usar aquí; la regla se ignora",
|
|
149
|
+
rule,
|
|
150
|
+
)
|
|
151
|
+
return None
|
|
152
|
+
if not build:
|
|
153
|
+
return "?"
|
|
154
|
+
return and_([self._condition(kind, name, node, is_self) for kind, name in needs])
|
|
155
|
+
|
|
156
|
+
# -- condiciones en la vista ---------------------------------------------
|
|
157
|
+
def _condition(self, kind: str, name: str, node: StyleNode, is_self: bool) -> str:
|
|
158
|
+
ir = node.ir
|
|
159
|
+
assert ir is not None
|
|
160
|
+
if kind == "toggle":
|
|
161
|
+
bid = node.toggles[name]
|
|
162
|
+
if is_self:
|
|
163
|
+
return f"!!jk.{bid}"
|
|
164
|
+
prop = _prop_name(name)
|
|
165
|
+
ir.props.setdefault(f"readonly property bool {prop}", Literal(f"!!jk.{bid}"))
|
|
166
|
+
return f"{self.ensure_id(ir)}.{prop}"
|
|
167
|
+
passed = f'{self.ensure_id(ir)}.jkInClass.indexOf(" {name} ") >= 0' if node.passed else None
|
|
168
|
+
if kind == "passed":
|
|
169
|
+
return passed
|
|
170
|
+
if kind == "dynamic":
|
|
171
|
+
if is_self:
|
|
172
|
+
cond = f'(jk.{node.dynamic} || "").indexOf(" {name} ") >= 0'
|
|
173
|
+
else:
|
|
174
|
+
ir.props.setdefault("readonly property string jkClasses", Literal(f'jk.{node.dynamic} || ""'))
|
|
175
|
+
cond = f'{self.ensure_id(ir)}.jkClasses.indexOf(" {name} ") >= 0'
|
|
176
|
+
return or_([cond, passed]) if passed else cond
|
|
177
|
+
return self.pseudo(ir, name)
|
|
178
|
+
|
|
179
|
+
def ensure_id(self, ir: IRElement) -> str:
|
|
180
|
+
if "id" not in ir.props:
|
|
181
|
+
ir.props["id"] = Literal(self.new_id())
|
|
182
|
+
return ir.props["id"].qml
|
|
183
|
+
|
|
184
|
+
def handler(self, ir: IRElement, kind: str) -> str:
|
|
185
|
+
"""Un HoverHandler o TapHandler hijo del elemento (uno de cada como mucho)."""
|
|
186
|
+
hid = f"{self.ensure_id(ir)}_{'hov' if kind == 'HoverHandler' else 'tap'}"
|
|
187
|
+
if not any(c.props.get("id") == Literal(hid) for c in ir.children if isinstance(c, IRElement)):
|
|
188
|
+
h = IRElement(kind, ir.loc)
|
|
189
|
+
h.props["id"] = Literal(hid)
|
|
190
|
+
ir.children.append(h)
|
|
191
|
+
return hid
|
|
192
|
+
|
|
193
|
+
def pseudo(self, ir: IRElement, name: str) -> str:
|
|
194
|
+
i = self.ensure_id(ir)
|
|
195
|
+
box = ir.qml_type in _BOXES
|
|
196
|
+
if name == "hover":
|
|
197
|
+
if box:
|
|
198
|
+
ir.props["jkTrackHover"] = Literal("true")
|
|
199
|
+
return f"{i}.hovered"
|
|
200
|
+
return f"{self.handler(ir, 'HoverHandler')}.hovered"
|
|
201
|
+
if name == "pressed":
|
|
202
|
+
if box:
|
|
203
|
+
ir.props["jkTrackPress"] = Literal("true")
|
|
204
|
+
return f"{i}.jkPressed"
|
|
205
|
+
return f"{self.handler(ir, 'TapHandler')}.pressed"
|
|
206
|
+
if name == "focus":
|
|
207
|
+
return f"{i}.activeFocus"
|
|
208
|
+
if name == "focus-visible":
|
|
209
|
+
# Las cajas solo toman el foco con el teclado; los controles dicen cómo lo tomaron.
|
|
210
|
+
return f"{i}.activeFocus" if box else f"({i}.activeFocus && {i}.focusReason !== Qt.MouseFocusReason)"
|
|
211
|
+
if name == "focus-within":
|
|
212
|
+
return f"Jk.within({i}, {i}.Window.activeFocusItem)"
|
|
213
|
+
if name == "disabled":
|
|
214
|
+
return f"!{i}.enabled"
|
|
215
|
+
if name == "dragging": # los pone qt_backend/events.py al arrastrar
|
|
216
|
+
return f"{i}.jkDragging"
|
|
217
|
+
if name == "drag-over":
|
|
218
|
+
return f"{i}.jkDragOver"
|
|
219
|
+
if name in ("checked", "selected", "expanded"):
|
|
220
|
+
return f"{i}.{name} === true"
|
|
221
|
+
# :first-child / :last-child: los marca el motor de <flex> (flex.js).
|
|
222
|
+
ir.props.setdefault("property bool jkFirst", Literal("false"))
|
|
223
|
+
ir.props.setdefault("property bool jkLast", Literal("false"))
|
|
224
|
+
return f"{i}.jkFirst" if name == "first-child" else f"{i}.jkLast"
|