Repository navigation
Expand file tree
/
Copy pathhtml.py
More file actions
1292 lines (1113 loc) · 43 KB
/
Copy pathhtml.py
File metadata and controls
1292 lines (1113 loc) · 43 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
"""HTML generation for validated Linkora documents.
Every block type has a ``render_<block>`` function. The dispatch table at the
bottom of this module maps block names to their renderer, so adding a new
block requires registering a single new renderer.
"""
from __future__ import annotations
import calendar
import html
import re
from urllib.parse import quote
from compiler.ast import Block, Document
from compiler.codegen.css import FONT_FAMILIES, build_css
from compiler.codegen.svg import (
ADDRESS_META,
BRAND_PATHS,
CONTACT_META,
DIVIDER_SVGS,
NETWORK_META,
PLATFORM_META,
SUPERLINK_SVG,
_icon_svg,
)
from compiler.types import jalali_to_gregorian
#: Counter used to give each slider block a unique HTML element id.
_slider_counter = 0
#: Inline script driving the Image slider dots: highlights the dot of the
#: slide currently in view and makes each dot jump to its slide.
SLIDER_JS = """<script>
(function () {
var sliders = document.querySelectorAll('.lk-image-slider');
if (!sliders.length) return;
sliders.forEach(function (slider) {
var track = slider.querySelector('.lk-image-slider-track');
var dots = slider.querySelectorAll('.lk-image-slider-dot');
var slides = track ? track.querySelectorAll('.lk-imagecard') : null;
if (!track || !dots.length || !slides || !slides.length) return;
var current = -1;
function slideIndex() {
var trackRect = track.getBoundingClientRect();
var best = 0, bestOverlap = -1;
for (var i = 0; i < slides.length; i++) {
var r = slides[i].getBoundingClientRect();
var overlap = Math.min(r.right, trackRect.right) - Math.max(r.left, trackRect.left);
if (overlap > bestOverlap) { bestOverlap = overlap; best = i; }
}
return best;
}
function update() {
var index = slideIndex();
if (index === current) return;
current = index;
dots.forEach(function (dot, i) {
dot.classList.toggle('is-active', i === current);
});
}
dots.forEach(function (dot) {
dot.addEventListener('click', function () {
var i = Number(dot.getAttribute('data-slide'));
var left = slides[i].getBoundingClientRect().left
- track.getBoundingClientRect().left + track.scrollLeft;
track.scrollTo({ left: left, behavior: 'smooth' });
});
});
track.addEventListener('scroll', update, { passive: true });
window.addEventListener('resize', update);
update();
});
})();
</script>"""
#: Inline script driving the FAQ accordion. Clicking a question smoothly
#: animates the height of its answer open or closed. Each item toggles
#: independently, and the chevron is rotated to match the open state.
FAQ_JS = """<script>
(function () {
document.querySelectorAll('.lk-faqitem').forEach(function (item) {
var button = item.querySelector('.lk-faqitem-summary');
var wrap = item.querySelector('.lk-faqitem-answer-wrap');
if (!button || !wrap) return;
var a11y = button.getAttribute('aria-expanded');
// Start collapsed unless the item was rendered open.
if (a11y === 'true') {
wrap.style.height = wrap.scrollHeight + 'px';
} else {
wrap.style.height = '0px';
}
button.addEventListener('click', function () {
var open = wrap.style.height !== '0px';
if (open) {
var from = wrap.scrollHeight;
wrap.style.height = from + 'px';
void wrap.offsetHeight;
wrap.style.height = '0px';
button.setAttribute('aria-expanded', 'false');
item.classList.remove('is-open');
} else {
wrap.style.height = wrap.scrollHeight + 'px';
button.setAttribute('aria-expanded', 'true');
item.classList.add('is-open');
}
});
if (window.ResizeObserver) {
new ResizeObserver(function () {
if (wrap.style.height !== '0px') {
wrap.style.height = wrap.scrollHeight + 'px';
}
}).observe(wrap);
}
});
})();
</script>"""
#: Inline script driving live Countdown timers. Each countdown carries its
#: target epoch in a ``data-target`` attribute; a timer ticks every second,
#: updates the four digit boxes, freezes the boxes at zero on expiry, and then
#: reveals the optional ``expiredText`` message. Countdowns marked
#: ``data-digits="fa"`` render their numbers using Persian digits.
COUNTDOWN_JS = """<script>
(function () {
var FA = {'0':'۰','1':'۱','2':'۲','3':'۳','4':'۴','5':'۵','6':'۶','7':'۷','8':'۸','9':'۹'};
function pad(n, digits) {
n = String(n);
while (n.length < digits) n = '0' + n;
return n;
}
function toPersian(s) {
var out = '';
for (var i = 0; i < s.length; i++) out += FA[s[i]] || s[i];
return out;
}
function update(root) {
var target = Number(root.getAttribute('data-target'));
var now = Date.now();
var diff = target - now;
if (diff < 0) diff = 0;
var days = Math.floor(diff / 86400000);
var hours = Math.floor(diff % 86400000 / 3600000);
var minutes = Math.floor(diff % 3600000 / 60000);
var seconds = Math.floor(diff % 60000 / 1000);
var vals = [pad(days, 2), pad(hours, 2), pad(minutes, 2), pad(seconds, 2)];
var fa = root.getAttribute('data-digits') === 'fa';
var boxes = root.querySelectorAll('.lk-countdown-digit');
if (boxes.length === 4) {
boxes.forEach(function (box, i) {
box.textContent = fa ? toPersian(vals[i]) : vals[i];
});
}
if (diff === 0) {
var expired = root.querySelector('.lk-countdown-expired');
if (expired) expired.style.display = 'block';
if (root.__timer) { clearInterval(root.__timer); root.__timer = null; }
}
}
document.querySelectorAll('.lk-countdown').forEach(function (root) {
update(root);
root.__timer = setInterval(function () { update(root); }, 1000);
});
})();
</script>"""
def render_html(document: Document) -> str:
"""Render a validated document into a complete HTML page."""
global _slider_counter, _faq_counter, _faq_item_counter, _countdown_counter
_slider_counter = 0
_faq_counter = 0
_faq_item_counter = 0
_countdown_counter = 0
theme_block = next((b for b in document.blocks if b.name == "Theme"), None)
theme_data = _theme_data(theme_block)
page_data = _page_data(document)
content_blocks = [b for b in document.blocks if b.name not in ("Theme", "Page")]
used_blocks = {b.name for b in content_blocks}
body = "\n".join(_render_block(block) for block in content_blocks)
scripts = ""
if _slider_counter > 0:
scripts += SLIDER_JS + "\n"
if _faq_counter > 0:
scripts += FAQ_JS + "\n"
if _countdown_counter > 0:
scripts += COUNTDOWN_JS + "\n"
head = " <meta charset=\"utf-8\">\n"
head += " <meta name=\"viewport\" content=\"width=device-width, initial-scale=1\">\n"
if page_data["favicon"]:
head += f' <link rel="icon" href="{html.escape(str(page_data["favicon"]))}">\n'
head += " <link rel=\"preconnect\" href=\"https://fonts.googleapis.com\">\n"
head += " <link rel=\"preconnect\" href=\"https://fonts.gstatic.com\" crossorigin>\n"
head += f" {_theme_font_stylesheet_link(theme_data)}\n"
head += f" <title>{html.escape(str(page_data['title'] or 'Linkora'))}</title>\n"
if page_data["description"]:
head += f' <meta name="description" content="{html.escape(str(page_data["description"]))}">\n'
head += " <style>\n"
head += build_css(theme_data, used_blocks)
head += " </style>\n"
return (
"<!DOCTYPE html>\n"
f"<html lang=\"{page_data['lang']}\" dir=\"{page_data['dir']}\">\n"
"<head>\n"
f"{head}"
"</head>\n"
"<body>\n"
f" <main class=\"lk-page\">\n{body}\n{render_brand(page_data['lang'])}\n </main>\n"
f"{scripts}"
"</body>\n"
"</html>\n"
)
#: GitHub URL behind the page-bottom branding mark.
BRAND_URL = "https://github.com/Fargolnz/Linkora"
#: Branding caption per page language. Pinned (never themed).
BRAND_CAPTIONS = {
"fa": "ساخته شده با لینکورا",
"en": "Built With Linkora",
}
#: Caption font stacks per page language. Pinned (never themed), so the
#: branding caption renders identically on every page.
_BRAND_FONT_TAIL = (
'-apple-system, BlinkMacSystemFont, "Segoe UI", '
"Roboto, Helvetica, Arial, sans-serif"
)
BRAND_FONTS = {
"fa": '"Vazirmatn", ' + _BRAND_FONT_TAIL,
"en": '"Inter", ' + _BRAND_FONT_TAIL,
}
def render_brand(lang: str) -> str:
"""Render the page-bottom branding mark linking to the project repo."""
caption = BRAND_CAPTIONS.get(lang, BRAND_CAPTIONS["en"])
family = BRAND_FONTS.get(lang, BRAND_FONTS["en"])
paths = "".join(BRAND_PATHS)
return (
f' <a class="lk-brand" href="{BRAND_URL}" target="_blank" rel="noopener">\n'
f' <span class="lk-brand-divider" aria-hidden="true"></span>\n'
f' <svg viewBox="0 0 128.2367 62.1405" xmlns="http://www.w3.org/2000/svg" '
f'aria-hidden="true"><g fill="#fff">{paths}</g></svg>\n'
f' <span class="lk-brand-caption" style="font-family: {family};">'
f"{html.escape(caption)}</span>\n"
" </a>"
)
_DEFAULT_FONT_STYLESHEET = (
"https://fonts.googleapis.com/css2?family=Vazirmatn:wght@400;600;700&display=swap"
)
def _page_data(document: Document) -> dict[str, str]:
"""Extract page-level metadata from the optional Page block."""
language = "fa"
title = ""
description = ""
favicon = ""
page_block = next((b for b in document.blocks if b.name == "Page"), None)
if page_block is not None:
language = str(page_block.resolved.get("language", "fa"))
title = str(page_block.resolved.get("title", ""))
description = str(page_block.resolved.get("description", ""))
favicon = str(page_block.resolved.get("favicon", ""))
lang = "fa" if language == "fa" else "en"
return {
"lang": lang,
"dir": "rtl" if lang == "fa" else "ltr",
"title": title,
"description": description,
"favicon": favicon,
}
def _theme_data(theme_block: Block | None) -> dict[str, str]:
"""Extract page-level theme values read by the page shell: the page
background, backdrop, background image and its size/repeat, and the
page font family."""
data: dict[str, str] = {}
if theme_block is None:
return data
page_theme = next(
(child for child in theme_block.children if child.name == "PageTheme"),
None,
)
if page_theme is None:
return data
for target, src in (
("background", "backgroundColor"),
("backdrop", "backdropColor"),
("font", "fontFamily"),
("background_image", "backgroundImage"),
("background_size", "backgroundSize"),
("background_repeat", "backgroundRepeat"),
):
value = str(page_theme.resolved.get(src, ""))
if value:
data[target] = value
return data
def _theme_font_stylesheet_link(theme_data: dict[str, str]) -> str:
"""Return the Google Fonts <link> URL for the active page font.
The page branding caption is pinned to Vazirmatn (fa) or Inter (en),
so the default Vazirmatn stylesheet is also emitted whenever the
active theme font is a different family.
"""
font = theme_data.get("font")
if not font:
return (
f'<link href="{_DEFAULT_FONT_STYLESHEET}" rel="stylesheet">'
)
family = quote(FONT_FAMILIES.get(font, font), safe="")
href = (
"https://fonts.googleapis.com/css2?"
f"family={family}:wght@400;600;700&display=swap"
)
link = f'<link href="{href}" rel="stylesheet">'
if font != "vazirmatn":
link += (
"\n"
f' <link href="{_DEFAULT_FONT_STYLESHEET}" rel="stylesheet">'
)
return link
def _render_block(block: Block) -> str:
renderer = _RENDERERS.get(block.name)
if renderer is None:
return f"<!-- unsupported block: {html.escape(block.name)} -->"
return renderer(block)
_PROFILE_CHILD_ORDER = ["Cover", "Logo", "Name", "Bio"]
def render_profile(block: Block) -> str:
"""Render a Profile container, sorting children into display order."""
sorted_children = sorted(
block.children,
key=lambda c: _PROFILE_CHILD_ORDER.index(c.name)
if c.name in _PROFILE_CHILD_ORDER
else len(_PROFILE_CHILD_ORDER),
)
inner = "\n".join(_render_block(child) for child in sorted_children)
return f' <section class="lk-profile">\n{inner}\n </section>'
def render_name(block: Block) -> str:
"""Render a Name block with title and subtitle."""
resolved = block.resolved
title = str(resolved["title"])
subtitle = str(resolved["subtitle"])
align = str(resolved["align"])
title_color = str(resolved["titleColor"])
sub_color = str(resolved["subtitleColor"])
parts = []
if title:
parts.append(
f' <h1 class="lk-name-title" '
f'style="color: {title_color};">{html.escape(title)}</h1>'
)
if subtitle:
parts.append(
f' <p class="lk-name-subtitle" '
f'style="color: {sub_color};">{html.escape(subtitle)}</p>'
)
inner = "\n".join(parts)
return (
f' <div class="lk-name lk-align-{align}">\n'
f"{inner}\n"
f" </div>"
)
#: Shared ``lk-shape-*`` class for each block-specific ``shape`` value.
_SHAPE_CLASS = {
"circle": "pill",
"square": "sharp",
"rectangle": "sharp",
}
def render_logo(block: Block) -> str:
"""Render a Logo block as a profile image."""
resolved = block.resolved
image = str(resolved["image"])
shape = _SHAPE_CLASS.get(str(resolved["shape"]), str(resolved["shape"]))
border_color = str(resolved["borderColor"])
style = f"border-color: {border_color};"
return (
f' <img class="lk-logo lk-shape-{shape}" '
f'style="{style}" '
f'src="{html.escape(image, quote=True)}" alt="Logo">'
)
def _is_boxed(bg_color: str, border_color: str) -> bool:
"""Whether a Bio/Text block draws a visible box needing inner padding."""
return bg_color.strip().lower() not in (
"",
"transparent",
) or border_color.strip().lower() not in ("", "transparent")
def render_bio(block: Block) -> str:
"""Render a Bio block as a styled paragraph."""
resolved = block.resolved
text = str(resolved["text"])
align = str(resolved["align"])
text_color = str(resolved["textColor"])
bg_color = str(resolved["backgroundColor"])
border_color = str(resolved["borderColor"])
shape = str(resolved["shape"])
classes = ["lk-bio", f"lk-shape-{shape}"]
if _is_boxed(bg_color, border_color):
classes.append("lk-bio--boxed")
classes = " ".join(classes)
style = (
f"color: {text_color}; "
f"background-color: {bg_color}; "
f"border-color: {border_color}; "
f"text-align: {align};"
)
return (
f' <p class="{classes}" style="{style}">'
f"{html.escape(text)}</p>"
)
def render_cover(block: Block) -> str:
"""Render a Cover block as a full-width banner image."""
resolved = block.resolved
image = str(resolved["image"])
shape = _SHAPE_CLASS.get(str(resolved["shape"]), str(resolved["shape"]))
classes = " ".join(["lk-cover", f"lk-shape-{shape}"])
return (
f' <div class="{classes}">\n'
f' <img class="lk-cover-img" '
f'src="{html.escape(image, quote=True)}" alt="Cover">\n'
f" </div>"
)
def render_link(block: Block) -> str:
"""Render a Link block as a clickable, styled button."""
resolved = block.resolved
title = str(resolved["title"])
url = str(resolved["url"])
shape = str(resolved["shape"])
align = str(resolved["align"])
title_color = str(resolved["titleColor"])
background_color = str(resolved["backgroundColor"])
border_color = str(resolved["borderColor"])
classes = " ".join(["lk-link", f"lk-shape-{shape}", f"lk-align-{align}"])
style = (
f"color: {title_color}; "
f"background-color: {background_color}; "
f"border-color: {border_color};"
)
return (
f' <a class="{classes}" style="{style}" '
f'href="{html.escape(url, quote=True)}">'
f"{html.escape(title)}</a>"
)
def render_title(block: Block) -> str:
"""Render a Title block as a styled heading."""
resolved = block.resolved
title = str(resolved["title"])
align = str(resolved["align"])
title_color = str(resolved["titleColor"])
style = f"color: {title_color}; text-align: {align};"
return (
f' <h2 class="lk-title" style="{style}">'
f"{html.escape(title)}</h2>"
)
def render_text(block: Block) -> str:
"""Render a Text block as a styled paragraph."""
resolved = block.resolved
text = str(resolved["text"])
align = str(resolved["align"])
text_color = str(resolved["textColor"])
bg_color = str(resolved["backgroundColor"])
border_color = str(resolved["borderColor"])
shape = str(resolved["shape"])
classes = ["lk-text", f"lk-shape-{shape}"]
if _is_boxed(bg_color, border_color):
classes.append("lk-text--boxed")
classes = " ".join(classes)
style = (
f"color: {text_color}; "
f"background-color: {bg_color}; "
f"border-color: {border_color}; "
f"text-align: {align};"
)
return (
f' <p class="{classes}" style="{style}">'
f"{html.escape(text)}</p>"
)
def _render_connect_container(block: Block, caption: str = "") -> str:
"""Render a connect container (SocialMedia, SocialNetwork, Contact, or
Address) as a responsive grid of items."""
resolved = block.resolved
columns = int(resolved["columns"])
direction = str(resolved["direction"])
items = "\n".join(_render_block(child) for child in block.children)
return (
f' <section class="lk-connect" '
f'data-columns="{columns}" data-direction="{direction}">\n'
f"{caption}"
f"{items}\n"
f" </section>"
)
def _render_connect_item(
block: Block,
meta: dict[str, object],
*,
title_fallback: str,
border_fallback: str,
icon_fallback: str,
href: str,
) -> str:
"""Render a single connect item (SocialMedia, SocialNetwork, Contact, or
Address) as a clickable styled button."""
resolved = block.resolved
parent = _parent_resolved(block)
title = str(resolved["title"]) or str(meta["name"])
title_color = _inherit(
parent, resolved, "titleColor", "titleColor", title_fallback
)
background_color = _inherit(
parent, resolved, "backgroundColor", "backgroundColor", str(meta["bg"])
)
border_color = _inherit(
parent, resolved, "borderColor", "borderColor", border_fallback
)
icon_color = _inherit(
parent, resolved, "iconColor", "iconColor", icon_fallback
)
show_title = bool(parent.get("showTitle", True))
show_icon = bool(parent.get("showIcon", True))
shape = str(parent.get("shape", "rounded"))
classes = " ".join(
["lk-connectitem", f"lk-shape-{shape}"]
)
style = (
f"color: {title_color}; "
f"background-color: {background_color}; "
f"border-color: {border_color};"
)
parts = []
if show_icon:
parts.append(_icon_svg(meta, icon_color))
if show_title:
parts.append(f'<span class="lk-connectitem-title">{html.escape(title)}</span>')
inner = "".join(parts)
return (
f' <a class="{classes}" style="{style}" '
f'href="{html.escape(href, quote=True)}">{inner}</a>'
)
def render_socialmedia_item(block: Block) -> str:
"""Render a single SocialMedia item as a clickable styled button."""
resolved = block.resolved
service = str(resolved["service"])
return _render_connect_item(
block,
PLATFORM_META[service],
title_fallback="#1A1A1A",
border_fallback="transparent",
icon_fallback="",
href=str(resolved["url"]),
)
def render_socialmedia(block: Block) -> str:
"""Render a SocialMedia container as a responsive grid of items."""
return _render_connect_container(block)
def render_socialnetwork_item(block: Block) -> str:
"""Render a single SocialNetwork item as a clickable styled button."""
resolved = block.resolved
service = str(resolved["service"])
return _render_connect_item(
block,
NETWORK_META[service],
title_fallback="#3B3B3B",
border_fallback="transparent",
icon_fallback="",
href=str(resolved["url"]),
)
def render_socialnetwork(block: Block) -> str:
"""Render a SocialNetwork container as a responsive grid of items."""
return _render_connect_container(block)
def render_contact(block: Block) -> str:
"""Render a Contact container as a responsive grid of contact items."""
return _render_connect_container(block)
def render_contact_item(block: Block) -> str:
"""Render a single Contact item as a clickable button with a scheme href."""
resolved = block.resolved
service = str(resolved["service"])
return _render_connect_item(
block,
CONTACT_META[service],
title_fallback="#00B4B0",
border_fallback="#00B4B0",
icon_fallback="#00B4B0",
href=_contact_href(service, str(resolved["value"])),
)
def _contact_href(contact_type: str, value: str) -> str:
"""Build the destination href for a contact type from its raw value."""
scheme = CONTACT_META[contact_type]["scheme"]
if contact_type == "website":
if "://" not in value:
return scheme + value
return value
return scheme + value
def render_address(block: Block) -> str:
"""Render an Address container as an address caption plus a provider grid."""
resolved = block.resolved
address = str(resolved["address"])
address_color = str(resolved["addressColor"]) or "#000000"
align = str(resolved["align"])
caption = ""
if address:
caption = (
f' <div class="lk-address-caption" '
f'style="color: {address_color}; text-align: {align};">'
f"{html.escape(address)}</div>\n"
)
return _render_connect_container(block, caption=caption)
def render_address_item(block: Block) -> str:
"""Render a single Address item as a clickable navigation button."""
resolved = block.resolved
service = str(resolved["service"])
return _render_connect_item(
block,
ADDRESS_META[service],
title_fallback="#3B3B3B",
border_fallback="transparent",
icon_fallback="",
href=str(resolved["url"]),
)
def render_image(block: Block) -> str:
"""Render an Image container as a grid of cards or a slider carousel."""
resolved = block.resolved
display_mode = str(resolved["displayMode"])
items = list(block.children)
if display_mode == "slider":
slider_id = _new_slider_id()
shadow = bool(resolved.get("shadow", True))
shape = str(resolved.get("shape") or "rounded")
section_classes = ["lk-image", "lk-image-slider"]
if shadow:
section_classes.append("lk-image-slider--shadow")
section_classes.append(f"lk-shape-{shape}")
cards = []
for i, child in enumerate(items):
cards.append(
_render_image_item(
child,
reserve_caption=False,
card_id=f"{slider_id}-slide-{i}",
apply_shadow=False,
)
)
dots = []
for i, child in enumerate(items):
active = " is-active" if i == 0 else ""
dots.append(
f' <button type="button" class="lk-image-slider-dot{active}" '
f'data-slide="{i}" aria-label="Go to slide {i + 1}"></button>'
)
section_class = " ".join(section_classes)
return (
f' <section class="{section_class}" id="{slider_id}">\n'
f' <div class="lk-image-slider-track">\n'
+ "\n".join(cards)
+ "\n"
f' </div>\n'
f' <div class="lk-image-slider-dots">\n'
+ "\n".join(dots)
+ "\n"
f' </div>\n'
f" </section>"
)
columns = int(resolved["columns"])
direction = str(resolved["direction"])
rows = []
for i in range(0, len(items), columns):
row_items = items[i : i + columns]
has_caption = any(
str(child.resolved.get("title") or "")
or str(child.resolved.get("description") or "")
for child in row_items
)
cards = "\n".join(
_render_image_item(child, reserve_caption=has_caption)
for child in row_items
)
rows.append(
f' <div class="lk-image-row">\n{cards}\n </div>'
)
body = "\n".join(rows)
return (
f' <section class="lk-image lk-image-grid" data-direction="{direction}">\n'
f"{body}\n"
f" </section>"
)
def render_image_item(block: Block) -> str:
"""Render a single Image item as a display card (image + optional caption)."""
return _render_image_item(block, reserve_caption=False)
def _new_slider_id() -> str:
"""Return a page-unique element id for a slider block."""
global _slider_counter
_slider_counter += 1
return f"lk-slider-{_slider_counter}"
def _render_image_item(block: Block, reserve_caption: bool, card_id: str | None = None, *, apply_shadow: bool = True) -> str:
"""Render a single Image item as a display card.
When ``reserve_caption`` is True the caption area is emitted even for
cards without their own caption, reserving equal space across the row.
``card_id`` optionally adds an element id (used by slider slides).
"""
resolved = block.resolved
parent = _parent_resolved(block)
image = str(resolved["image"])
title = str(resolved["title"])
description = str(resolved["description"])
alt = str(resolved["alt"]) or title or description or "Image"
shape = str(parent.get("shape", "rounded"))
shadow = bool(parent.get("shadow", True))
background_color = _inherit(
parent, resolved, "backgroundColor", "backgroundColor"
) or "#FFFFFF"
border_color = _inherit(
parent, resolved, "borderColor", "borderColor"
) or "transparent"
title_color = (
_inherit(parent, resolved, "titleColor", "titleColor")
or str(parent.get("titleColor", "#000000"))
)
description_color = (
_inherit(parent, resolved, "descriptionColor", "descriptionColor")
or str(parent.get("descriptionColor", "#3B3B3B"))
)
has_caption = bool(title or description)
classes = ["lk-imagecard", f"lk-shape-{shape}"]
if has_caption:
classes.append("lk-imagecard--has-caption")
if apply_shadow and shadow:
classes.append("lk-imagecard--shadow")
style = (
f"background-color: {background_color}; "
f"border-color: {border_color};"
)
caption = ""
if has_caption or reserve_caption:
cap_parts = []
if title:
cap_parts.append(
f'<div class="lk-imagecard-title" style="color: {title_color};">'
f"{html.escape(title)}</div>"
)
if description:
cap_parts.append(
f'<div class="lk-imagecard-desc" style="color: {description_color};">'
f"{html.escape(description)}</div>"
)
if cap_parts:
inner = "\n ".join(cap_parts)
caption = (
"\n <figcaption class=\"lk-imagecard-caption\">\n "
+ inner
+ "\n </figcaption>"
)
else:
caption = '\n <figcaption class="lk-imagecard-caption lk-imagecard-caption--empty"></figcaption>'
media = (
f'\n <img class="lk-imagecard-img lk-shape-{shape}" '
f'src="{html.escape(image, quote=True)}" '
f'alt="{html.escape(alt, quote=True)}">'
)
id_attr = f' id="{html.escape(card_id, quote=True)}"' if card_id else ""
return (
f' <figure class="{" ".join(classes)}"{id_attr} style="{style}">'
f"{media}{caption}"
f"\n </figure>"
)
def render_banner(block: Block) -> str:
"""Render a Banner container as a grid of linked image cards."""
resolved = block.resolved
columns = int(resolved["columns"])
direction = str(resolved["direction"])
items = list(block.children)
rows = []
for i in range(0, len(items), columns):
row_items = items[i : i + columns]
cards = "\n".join(_render_banner_item(child) for child in row_items)
rows.append(f' <div class="lk-banner-row">\n{cards}\n </div>')
body = "\n".join(rows)
return (
f' <section class="lk-banner" data-direction="{direction}">\n'
f"{body}\n"
f" </section>"
)
def _render_banner_item(block: Block) -> str:
"""Render a single Banner item as a linked image card with overlay."""
resolved = block.resolved
parent = _parent_resolved(block)
image = str(resolved["image"])
url = str(resolved["url"])
title = str(resolved["title"])
description = str(resolved["description"])
alt = title or description or "Banner"
shape = str(parent.get("shape", "rounded"))
border_color = _inherit(
parent, resolved, "borderColor", "borderColor"
) or "transparent"
title_color = _inherit(
parent, resolved, "titleColor", "titleColor"
) or "#FFFFFF"
description_color = _inherit(
parent, resolved, "descriptionColor", "descriptionColor"
) or "#FFFFFF"
classes = " ".join(["lk-banneritem", f"lk-shape-{shape}"])
style = f"border-color: {border_color};"
title_html = ""
if title:
title_html = (
f'\n <div class="lk-banneritem-title" '
f'style="color: {title_color};">'
f"{html.escape(title)}</div>"
)
desc_html = ""
if description:
desc_html = (
f'\n <div class="lk-banneritem-desc" '
f'style="color: {description_color};">'
f"{html.escape(description)}</div>"
)
mask = f'\n <div class="lk-banneritem-mask">{title_html}{desc_html}\n </div>'
img = (
f'\n <img class="lk-banneritem-img" '
f'src="{html.escape(image, quote=True)}" '
f'alt="{html.escape(alt, quote=True)}">'
)
return (
f' <a class="{classes}" href="{html.escape(url, quote=True)}" '
f'style="{style}">'
f"{img}{mask}"
f"\n </a>"
)
def render_banner_item(block: Block) -> str:
"""Render a BannerItem — always rendered inside its container."""
return _render_banner_item(block)
def _youtube_video_id(url: str) -> str:
"""Extract the YouTube video ID from a watch URL, or "" if not one."""
m = re.match(
r"^https?://(?:(?:www\.)?youtube\.com/watch\?.*v=|youtu\.be/)([A-Za-z0-9_-]+)",
url,
)
return m.group(1) if m else ""
def _is_local_video(url: str) -> bool:
"""Return True if *url* looks like a local video file path."""
lower = url.lower()
return any(lower.endswith(ext) for ext in (".mp4", ".webm", ".mov"))
def render_video(block: Block) -> str:
"""Render a Video block as a thumbnail card with play icon overlay."""
resolved = block.resolved
url = str(resolved["url"])
thumbnail = str(resolved["thumbnail"])
shape = str(resolved["shape"])
border_color = str(resolved["borderColor"])
vid = _youtube_video_id(url)
is_yt = bool(vid)
is_local = _is_local_video(url)
if not thumbnail and is_yt:
thumbnail = f"https://img.youtube.com/vi/{vid}/maxresdefault.jpg"
alt = "Video"
style = f"border-color: {border_color};" if border_color != "transparent" else ""
img_tag = (
f'\n <img class="lk-video-img" '
f'src="{html.escape(thumbnail, quote=True)}" '
f'alt="{html.escape(alt, quote=True)}">'
) if thumbnail else ""
card_class = "lk-video" if thumbnail else "lk-video lk-video-no-thumbnail"
play_icon = (
'\n <div class="lk-video-play">'
'<div class="lk-video-play-triangle"></div>'
'</div>'
)
inner = f"{img_tag}{play_icon}"
style_attr = f' style="{style}"' if style else ""
if is_local:
tag_open = (
f' <div class="{card_class} lk-shape-{shape}"{style_attr}>'
)
tag_close = " </div>"
video_el = (
f'\n <video class="lk-video-player" controls preload="metadata"'
f' src="{html.escape(url, quote=True)}"></video>'
)
return f"{tag_open}{inner}{video_el}\n{tag_close}"
tag_open = (
f' <a class="{card_class} lk-shape-{shape}" '
f'href="{html.escape(url, quote=True)}" '