htmlxify 1.0.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.
- htmlxify/__init__.py +0 -0
- htmlxify/cli.py +153 -0
- htmlxify/generators/__init__.py +0 -0
- htmlxify/generators/css_gen.py +574 -0
- htmlxify/generators/html_gen.py +184 -0
- htmlxify/generators/js_gen.py +260 -0
- htmlxify/parser/__init__.py +0 -0
- htmlxify/parser/ast_builder.py +412 -0
- htmlxify/parser/grammar.lark +70 -0
- htmlxify/parser/indent_processor.py +76 -0
- htmlxify/utils/__init__.py +0 -0
- htmlxify/validator/__init__.py +0 -0
- htmlxify/validator/semantic.py +241 -0
- htmlxify-1.0.0.dist-info/METADATA +775 -0
- htmlxify-1.0.0.dist-info/RECORD +19 -0
- htmlxify-1.0.0.dist-info/WHEEL +5 -0
- htmlxify-1.0.0.dist-info/entry_points.txt +2 -0
- htmlxify-1.0.0.dist-info/licenses/LICENSE +490 -0
- htmlxify-1.0.0.dist-info/top_level.txt +1 -0
|
@@ -0,0 +1,412 @@
|
|
|
1
|
+
"""
|
|
2
|
+
AST Builder - Converts Lark parse tree to custom Abstract Syntax Tree
|
|
3
|
+
PRODUCTION READY VERSION
|
|
4
|
+
"""
|
|
5
|
+
|
|
6
|
+
from pathlib import Path
|
|
7
|
+
from typing import Dict, Any, List, Optional
|
|
8
|
+
from lark import Lark, Transformer, Tree, Token
|
|
9
|
+
|
|
10
|
+
# Load grammar file
|
|
11
|
+
GRAMMAR_FILE = Path(__file__).parent / "grammar.lark"
|
|
12
|
+
|
|
13
|
+
|
|
14
|
+
class ASTTransformer(Transformer):
|
|
15
|
+
"""
|
|
16
|
+
Transforms Lark parse tree to custom AST
|
|
17
|
+
Matches grammar: start: element+
|
|
18
|
+
"""
|
|
19
|
+
|
|
20
|
+
def start(self, children: list) -> Dict[str, Any]:
|
|
21
|
+
"""Root: start: element+"""
|
|
22
|
+
elements = [c for c in children if c is not None]
|
|
23
|
+
return {
|
|
24
|
+
'type': 'Document',
|
|
25
|
+
'children': elements,
|
|
26
|
+
'meta': {}
|
|
27
|
+
}
|
|
28
|
+
|
|
29
|
+
def element(self, children: list) -> Dict[str, Any]:
|
|
30
|
+
"""
|
|
31
|
+
element: tag_with_selectors attributes? body? | tag_with_selectors
|
|
32
|
+
children[0] is always tag_with_selectors
|
|
33
|
+
"""
|
|
34
|
+
if not children:
|
|
35
|
+
return None
|
|
36
|
+
|
|
37
|
+
# First child is always tag_with_selectors
|
|
38
|
+
if isinstance(children[0], dict) and 'tag' in children[0]:
|
|
39
|
+
tag_data = children[0]
|
|
40
|
+
else:
|
|
41
|
+
# Fallback for old parser state
|
|
42
|
+
tag_data = {'tag': str(children[0]), 'classes': [], 'id': None}
|
|
43
|
+
|
|
44
|
+
node = {
|
|
45
|
+
'type': 'Element',
|
|
46
|
+
'tag': tag_data['tag'],
|
|
47
|
+
'classes': tag_data.get('classes', []),
|
|
48
|
+
'id': tag_data.get('id'),
|
|
49
|
+
'attributes': {},
|
|
50
|
+
'children': []
|
|
51
|
+
}
|
|
52
|
+
|
|
53
|
+
# Process optional attributes and body
|
|
54
|
+
for child in children[1:]:
|
|
55
|
+
if child is None:
|
|
56
|
+
continue
|
|
57
|
+
|
|
58
|
+
if isinstance(child, dict):
|
|
59
|
+
if child.get('_type') == 'attributes':
|
|
60
|
+
node['attributes'] = child['attrs']
|
|
61
|
+
elif child.get('_type') == 'body':
|
|
62
|
+
node['children'] = child['children']
|
|
63
|
+
|
|
64
|
+
return node
|
|
65
|
+
|
|
66
|
+
def tag_with_selectors(self, children: list) -> Dict[str, Any]:
|
|
67
|
+
"""
|
|
68
|
+
tag_with_selectors: WORD class_sel* id_sel?
|
|
69
|
+
First child is WORD (tag), rest are selectors
|
|
70
|
+
"""
|
|
71
|
+
tag = str(children[0])
|
|
72
|
+
classes = []
|
|
73
|
+
element_id = None
|
|
74
|
+
|
|
75
|
+
# Process selectors
|
|
76
|
+
for child in children[1:]:
|
|
77
|
+
if isinstance(child, dict):
|
|
78
|
+
if child.get('_type') == 'class':
|
|
79
|
+
classes.append(child['value'])
|
|
80
|
+
elif child.get('_type') == 'id':
|
|
81
|
+
element_id = child['value']
|
|
82
|
+
|
|
83
|
+
return {
|
|
84
|
+
'tag': tag,
|
|
85
|
+
'classes': classes,
|
|
86
|
+
'id': element_id
|
|
87
|
+
}
|
|
88
|
+
|
|
89
|
+
def class_sel(self, children: list) -> Dict[str, Any]:
|
|
90
|
+
"""class_sel: "." WORD"""
|
|
91
|
+
return {
|
|
92
|
+
'_type': 'class',
|
|
93
|
+
'value': str(children[0])
|
|
94
|
+
}
|
|
95
|
+
|
|
96
|
+
def id_sel(self, children: list) -> Dict[str, Any]:
|
|
97
|
+
"""id_sel: "#" WORD"""
|
|
98
|
+
return {
|
|
99
|
+
'_type': 'id',
|
|
100
|
+
'value': str(children[0])
|
|
101
|
+
}
|
|
102
|
+
|
|
103
|
+
def attributes(self, children: list) -> Dict[str, Any]:
|
|
104
|
+
"""attributes: "(" attr_list ")" """
|
|
105
|
+
attrs = children[0] if children else {}
|
|
106
|
+
return {
|
|
107
|
+
'_type': 'attributes',
|
|
108
|
+
'attrs': attrs
|
|
109
|
+
}
|
|
110
|
+
|
|
111
|
+
def attr_list(self, children: list) -> Dict[str, Any]:
|
|
112
|
+
"""attr_list: attribute ("," attribute)*"""
|
|
113
|
+
result = {}
|
|
114
|
+
for attr in children:
|
|
115
|
+
if isinstance(attr, dict):
|
|
116
|
+
result.update(attr)
|
|
117
|
+
return result
|
|
118
|
+
|
|
119
|
+
def attribute(self, children: list) -> Dict[str, Any]:
|
|
120
|
+
"""
|
|
121
|
+
attribute: attr_key ":" attr_value
|
|
122
|
+
Lark filters out ":", so children = [key, value]
|
|
123
|
+
"""
|
|
124
|
+
if len(children) >= 2:
|
|
125
|
+
key = str(children[0])
|
|
126
|
+
value = children[1]
|
|
127
|
+
return {key: value}
|
|
128
|
+
return {}
|
|
129
|
+
|
|
130
|
+
def attr_key(self, children: list) -> str:
|
|
131
|
+
"""attr_key: SPECIAL_ATTR | WORD"""
|
|
132
|
+
return str(children[0])
|
|
133
|
+
|
|
134
|
+
def attr_value(self, children: list) -> Any:
|
|
135
|
+
"""attr_value: STRING | NUMBER | WORD"""
|
|
136
|
+
return children[0]
|
|
137
|
+
|
|
138
|
+
def body(self, children: list) -> Dict[str, Any]:
|
|
139
|
+
"""body: "{" body_content "}" """
|
|
140
|
+
content = children[0] if children else []
|
|
141
|
+
return {
|
|
142
|
+
'_type': 'body',
|
|
143
|
+
'children': content
|
|
144
|
+
}
|
|
145
|
+
|
|
146
|
+
def body_content(self, children: list) -> List[Any]:
|
|
147
|
+
"""body_content: body_item*"""
|
|
148
|
+
return [c for c in children if c is not None]
|
|
149
|
+
|
|
150
|
+
def body_element(self, children: list) -> Dict[str, Any]:
|
|
151
|
+
"""Alias for full_element inside body"""
|
|
152
|
+
return children[0] if children else None
|
|
153
|
+
|
|
154
|
+
def body_text(self, children: list) -> Dict[str, Any]:
|
|
155
|
+
"""Alias for text_content inside body"""
|
|
156
|
+
return children[0] if children else None
|
|
157
|
+
|
|
158
|
+
def full_element(self, children: list) -> Dict[str, Any]:
|
|
159
|
+
"""
|
|
160
|
+
full_element: WORD class_sel* id_sel? attributes? body
|
|
161
|
+
First child is WORD, rest are optional selectors/attributes/body
|
|
162
|
+
"""
|
|
163
|
+
if not children:
|
|
164
|
+
return None
|
|
165
|
+
|
|
166
|
+
tag = str(children[0])
|
|
167
|
+
classes = []
|
|
168
|
+
element_id = None
|
|
169
|
+
attributes = {}
|
|
170
|
+
body_children = []
|
|
171
|
+
|
|
172
|
+
# Process rest of children
|
|
173
|
+
for child in children[1:]:
|
|
174
|
+
if child is None:
|
|
175
|
+
continue
|
|
176
|
+
if isinstance(child, dict):
|
|
177
|
+
if child.get('_type') == 'class':
|
|
178
|
+
classes.append(child['value'])
|
|
179
|
+
elif child.get('_type') == 'id':
|
|
180
|
+
element_id = child['value']
|
|
181
|
+
elif child.get('_type') == 'attributes':
|
|
182
|
+
attributes = child['attrs']
|
|
183
|
+
elif child.get('_type') == 'body':
|
|
184
|
+
body_children = child['children']
|
|
185
|
+
|
|
186
|
+
return {
|
|
187
|
+
'type': 'Element',
|
|
188
|
+
'tag': tag,
|
|
189
|
+
'classes': classes,
|
|
190
|
+
'id': element_id,
|
|
191
|
+
'attributes': attributes,
|
|
192
|
+
'children': body_children
|
|
193
|
+
}
|
|
194
|
+
|
|
195
|
+
def text_content(self, children: list) -> Dict[str, Any]:
|
|
196
|
+
"""text_content: text_token+"""
|
|
197
|
+
text_parts = []
|
|
198
|
+
for child in children:
|
|
199
|
+
if isinstance(child, str):
|
|
200
|
+
text_parts.append(child)
|
|
201
|
+
|
|
202
|
+
text = ' '.join(text_parts).strip()
|
|
203
|
+
if text:
|
|
204
|
+
return {
|
|
205
|
+
'type': 'Text',
|
|
206
|
+
'value': text
|
|
207
|
+
}
|
|
208
|
+
return None
|
|
209
|
+
|
|
210
|
+
def text_token(self, children: list) -> str:
|
|
211
|
+
"""text_token: TEXT_CHUNK | WORD"""
|
|
212
|
+
return str(children[0]) if children else ''
|
|
213
|
+
|
|
214
|
+
# ============================================================
|
|
215
|
+
# TERMINAL HANDLERS
|
|
216
|
+
# ============================================================
|
|
217
|
+
|
|
218
|
+
def WORD(self, token: Token) -> str:
|
|
219
|
+
return str(token)
|
|
220
|
+
|
|
221
|
+
def TEXT_CHUNK(self, token: Token) -> str:
|
|
222
|
+
return str(token)
|
|
223
|
+
|
|
224
|
+
def STRING(self, token: Token) -> str:
|
|
225
|
+
"""Remove quotes from strings"""
|
|
226
|
+
s = str(token)
|
|
227
|
+
if (s.startswith('"') and s.endswith('"')) or \
|
|
228
|
+
(s.startswith("'") and s.endswith("'")):
|
|
229
|
+
return s[1:-1]
|
|
230
|
+
return s
|
|
231
|
+
|
|
232
|
+
def NUMBER(self, token: Token) -> float:
|
|
233
|
+
try:
|
|
234
|
+
val = str(token)
|
|
235
|
+
if '.' in val:
|
|
236
|
+
return float(val)
|
|
237
|
+
return int(val)
|
|
238
|
+
except:
|
|
239
|
+
return 0
|
|
240
|
+
|
|
241
|
+
def SPECIAL_ATTR(self, token: Token) -> str:
|
|
242
|
+
return str(token)
|
|
243
|
+
|
|
244
|
+
|
|
245
|
+
|
|
246
|
+
|
|
247
|
+
class ASTBuilder:
|
|
248
|
+
"""
|
|
249
|
+
Main parser class - interfaces with Lark parser
|
|
250
|
+
PRODUCTION READY
|
|
251
|
+
"""
|
|
252
|
+
|
|
253
|
+
# Class-level parser cache for performance
|
|
254
|
+
_parser_cache = None
|
|
255
|
+
|
|
256
|
+
def __init__(self, source_code: str, filename: str):
|
|
257
|
+
self.source = source_code
|
|
258
|
+
self.filename = filename
|
|
259
|
+
self.parser = None
|
|
260
|
+
self._load_parser()
|
|
261
|
+
|
|
262
|
+
def _load_parser(self):
|
|
263
|
+
"""Load and cache Lark parser"""
|
|
264
|
+
# Use cached parser if available
|
|
265
|
+
if ASTBuilder._parser_cache is not None:
|
|
266
|
+
self.parser = ASTBuilder._parser_cache
|
|
267
|
+
return
|
|
268
|
+
|
|
269
|
+
try:
|
|
270
|
+
with open(GRAMMAR_FILE, 'r', encoding='utf-8') as f:
|
|
271
|
+
grammar = f.read()
|
|
272
|
+
|
|
273
|
+
# Create parser with optimized settings
|
|
274
|
+
self.parser = Lark(
|
|
275
|
+
grammar,
|
|
276
|
+
start='start',
|
|
277
|
+
parser='earley', # Handles ambiguity
|
|
278
|
+
lexer='dynamic', # Works with earley
|
|
279
|
+
propagate_positions=True, # Track line numbers
|
|
280
|
+
maybe_placeholders=True, # Allow None for optionals
|
|
281
|
+
ambiguity='resolve' # Auto-resolve ambiguity
|
|
282
|
+
)
|
|
283
|
+
|
|
284
|
+
# Cache for future instances
|
|
285
|
+
ASTBuilder._parser_cache = self.parser
|
|
286
|
+
|
|
287
|
+
except FileNotFoundError:
|
|
288
|
+
print(f"❌ Error: Grammar file not found: {GRAMMAR_FILE}")
|
|
289
|
+
raise
|
|
290
|
+
except Exception as e:
|
|
291
|
+
print(f"❌ Error loading grammar: {e}")
|
|
292
|
+
raise
|
|
293
|
+
|
|
294
|
+
def parse(self) -> Dict[str, Any]:
|
|
295
|
+
"""Parse source code into AST"""
|
|
296
|
+
try:
|
|
297
|
+
# Step 1: Parse with Lark
|
|
298
|
+
tree = self.parser.parse(self.source)
|
|
299
|
+
|
|
300
|
+
# Step 2: Transform to custom AST
|
|
301
|
+
transformer = ASTTransformer()
|
|
302
|
+
ast = transformer.transform(tree)
|
|
303
|
+
|
|
304
|
+
return ast
|
|
305
|
+
|
|
306
|
+
except Exception as e:
|
|
307
|
+
self._handle_parse_error(e)
|
|
308
|
+
raise
|
|
309
|
+
|
|
310
|
+
def _handle_parse_error(self, error: Exception):
|
|
311
|
+
"""Pretty-print parser errors"""
|
|
312
|
+
print(f"\n❌ Parse Error in {self.filename}:")
|
|
313
|
+
print(f" {str(error)}")
|
|
314
|
+
|
|
315
|
+
# Try to extract line number
|
|
316
|
+
error_str = str(error)
|
|
317
|
+
if 'line' in error_str.lower():
|
|
318
|
+
try:
|
|
319
|
+
import re
|
|
320
|
+
match = re.search(r'line (\d+)', error_str, re.IGNORECASE)
|
|
321
|
+
if match:
|
|
322
|
+
line_num = int(match.group(1))
|
|
323
|
+
lines = self.source.split('\n')
|
|
324
|
+
if 0 <= line_num - 1 < len(lines):
|
|
325
|
+
print(f"\n Line {line_num}: {lines[line_num - 1]}")
|
|
326
|
+
print(f" {'':>{len(str(line_num)) + 7}}^")
|
|
327
|
+
except:
|
|
328
|
+
pass
|
|
329
|
+
|
|
330
|
+
print()
|
|
331
|
+
|
|
332
|
+
|
|
333
|
+
# ============================================================
|
|
334
|
+
# TEST SUITE
|
|
335
|
+
# ============================================================
|
|
336
|
+
|
|
337
|
+
def test_parser():
|
|
338
|
+
"""Comprehensive test suite"""
|
|
339
|
+
|
|
340
|
+
tests = [
|
|
341
|
+
# Basic element
|
|
342
|
+
('div { Hello World }', 'Basic element with text'),
|
|
343
|
+
|
|
344
|
+
# Classes
|
|
345
|
+
('div.container { Test }', 'Single class'),
|
|
346
|
+
('div.container.main { Test }', 'Multiple classes'),
|
|
347
|
+
|
|
348
|
+
# ID
|
|
349
|
+
('div#app { Test }', 'ID selector'),
|
|
350
|
+
|
|
351
|
+
# Classes + ID
|
|
352
|
+
('div.container.main#app { Test }', 'Classes and ID'),
|
|
353
|
+
|
|
354
|
+
# Nested elements
|
|
355
|
+
('div { p { Nested } }', 'Nested element'),
|
|
356
|
+
|
|
357
|
+
# Multiple children
|
|
358
|
+
('div { p { One } p { Two } }', 'Multiple children'),
|
|
359
|
+
|
|
360
|
+
# Mixed content
|
|
361
|
+
('div { Some text p { Element } More text }', 'Mixed text and elements'),
|
|
362
|
+
|
|
363
|
+
# Attributes
|
|
364
|
+
('button(onclick: "test") { Click }', 'Simple attribute'),
|
|
365
|
+
('button(id: "btn", class: "primary") { Click }', 'Multiple attributes'),
|
|
366
|
+
|
|
367
|
+
# Special attributes
|
|
368
|
+
('button(⚡-call: "api") { Submit }', 'Backend call'),
|
|
369
|
+
('div(⚡-data: "userInfo") { }', 'Dynamic data'),
|
|
370
|
+
|
|
371
|
+
# Complex example
|
|
372
|
+
('''div.container#main {
|
|
373
|
+
header.navbar {
|
|
374
|
+
h1 { My App }
|
|
375
|
+
}
|
|
376
|
+
section.content {
|
|
377
|
+
p { Welcome to htmlxify }
|
|
378
|
+
button(⚡-call: "login") { Login }
|
|
379
|
+
}
|
|
380
|
+
}''', 'Complex nested structure'),
|
|
381
|
+
]
|
|
382
|
+
|
|
383
|
+
passed = 0
|
|
384
|
+
failed = 0
|
|
385
|
+
|
|
386
|
+
for code, description in tests:
|
|
387
|
+
print(f"\n{'='*60}")
|
|
388
|
+
print(f"Test: {description}")
|
|
389
|
+
print(f"{'='*60}")
|
|
390
|
+
print(f"Input:\n{code}\n")
|
|
391
|
+
|
|
392
|
+
try:
|
|
393
|
+
builder = ASTBuilder(code, 'test.htmlxify')
|
|
394
|
+
ast = builder.parse()
|
|
395
|
+
|
|
396
|
+
import json
|
|
397
|
+
print("PASSED")
|
|
398
|
+
print(json.dumps(ast, indent=2))
|
|
399
|
+
passed += 1
|
|
400
|
+
|
|
401
|
+
except Exception as e:
|
|
402
|
+
print(f"FAILED: {e}")
|
|
403
|
+
failed += 1
|
|
404
|
+
|
|
405
|
+
print(f"\n{'='*60}")
|
|
406
|
+
print(f"Results: {passed} passed, {failed} failed")
|
|
407
|
+
print(f"{'='*60}\n")
|
|
408
|
+
|
|
409
|
+
|
|
410
|
+
if __name__ == '__main__':
|
|
411
|
+
test_parser()
|
|
412
|
+
|
|
@@ -0,0 +1,70 @@
|
|
|
1
|
+
|
|
2
|
+
// Start: One or more top-level elements
|
|
3
|
+
start: element+
|
|
4
|
+
|
|
5
|
+
// Element syntax: tag[.class][#id][(attrs)][{body}]
|
|
6
|
+
element: tag_with_selectors attributes? body?
|
|
7
|
+
|
|
8
|
+
// Tag with optional selectors
|
|
9
|
+
tag_with_selectors: WORD class_sel* id_sel?
|
|
10
|
+
|
|
11
|
+
// Class selector: .classname
|
|
12
|
+
class_sel: "." WORD
|
|
13
|
+
|
|
14
|
+
// ID selector: #idname
|
|
15
|
+
id_sel: "#" WORD
|
|
16
|
+
|
|
17
|
+
// ============================================================
|
|
18
|
+
// ATTRIBUTES
|
|
19
|
+
// ============================================================
|
|
20
|
+
|
|
21
|
+
attributes: "(" attr_list ")"
|
|
22
|
+
|
|
23
|
+
attr_list: attribute ("," attribute)*
|
|
24
|
+
|
|
25
|
+
attribute: attr_key ":" attr_value
|
|
26
|
+
|
|
27
|
+
attr_key: SPECIAL_ATTR | WORD
|
|
28
|
+
|
|
29
|
+
attr_value: STRING | NUMBER | WORD
|
|
30
|
+
|
|
31
|
+
// ============================================================
|
|
32
|
+
// BODY (Content)
|
|
33
|
+
// ============================================================
|
|
34
|
+
|
|
35
|
+
body: "{" body_content "}"
|
|
36
|
+
|
|
37
|
+
// body_content: Items can be full elements or text
|
|
38
|
+
body_content: body_item*
|
|
39
|
+
|
|
40
|
+
// body_item: Try element first (with at least attributes or body), then text
|
|
41
|
+
body_item: full_element -> body_element
|
|
42
|
+
| text_content -> body_text
|
|
43
|
+
|
|
44
|
+
// full_element: Has either attributes, body, or both (this disambiguates from plain text)
|
|
45
|
+
full_element: WORD class_sel* id_sel? (attributes | body | attributes body)
|
|
46
|
+
|
|
47
|
+
// text_content: Text chunks or plain words
|
|
48
|
+
text_content: text_token+
|
|
49
|
+
|
|
50
|
+
text_token: TEXT_CHUNK | WORD
|
|
51
|
+
|
|
52
|
+
// ============================================================
|
|
53
|
+
// TERMINALS
|
|
54
|
+
// ============================================================
|
|
55
|
+
|
|
56
|
+
COMMENT: "//" /[^\n]*/
|
|
57
|
+
|
|
58
|
+
SPECIAL_ATTR.10: "⚡-call" | "⚡-data"
|
|
59
|
+
|
|
60
|
+
STRING.9: /"[^"]*"/ | /'[^']*'/
|
|
61
|
+
|
|
62
|
+
NUMBER.8: /-?\d+\.?\d*/
|
|
63
|
+
|
|
64
|
+
WORD.7: /[a-zA-Z_][a-zA-Z0-9_-]*/
|
|
65
|
+
|
|
66
|
+
TEXT_CHUNK.1: /[a-zA-Z0-9.!?;:'"&%$@*+=<>\/\[\]\\|~`\s\-–—,]+/
|
|
67
|
+
|
|
68
|
+
%import common.WS
|
|
69
|
+
%ignore WS
|
|
70
|
+
%ignore COMMENT
|
|
@@ -0,0 +1,76 @@
|
|
|
1
|
+
"""
|
|
2
|
+
Indentation Processor - Converts flat indented elements to nested tree
|
|
3
|
+
"""
|
|
4
|
+
|
|
5
|
+
from typing import Dict, Any, List
|
|
6
|
+
|
|
7
|
+
|
|
8
|
+
class IndentationProcessor:
|
|
9
|
+
"""
|
|
10
|
+
Processes indentation to create hierarchical structure.
|
|
11
|
+
|
|
12
|
+
Example:
|
|
13
|
+
div { # indent 0
|
|
14
|
+
p { # indent 1 -> child of div
|
|
15
|
+
text # indent 2 -> child of p
|
|
16
|
+
}
|
|
17
|
+
span { # indent 1 -> sibling of p
|
|
18
|
+
text
|
|
19
|
+
}
|
|
20
|
+
}
|
|
21
|
+
"""
|
|
22
|
+
|
|
23
|
+
def process(self, ast: Dict[str, Any]) -> Dict[str, Any]:
|
|
24
|
+
"""Convert flat list with indent info to nested tree"""
|
|
25
|
+
if ast['type'] != 'Document':
|
|
26
|
+
return ast
|
|
27
|
+
|
|
28
|
+
elements = ast['children']
|
|
29
|
+
if not elements:
|
|
30
|
+
return ast
|
|
31
|
+
|
|
32
|
+
# Build hierarchy using a stack
|
|
33
|
+
root = {'type': 'Root', 'children': []}
|
|
34
|
+
stack = [(root, -1)] # (node, indent_level)
|
|
35
|
+
|
|
36
|
+
for element in elements:
|
|
37
|
+
if not isinstance(element, dict):
|
|
38
|
+
continue
|
|
39
|
+
|
|
40
|
+
indent = element.get('meta', {}).get('indent_level', 0)
|
|
41
|
+
|
|
42
|
+
# Pop stack until we find the parent
|
|
43
|
+
while len(stack) > 1 and stack[-1][1] >= indent:
|
|
44
|
+
stack.pop()
|
|
45
|
+
|
|
46
|
+
# Add element to current parent
|
|
47
|
+
parent = stack[-1][0]
|
|
48
|
+
parent['children'].append(element)
|
|
49
|
+
|
|
50
|
+
# Push element onto stack
|
|
51
|
+
stack.append((element, indent))
|
|
52
|
+
|
|
53
|
+
return root
|
|
54
|
+
|
|
55
|
+
|
|
56
|
+
# Test
|
|
57
|
+
if __name__ == '__main__':
|
|
58
|
+
from ast_builder import ASTBuilder
|
|
59
|
+
|
|
60
|
+
code = '''
|
|
61
|
+
div {
|
|
62
|
+
p { Outer }
|
|
63
|
+
div {
|
|
64
|
+
p { Nested }
|
|
65
|
+
}
|
|
66
|
+
}
|
|
67
|
+
'''
|
|
68
|
+
|
|
69
|
+
builder = ASTBuilder(code, 'test.htmlxify')
|
|
70
|
+
ast = builder.parse()
|
|
71
|
+
|
|
72
|
+
processor = IndentationProcessor()
|
|
73
|
+
nested_ast = processor.process(ast)
|
|
74
|
+
|
|
75
|
+
import json
|
|
76
|
+
print(json.dumps(nested_ast, indent=2))
|
|
File without changes
|
|
File without changes
|