-
Notifications
You must be signed in to change notification settings - Fork 4
Expand file tree
/
Copy pathcontainers.py
More file actions
1023 lines (945 loc) · 45.2 KB
/
Copy pathcontainers.py
File metadata and controls
1023 lines (945 loc) · 45.2 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
"""Build Elementor container structures from sections."""
from __future__ import annotations
import re as _re
from typing import Any
from .colors import to_hex, is_dark
from .styles import css_padding_to_elementor, px_to_int
from .widgets import walk_and_emit, is_hero_bg_image, is_icon_box, _iter
def _parse_grid_columns(grid_template_columns: str) -> int:
"""Parse grid-template-columns and return the number of explicit columns."""
if not grid_template_columns:
return 1
val = grid_template_columns.strip()
# repeat(N, ...) → N columns
m = _re.match(r"repeat\(\s*(\d+)\s*,", val)
if m:
return int(m.group(1))
# repeat(auto-fill/auto-fit, ...) → can't determine statically, return 0
if "auto-fill" in val or "auto-fit" in val:
return 0
# Space-separated list of track sizes: "1fr 2fr 1fr" → 3
return len(val.split())
def _parse_grid_tracks(grid_template_columns: str) -> list[float] | None:
"""Parse grid-template-columns into a list of relative fr weights.
"1.5fr 1fr 1fr" → [1.5, 1.0, 1.0]
"repeat(3, 1fr)" → [1.0, 1.0, 1.0]
Non-fr tracks (px, %, auto) fall back to equal weights so we don't
mis-proportion rows. Returns None when the grid is indeterminate
(auto-fit / auto-fill / empty).
"""
if not grid_template_columns:
return None
val = grid_template_columns.strip()
if "auto-fill" in val or "auto-fit" in val:
return None
# Expand repeat(N, TRACKS) once so "repeat(3, 1fr)" becomes "1fr 1fr 1fr"
m = _re.match(r"repeat\(\s*(\d+)\s*,\s*(.+)\)\s*$", val)
if m:
n = int(m.group(1))
inner = m.group(2).strip()
val = " ".join([inner] * n)
parts = val.split()
weights: list[float] = []
for p in parts:
fr = _re.match(r"([\d.]+)fr$", p)
if fr:
try:
weights.append(float(fr.group(1)))
except ValueError:
weights.append(1.0)
else:
# Unknown unit (px/%/auto/minmax(...)) → treat as equal-weight.
# Still preserves column count, just loses proportional sizing.
weights.append(1.0)
return weights if weights else None
def map_section(section: dict) -> tuple[dict[str, Any], list[dict]]:
container = _section_settings(section)
sec_tag = section.get("tag", "")
sec_display = section.get("styles", {}).get("display", "")
if sec_tag in ("header", "nav", "footer"):
# Check for a grid layout inside footer — if found, fall through to
# normal section handling so the grid columns are preserved.
has_grid_child = any(
(c.get("styles", {}).get("display") or "") == "grid"
for c in _iter(section)
if c is not section
)
use_header_builder = (sec_tag in ("header", "nav")) or (sec_tag == "footer" and not has_grid_child)
if use_header_builder:
is_flex_row = sec_display == "flex" or sec_tag in ("header", "nav")
if is_flex_row:
container["flex_direction"] = "row"
container["flex_direction_tablet"] = "row"
container["flex_direction_mobile"] = "column"
container["flex_justify_content"] = "space-between"
container["flex_align_items"] = "center"
container["flex_wrap"] = "nowrap"
container["flex_wrap_tablet"] = "wrap"
container["content_width"] = "full"
inner = _find_content_wrapper(section)
if inner and inner is not section:
inner_p = css_padding_to_elementor(inner.get("styles", {}))
for side in ("top", "bottom"):
if inner_p[side] != "0":
container["padding"][side] = inner_p[side]
for side in ("top", "bottom"):
if int(container["padding"][side]) < 12:
container["padding"][side] = "16"
return container, _build_header_elements(section)
# Footer with grid inside: fall through to generic section handling
# Split hero: flex row with 2 children (image + content)
split = _detect_split_layout(section)
if split:
first_node, second_node = split
# Determine which is image and which is content
first_styles = first_node.get("styles", {})
first_has_bg = "url(" in (first_styles.get("background-image", "") or first_styles.get("background", ""))
if first_has_bg:
img_node, content_node = first_node, second_node
else:
img_node, content_node = second_node, first_node
container["flex_direction"] = "row"
container["flex_direction_tablet"] = "row"
container["flex_direction_mobile"] = "column"
container["flex_align_items"] = "stretch"
container["content_width"] = "full"
container["padding"] = {"unit": "px", "top": "0", "right": "0", "bottom": "0", "left": "0", "isLinked": True}
# Image side
img_styles = img_node.get("styles", {})
bg_url = img_styles.get("background-image", "")
import re as _re
url_match = _re.search(r"url\(['\"]?([^)'\"\s]+)['\"]?\)", bg_url)
img_container: dict[str, Any] = {
"__inner_container__": True,
"settings": {
"content_width": "full",
"flex_direction": "column",
"_element_width": "initial",
"_element_custom_width": {"unit": "%", "size": 50, "sizes": []},
"_element_custom_width_mobile": {"unit": "%", "size": 100, "sizes": []},
},
"children": [],
}
if url_match:
img_container["settings"]["background_background"] = "classic"
img_container["settings"]["background_image"] = {"url": url_match.group(1), "id": ""}
img_container["settings"]["background_size"] = "cover"
img_container["settings"]["background_position"] = "center center"
img_container["settings"]["min_height"] = {"unit": "vh", "size": 60, "sizes": []}
# Content side
content_elements = walk_and_emit(content_node)
content_elements = _group_into_grids(content_elements)
content_padding = css_padding_to_elementor(content_node.get("styles", {}))
# Ensure minimum padding so content isn't flush
for side in ("top", "bottom"):
if int(content_padding.get(side, "0")) < 40:
content_padding[side] = "60"
for side in ("left", "right"):
if int(content_padding.get(side, "0")) < 20:
content_padding[side] = "40"
content_container: dict[str, Any] = {
"__inner_container__": True,
"settings": {
"content_width": "full",
"flex_direction": "column",
"flex_justify_content": "center",
"flex_gap": {"unit": "px", "size": 20, "column": "20", "row": "20"},
"padding": content_padding,
"_element_width": "initial",
"_element_custom_width": {"unit": "%", "size": 50, "sizes": []},
"_element_custom_width_mobile": {"unit": "%", "size": 100, "sizes": []},
},
"children": content_elements,
}
# Return in original DOM order
if first_has_bg:
return container, [img_container, content_container]
else:
return container, [content_container, img_container]
# Flex-row section with uniform children (stats bar, logo bar, etc.)
# → each child becomes an inner column container
sec_styles = section.get("styles", {})
sec_display = sec_styles.get("display", "")
sec_dir = sec_styles.get("flex-direction", "row")
if sec_display == "flex" and sec_dir in ("row", ""):
children = [c for c in section.get("children", []) if c.get("tag") == "div"]
if len(children) >= 3:
container["flex_direction"] = "row"
container["flex_direction_tablet"] = "row"
container["flex_direction_mobile"] = "column"
container["flex_wrap"] = "nowrap"
container["flex_wrap_tablet"] = "wrap"
container["flex_justify_content"] = "center"
container["flex_align_items"] = "stretch"
container["content_width"] = "full"
gap = sec_styles.get("gap", "24px").split()[0]
container["flex_gap"] = {"unit": "px", "size": px_to_int(gap) or 24, "column": gap, "row": gap}
n = len(children)
col_pct = int((100 - (n - 1) * 2) / n)
cols: list[dict] = []
for child in children:
child_widgets = walk_and_emit(child)
child_styles = child.get("styles", {})
col_settings: dict[str, Any] = {
"content_width": "full",
"flex_direction": "column",
"flex_align_items": "center",
"padding": css_padding_to_elementor(child_styles),
"_element_width": "initial",
"_element_width_tablet": "initial",
"_element_width_mobile": "initial",
"_element_custom_width": {"unit": "%", "size": col_pct, "sizes": []},
"_element_custom_width_tablet": {"unit": "%", "size": 47, "sizes": []},
"_element_custom_width_mobile": {"unit": "%", "size": 100, "sizes": []},
}
# Child border (e.g., border-right divider on features strip)
for side in ("right", "left", "top", "bottom"):
bw = px_to_int(child_styles.get(f"border-{side}-width"))
if bw:
col_settings.setdefault("border_border", "solid")
col_settings.setdefault("border_width", {
"unit": "px", "top": "0", "right": "0",
"bottom": "0", "left": "0", "isLinked": False,
})
col_settings["border_width"][side] = str(bw)
bc = to_hex(child_styles.get(f"border-{side}-color"))
if bc:
col_settings["border_color"] = bc
col: dict[str, Any] = {
"__inner_container__": True,
"settings": col_settings,
"children": child_widgets,
}
from .styles import apply_card_styling as acs
acs(col["settings"], child.get("styles", {}))
cols.append(col)
return container, cols
consumed: set[int] = set()
bg_img = _find_hero_bg(section, consumed)
if bg_img:
container["background_background"] = "classic"
container["background_image"] = {"url": bg_img["src"], "id": ""}
container["background_size"] = "cover"
container["background_position"] = "center center"
container["background_overlay_background"] = "classic"
container["background_overlay_color"] = "#000000"
container["background_overlay_opacity"] = {"unit": "px", "size": 0.45, "sizes": []}
container["min_height"] = {"unit": "px", "size": 600, "sizes": []}
container["flex_direction"] = "column"
# Preserve original alignment — don't force left
sec_jc = sec_styles.get("justify-content") or ""
sec_ai = sec_styles.get("align-items") or ""
sec_ta = sec_styles.get("text-align") or ""
if sec_jc == "center" or sec_ta == "center":
container["flex_align_items"] = "center"
container["flex_justify_content"] = "center"
else:
container["flex_align_items"] = "flex-start"
container["flex_justify_content"] = "center"
container["__dark_bg__"] = True
elements = _walk_skip(section, consumed)
elements = _group_into_grids(elements, container.get("flex_align_items", "center"))
if container.pop("__dark_bg__", False):
_invert_text_colors(elements)
else:
# Check if the section bg needs white text (dark OR saturated bg)
sec_styles = section.get("styles", {})
section_bg = to_hex(
sec_styles.get("background-color") or sec_styles.get("backgroundColor") or
sec_styles.get("background") or sec_styles.get("bg") or ""
)
if section_bg and len(section_bg) <= 7:
from .colors import contrast_ratio, relative_luminance
# White text when: bg is dark OR bg is vivid/saturated (mid-luminance)
# Use luminance < 0.4 as threshold — covers dark + saturated colors
lum = relative_luminance(section_bg)
if lum < 0.4:
_invert_text_colors(elements)
# If section has horizontal margin, wrap in a transparent outer section
# with padding, and move bg/radius to inner container (prevents overflow)
sec_styles = section.get("styles", {})
ml = px_to_int(sec_styles.get("margin-left", "0"))
mr = px_to_int(sec_styles.get("margin-right", "0"))
if ml or mr:
# Move bg, gradient, radius, padding from section to inner container
inner_settings: dict[str, Any] = {
"content_width": "full",
"flex_direction": container.get("flex_direction", "column"),
"flex_justify_content": container.get("flex_justify_content", "center"),
"flex_align_items": container.get("flex_align_items", "center"),
"flex_gap": container.get("flex_gap", {"unit": "px", "size": 20, "column": "20", "row": "20"}),
}
# Move styling keys to inner
for key in list(container.keys()):
if key.startswith("background") or key.startswith("border"):
inner_settings[key] = container.pop(key)
# Move padding to inner
if "padding" in container:
inner_settings["padding"] = container.pop("padding")
# Outer becomes transparent wrapper with margin as padding
mt = px_to_int(sec_styles.get("margin-top", "0"))
mb = px_to_int(sec_styles.get("margin-bottom", "0"))
container["content_width"] = "full"
container["flex_direction"] = "column"
container["padding"] = {
"unit": "px",
"top": str(mt or 0), "right": str(mr or 0),
"bottom": str(mb or 0), "left": str(ml or 0),
"isLinked": False,
}
container.pop("margin", None)
# Wrap elements in inner container
inner = {
"__inner_container__": True,
"settings": inner_settings,
"children": elements,
}
return container, [inner]
return container, elements
def _section_settings(section: dict) -> dict[str, Any]:
styles = section.get("styles", {})
wrapper = _find_content_wrapper(section)
w_styles = wrapper.get("styles", {}) if wrapper else styles
bg = (styles.get("background-color") or styles.get("backgroundColor") or
styles.get("background") or styles.get("bg"))
display = (w_styles.get("display") or "")
is_flex = display in ("flex", "inline-flex", "grid")
flex_dir = "column"
# For column (vertical) sections, use stretch so child widgets take full
# width — then each widget's own align setting (from text-align) controls
# horizontal positioning of its content. This handles both "centered
# hero" (widgets stretched, text centered) and "left-aligned hero"
# (widgets stretched, text left-aligned) uniformly.
align = "stretch"
justify = "flex-start"
if display == "grid":
# CSS grid → Elementor row container. Determine column count from
# grid-template-columns so _group_into_grids can chunk correctly.
gtc = w_styles.get("grid-template-columns", "")
ncols = _parse_grid_columns(gtc)
if ncols >= 2:
flex_dir = "row"
elif is_flex:
fd = w_styles.get("flex-direction") or w_styles.get("flexDirection") or "column"
flex_dir = "row" if fd.startswith("row") else "column"
ai = w_styles.get("align-items") or w_styles.get("alignItems")
if ai and ai not in ("normal", "stretch", "center"):
mapping = {"flex-start": "flex-start", "start": "flex-start",
"flex-end": "flex-end", "end": "flex-end", "center": "center"}
align = mapping.get(ai, "center")
jc = w_styles.get("justify-content") or w_styles.get("justifyContent")
if jc and jc not in ("normal", "center"):
mapping = {"flex-start": "flex-start", "start": "flex-start",
"flex-end": "flex-end", "end": "flex-end",
"space-between": "space-between", "space-around": "space-around"}
justify = mapping.get(jc, "center")
padding = css_padding_to_elementor(styles)
if wrapper and wrapper is not section:
wp = css_padding_to_elementor(wrapper.get("styles", {}))
for side in ("left", "right"):
if padding[side] == "0" and wp[side] != "0":
padding[side] = wp[side]
for side in ("left", "right"):
if int(padding[side]) < 20:
padding[side] = "40"
# Read gap from CSS (row-gap / column-gap / gap shorthand)
raw_gap = (w_styles.get("gap") or w_styles.get("row-gap") or
styles.get("gap") or styles.get("row-gap") or "")
gap_val = px_to_int(raw_gap) if raw_gap else None
# Only use default gap if section is flex/grid; otherwise margins handle spacing
gap_px = gap_val if gap_val is not None else (20 if is_flex else 0)
gap_str = str(gap_px)
settings: dict[str, Any] = {
"content_width": "boxed",
"flex_direction": flex_dir,
"flex_justify_content": justify,
"flex_align_items": align,
"flex_gap": {"unit": "px", "size": gap_px, "column": gap_str, "row": gap_str},
"padding": padding,
}
# Check for gradient background first
bg_raw = styles.get("background") or styles.get("background-image") or ""
if "linear-gradient" in bg_raw or "radial-gradient" in bg_raw:
_apply_gradient(settings, bg_raw)
else:
bg_hex = to_hex(bg)
if bg_hex:
settings["background_background"] = "classic"
settings["background_color"] = bg_hex
# Section borders (top/bottom lines on features strips, dividers, etc.)
for side in ("top", "bottom"):
bw_key = f"border-{side}-width"
bw = px_to_int(styles.get(bw_key))
if bw:
settings.setdefault("border_border", "solid")
settings.setdefault("border_width", {
"unit": "px", "top": "0", "right": "0",
"bottom": "0", "left": "0", "isLinked": False,
})
settings["border_width"][side] = str(bw)
bc_key = f"border-{side}-color"
bc = to_hex(styles.get(bc_key) or styles.get("border-color"))
if bc:
settings["border_color"] = bc
# Section border-radius
br = styles.get("border-radius") or styles.get("border-top-left-radius") or ""
br_val = px_to_int(br) if br else None
if br_val:
settings["border_radius"] = {
"unit": "px",
"top": str(br_val), "right": str(br_val),
"bottom": str(br_val), "left": str(br_val),
"isLinked": True,
}
# Section margin — only top/bottom applied directly.
# Left/right margin handled in map_section via wrapper approach.
mt = px_to_int(styles.get("margin-top", "0"))
mb = px_to_int(styles.get("margin-bottom", "0"))
if mt or mb:
settings["margin"] = {
"unit": "px",
"top": str(mt or 0), "right": "0",
"bottom": str(mb or 0), "left": "0",
"isLinked": False,
}
return settings
def _apply_gradient(settings: dict, css: str) -> None:
"""Parse CSS linear-gradient and apply as Elementor gradient background."""
import re
settings["background_background"] = "gradient"
# Extract angle
angle_match = re.search(r"(\d+)deg", css)
angle = int(angle_match.group(1)) if angle_match else 180
# Extract color stops
colors = re.findall(r"(#[0-9a-fA-F]{3,8}|rgba?\([^)]+\))", css)
color1 = to_hex(colors[0]) if colors else "#ffffff"
color2 = to_hex(colors[-1]) if len(colors) > 1 else color1
settings["background_color"] = color1
settings["background_color_b"] = color2
settings["background_gradient_angle"] = {"unit": "deg", "size": angle, "sizes": []}
settings["background_gradient_position"] = "center center"
def _detect_split_layout(section: dict) -> tuple[dict, dict] | None:
"""Detect a flex-row section with exactly 2 children: one image, one content.
Common pattern: hero with image left + text right (or vice versa)."""
styles = section.get("styles", {})
display = styles.get("display", "")
direction = styles.get("flex-direction", "")
if display != "flex" or direction not in ("row", "row-reverse", ""):
return None
children = [c for c in section.get("children", []) if c.get("tag") in ("div", "section", "article")]
if len(children) != 2:
return None
# Identify which child is image and which is content
for i, child in enumerate(children):
child_styles = child.get("styles", {})
bg_img_val = child_styles.get("background-image", "") or child_styles.get("background", "")
has_bg_img = "url(" in bg_img_val
# Skip overlays — divs with semi-transparent bg but no image and no text
is_overlay = (
not has_bg_img and
not child.get("text") and
not child.get("children") and
("rgba" in (child_styles.get("background", "") or child_styles.get("background-color", "")))
)
if is_overlay:
continue
has_no_text = not child.get("text") and not any(
gc.get("tag") in ("h1", "h2", "h3", "p") for gc in child.get("children", [])
)
if has_bg_img or (has_no_text and not is_overlay):
other = children[1 - i]
# Return in ORIGINAL DOM order (preserve left/right)
if i == 0:
return (child, other) # image first (left), content second (right)
else:
return (other, child) # content first (left), image second (right)
return None
def _find_content_wrapper(section: dict) -> dict | None:
node = section
for _ in range(4):
children = [c for c in node.get("children", []) if c.get("tag") not in ("script", "style", None)]
if len(children) != 1:
return node
ch = children[0]
if ch.get("tag") in ("div", "section", "article"):
# Stop before descending into a multi-column grid/flex container.
# Those are content grids that walk_and_emit() should handle via
# _is_card_grid() — promoting their direction to the section level
# collapses the grid into a flat row of mixed widgets.
ch_styles = ch.get("styles", {})
ch_display = ch_styles.get("display", "")
if ch_display == "grid":
ncols = _parse_grid_columns(ch_styles.get("grid-template-columns", ""))
if ncols >= 2:
return node
elif ch_display in ("flex", "inline-flex"):
fd = ch_styles.get("flex-direction", "row")
if not fd.startswith("column") and len(ch.get("children", [])) >= 2:
# Flex-row with 2+ children — this is a content row, stop here.
# Exception: if child has a .container-style class (max-width wrapper)
# it's just a centering shell, keep descending.
cls = " ".join(ch.get("classes", [])).lower()
if not any(k in cls for k in ("container", "wrapper", "inner", "content")):
return node
node = ch
else:
return node
return node
def _find_hero_bg(section: dict, consumed: set[int]) -> dict | None:
"""Find hero bg image — only check first 2 levels (not deep inside cards)."""
for node in _iter(section, max_depth=2):
if is_hero_bg_image(node, section):
consumed.add(id(node))
return node
return None
def _walk_skip(node: dict, consumed: set[int]) -> list[dict]:
return walk_and_emit(node, consumed)
def _group_into_grids(elements: list[dict], parent_align: str = "center") -> list[dict]:
out: list[dict] = []
i = 0
while i < len(elements):
el = elements[i]
wt = el.get("widgetType")
# Group 3+ consecutive cards (icon-box, image-box, or inner containers) into a grid
is_card = wt in ("icon-box", "image-box") or el.get("__inner_container__")
if is_card and el.get("_no_group"):
# Card explicitly opted out of row grouping (block/flex-column parent)
el.pop("_no_group", None)
out.append(el)
i += 1
continue
if is_card:
group = [el]
# Sentinel values that identify which source grid a card came
# from — we only merge cards into one group if they share all
# of these, otherwise a section with two grids (e.g. a 2-col
# .showcase-header followed by a 3-col .aicom-mod-grid) would
# get chunked uniformly by whichever grid appeared first.
def _grid_key(c):
return (
c.get("_grid_cols"),
c.get("_grid_max_width"),
c.get("_grid_gap"),
tuple(c.get("_grid_tracks") or ()),
c.get("_grid_align_items"),
bool(c.get("_grid_stack_tablet")),
bool(c.get("_grid_stack_mobile")),
)
head_key = _grid_key(el)
j = i + 1
while j < len(elements):
nxt = elements[j]
if (nxt.get("widgetType") in ("icon-box", "image-box") or nxt.get("__inner_container__")) \
and _grid_key(nxt) == head_key:
group.append(nxt)
j += 1
else:
break
if len(group) >= 2:
grid_cols = group[0].get("_grid_cols") if group else None
grid_max_width = group[0].get("_grid_max_width") if group else None
grid_gap = group[0].get("_grid_gap") if group else None
def _extras_from(cards_list):
# Read spacing extras from the FIRST card of each chunk — not
# from the first of the whole group. When a section mixes
# showcase-header (no per-row padding) with repeated .mod
# rows (padding: 72px 0; border-top: 1px), each chunk needs
# its own source-of-truth for per-row padding/border.
first = cards_list[0] if cards_list else {}
return {
"margin": first.get("_grid_margin"),
"padding": first.get("_grid_padding"),
"border_top": first.get("_grid_border_top"),
"tracks": first.get("_grid_tracks"),
"align_items": first.get("_grid_align_items"),
"stack_tablet": first.get("_grid_stack_tablet"),
"stack_mobile": first.get("_grid_stack_mobile"),
}
if grid_cols and grid_cols < len(group):
# Check if all cards share uniform per-row properties (no
# per-chunk padding/border differences). If so, emit a
# single wrapping row with width-per-card = 1/grid_cols,
# letting flex-wrap produce clean N-per-row breaks at all
# breakpoints (desktop 3-col, tablet 2-col, mobile 1-col).
# Otherwise fall back to explicit chunking.
uniform = all(
c.get("_grid_padding") == group[0].get("_grid_padding") and
c.get("_grid_border_top") == group[0].get("_grid_border_top")
for c in group
)
if uniform:
out.append(_wrap_row(group, grid_max_width, grid_gap,
_extras_from(group), cols_per_row=grid_cols))
else:
for chunk_start in range(0, len(group), grid_cols):
chunk = group[chunk_start:chunk_start + grid_cols]
out.append(_wrap_row(chunk, grid_max_width, grid_gap, _extras_from(chunk)))
else:
out.append(_wrap_row(group, grid_max_width, grid_gap, _extras_from(group)))
i = j
continue
# Group 2+ consecutive buttons into an inline row
if wt == "button":
group = [el]
j = i + 1
while j < len(elements) and elements[j].get("widgetType") == "button":
group.append(elements[j])
j += 1
if len(group) >= 2:
out.append(_wrap_buttons(group, parent_align))
i = j
continue
out.append(el)
i += 1
return out
def _wrap_buttons(buttons: list[dict], parent_align: str = "flex-start") -> dict:
"""Wrap 2+ buttons in a horizontal flex row, inheriting parent alignment."""
return {
"__inner_container__": True,
"settings": {
"content_width": "full",
"flex_direction": "row",
"flex_direction_tablet": "row",
"flex_direction_mobile": "column",
"flex_wrap": "wrap",
"flex_justify_content": parent_align,
"flex_align_items": "center",
"flex_gap": {"unit": "px", "size": 16, "column": "16", "row": "16"},
},
"children": buttons,
}
def _wrap_row(widgets: list[dict], max_width: int | None = None, gap: int | None = None,
extras: dict | None = None, cols_per_row: int | None = None) -> dict:
n = max(len(widgets), 1)
extras = extras or {}
# When cols_per_row is set (multi-row wrap mode), widths are based on the
# intended per-row count, not the total card count.
width_n = cols_per_row if cols_per_row else n
tablet_width_pct = 100 if extras.get("stack_tablet") else 47
# Proportional widths from grid-template-columns fr tracks (e.g.
# "1.5fr 1fr 1fr" → first col ~43%, others ~28%). Falls back to equal
# split when tracks are absent or counts don't match the widget count.
tracks = extras.get("tracks")
if tracks and len(tracks) == width_n and sum(tracks) > 0 and not cols_per_row:
# Reserve 2% per gap between columns for visual breathing room,
# matching the equal-split heuristic, then distribute the remainder
# by track weights.
available = 100 - (width_n - 1) * 2
total = sum(tracks)
pcts = [max(5, int(round(available * t / total))) for t in tracks]
else:
# Leave more breathing room when wrapping: gaps are in px (not %) and
# at larger gaps (40-48px) they consume enough space that tight %
# widths push the last card onto a new row.
if cols_per_row:
# Budget ~5% per gap so 3-col with 48px gap still fits at 1240px:
# (100 - 2*5)/3 = 30% × 3 = 90% + 2×~4% gap ≈ 98% < 100%.
reserve_per_gap = 5
else:
reserve_per_gap = 2
equal = int((100 - (width_n - 1) * reserve_per_gap) / width_n)
pcts = [equal] * n
widgets_with_widths = []
for w, desktop_pct in zip(widgets, pcts):
w_copy = dict(w)
s = dict(w_copy.get("settings", {}))
if w_copy.get("__inner_container__"):
# Inner containers inside a row: force content_width=full so Elementor
# doesn't insert .e-con-inner wrapper, which breaks flex-grow width calc.
s["content_width"] = "full"
# Elementor 4.x containers use `width` (not _element_custom_width) for sizing.
s["width"] = {"unit": "%", "size": desktop_pct, "sizes": []}
s["width_tablet"] = {"unit": "%", "size": tablet_width_pct, "sizes": []}
s["width_mobile"] = {"unit": "%", "size": 100, "sizes": []}
else:
# Widgets: explicit percentage widths
s["_element_width"] = "initial"
s["_element_width_tablet"] = "initial"
s["_element_width_mobile"] = "initial"
s["_element_custom_width"] = {"unit": "%", "size": desktop_pct, "sizes": []}
s["_element_custom_width_tablet"] = {"unit": "%", "size": tablet_width_pct, "sizes": []}
s["_element_custom_width_mobile"] = {"unit": "%", "size": 100, "sizes": []}
w_copy["settings"] = s
widgets_with_widths.append(w_copy)
gap_px = gap or 16
gap_str = str(gap_px)
tablet_dir = "column" if extras.get("stack_tablet") else "row"
mobile_dir = "column" # Mobile always stacks by default
# Wrap when there are 3+ cards or multi-row mode — at tablet their 47%
# widths need to wrap into 2-per-row, otherwise they overflow.
wrap_desktop = "wrap" if cols_per_row and len(widgets) > cols_per_row else "nowrap"
wrap_tablet = "wrap" if (n >= 3 or wrap_desktop == "wrap") and tablet_dir == "row" else "nowrap"
row_settings: dict = {
"content_width": "boxed" if max_width else "full",
"flex_direction": "row",
"flex_direction_tablet": tablet_dir,
"flex_direction_mobile": mobile_dir,
"flex_wrap": wrap_desktop,
"flex_wrap_tablet": wrap_tablet,
"flex_justify_content": "center",
"flex_align_items": extras.get("align_items") or "stretch",
"flex_gap": {"unit": "px", "size": gap_px, "column": gap_str, "row": gap_str},
"flex_gap_tablet": {"unit": "px", "size": gap_px, "column": gap_str, "row": gap_str},
}
if max_width:
row_settings["boxed_width"] = {"unit": "px", "size": max_width, "sizes": []}
else:
row_settings["width"] = {"unit": "%", "size": 100, "sizes": []}
# Wrapper-level spacing inherited from the grid div itself.
# Margin (above/below the row), padding (inside, usually padding-top
# between a hero headline and its stats), and border-top (a horizontal
# divider line) are all part of the source's vertical rhythm.
extras = extras or {}
margin = extras.get("margin")
padding = extras.get("padding")
border_top = extras.get("border_top")
if margin and (margin.get("top") or margin.get("bottom")):
row_settings["margin"] = {
"unit": "px",
"top": str(margin.get("top") or 0), "right": "0",
"bottom": str(margin.get("bottom") or 0), "left": "0",
"isLinked": False,
}
if padding and (padding.get("top") or padding.get("bottom")):
row_settings["padding"] = {
"unit": "px",
"top": str(padding.get("top") or 0), "right": "0",
"bottom": str(padding.get("bottom") or 0), "left": "0",
"isLinked": False,
}
if border_top and border_top.get("width"):
row_settings["border_border"] = "solid"
row_settings["border_width"] = {
"unit": "px",
"top": str(border_top["width"]), "right": "0",
"bottom": "0", "left": "0", "isLinked": False,
}
if border_top.get("color"):
row_settings["border_color"] = border_top["color"]
return {
"__inner_container__": True,
"settings": row_settings,
"children": widgets_with_widths,
}
def _build_header_elements(section: dict) -> list[dict]:
from .widgets import image_widget, looks_like_button, _first_text
logo_src = None
logo_node = None
nav_items: list[tuple[str, str]] = []
for n in _iter(section):
if n.get("tag") == "img" and n.get("src") and not logo_src:
logo_src = n["src"]
logo_node = n
if n.get("tag") == "a" and n.get("href"):
txt = (n.get("text") or _first_text(n)).strip()
if txt and 2 <= len(txt) <= 30 and not looks_like_button(n):
nav_items.append((txt, n["href"]))
# Find text logo (div/span with short text, large font, or "logo" class)
logo_text = None
for n in _iter(section):
if n.get("tag") in ("div", "span", "a") and not logo_src:
cls = " ".join(n.get("classes", [])).lower()
txt = (n.get("text") or "").strip()
if txt and len(txt) <= 20 and ("logo" in cls or "brand" in cls):
logo_text = n
break
elements: list[dict] = []
if logo_src:
# Route through image_widget so it reads actual CSS dimensions
# (e.g., .nav-logo img { height: 28px }) instead of the old
# hardcoded 80px that ignored source styling.
if logo_node:
elements.append(image_widget(logo_node))
else:
elements.append({
"widgetType": "image",
"settings": {
"image": {"url": logo_src, "id": ""},
"image_size": "full", "align": "left",
},
})
elif logo_text:
from .styles import apply_typography, px_to_int as _px
from .widgets import _all_text_html, _apply_margin
# Preserve ALL text including child spans (e.g., "Code<span>Academy</span>")
full_text = _all_text_html(logo_text).strip()
if not full_text:
full_text = logo_text.get("text", "").strip()
logo_settings: dict = {
"title": full_text,
"header_size": "h4",
"align": "left",
}
apply_typography(logo_settings, logo_text.get("styles", {}))
color = to_hex(logo_text.get("styles", {}).get("color"))
if color:
logo_settings["title_color"] = color
_apply_margin(logo_settings, logo_text.get("styles", {}))
elements.append({"widgetType": "heading", "settings": logo_settings})
if nav_items:
# Find the parent div of nav links (for margin-bottom)
links_parent = None
first_link_node = None
for n in _iter(section):
if n.get("tag") == "div" and any(
c.get("tag") == "a" for c in n.get("children", [])
):
links_parent = n
break
# Read link color from the first nav <a> (non-button) in CSS
for n in _iter(section):
if n.get("tag") == "a" and n.get("href") and not looks_like_button(n):
first_link_node = n
break
# Read spacing between links from CSS (margin-left or margin-right)
spacing = 20
if first_link_node:
ls = first_link_node.get("styles", {})
ml = px_to_int(ls.get("margin-left"))
mr = px_to_int(ls.get("margin-right"))
spacing = ml or mr or 20
icon_list_settings: dict = {
"view": "inline",
"space_between": {"unit": "px", "size": spacing, "sizes": []},
"icon_list": [
{"text": txt, "link": {"url": href, "is_external": False},
"selected_icon": {"value": "", "library": ""}}
for txt, href in nav_items[:8]
],
}
if first_link_node:
from .styles import apply_typography as _at
link_styles = first_link_node.get("styles", {})
link_color = to_hex(link_styles.get("color"))
if link_color:
icon_list_settings["text_color"] = link_color
# Apply typography (font-size, font-weight, etc.) with icon_list prefix
tmp: dict = {}
_at(tmp, link_styles)
for k, v in tmp.items():
if k == "typography_typography":
icon_list_settings["icon_typography_typography"] = v
elif k.startswith("typography_"):
icon_list_settings["icon_" + k] = v
if links_parent:
from .widgets import _apply_margin as _am
_am(icon_list_settings, links_parent.get("styles", {}))
nav_icon_list = {"widgetType": "icon-list", "settings": icon_list_settings}
else:
nav_icon_list = None
nav_cta = None
for n in _iter(section):
if n.get("tag") == "a" and looks_like_button(n):
from .widgets import button_widget
txt = (n.get("text") or _first_text(n)).strip()
if txt:
nav_cta = button_widget(n, txt)
break
# For flex-row headers with BOTH nav + CTA: group them in a nested row
# so they stay together on the right (HTML <nav> semantics).
# Use _element_custom_width: auto + content_width not set so container shrinks.
sec_tag_local = section.get("tag", "")
is_flex_header = (
sec_tag_local in ("header", "nav")
or section.get("styles", {}).get("display") == "flex"
)
if is_flex_header and nav_icon_list and nav_cta:
# Wrap logo in its own container too for symmetry
if elements and elements[0].get("widgetType") in ("heading", "image"):
logo_widget = elements.pop(0)
elements.insert(0, {
"__inner_container__": True,
"settings": {
"flex_direction": "row",
"flex_align_items": "center",
"_flex_size": "shrink",
},
"children": [logo_widget],
})
elements.append({
"__inner_container__": True,
"settings": {
"flex_direction": "row",
"flex_align_items": "center",
"flex_justify_content": "flex-end",
"flex_gap": {"unit": "px", "size": 20, "column": "20", "row": "20"},
"_flex_size": "shrink",
},
"children": [nav_icon_list, nav_cta],
})
else:
if nav_icon_list:
elements.append(nav_icon_list)
if nav_cta:
elements.append(nav_cta)
# Emit remaining text divs (copyright, taglines) not captured above
collected_texts = set()
if logo_text:
collected_texts.add(logo_text.get("text", "").strip())
for txt, _ in nav_items:
collected_texts.add(txt)
for child in section.get("children", []):
tag = child.get("tag", "")
txt = (child.get("text") or "").strip()
if tag == "div" and txt and txt not in collected_texts:
from .styles import apply_typography
settings: dict = {"editor": txt}
apply_typography(settings, child.get("styles", {}))
color = to_hex(child.get("styles", {}).get("color"))
if color:
settings["text_color"] = color
elements.append({"widgetType": "text-editor", "settings": settings})
return elements
def _invert_text_colors(elements: list[dict]) -> None:
"""On dark sections: only override widget colors if they don't already have
an explicit light color. If the widget already extracted a light color from
CSS (e.g., gold #d4c5a9), keep it. Only default dark text gets inverted."""
from .globals import short_id, resolve_global_color
from .colors import relative_luminance, to_hex as _to_hex
# These IDs must match what globals.py registers as custom colors
# (title + hex_val, see globals._build_kit_settings).
white_id = short_id("White" + "#ffffff")
white80_id = short_id("White 80" + "#ffffffcc")
def _existing_hex(raw: str | None, global_ref: str | None) -> str | None:
"""Return hex of whichever color source is set (raw wins if both)."""
if raw:
h = _to_hex(raw)
if h:
return h
if global_ref:
return resolve_global_color(global_ref)
return None
def _has_own_bg(s: dict) -> bool:
"""Widget has its own classic background set — skip invert (self-contained island)."""
if s.get("_background_background") != "classic":
return False
g = s.get("__globals__", {})
return bool(s.get("_background_color") or g.get("_background_color"))
for el in elements:
if el.get("__inner_container__"):
_invert_text_colors(el["children"])
continue
s = el.get("settings", {})
g = s.setdefault("__globals__", {})
wt = el.get("widgetType")