-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathcf-elements.js
More file actions
4777 lines (4329 loc) · 171 KB
/
cf-elements.js
File metadata and controls
4777 lines (4329 loc) · 171 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
/**
* ============================================================================
* FUNNELWIND WEB COMPONENTS - cf-elements.js
* ============================================================================
*
* A zero-dependency Web Components library that generates ClickFunnels
* compatible HTML with inline styles. No CSS framework required.
*
* USAGE:
* <script src="cf-elements.js"></script>
*
* <cf-page bg="#ffffff">
* <cf-section pt="80px" pb="80px" bg="#0f172a">
* <cf-row width="wide">
* <cf-col span="12">
* <cf-headline size="48px" color="#ffffff" align="center">
* Hello World
* </cf-headline>
* </cf-col>
* </cf-row>
* </cf-section>
* </cf-page>
*
* OUTPUT: Clean HTML with data-type attributes for ClickFunnels conversion
*
* ============================================================================
* CLICKFUNNELS LIMITATIONS (enforced by this library)
* ============================================================================
*
* - NO margin-bottom (only margin-top via mt attribute)
* - Horizontal padding is unified (px, not pl/pr separately)
* - FontAwesome OLD format only: "fas fa-check" not "fa-solid fa-check"
* - Line heights as percentages: 100%, 110%, 120%, 140%, 160%, 180%
* - FlexContainer always centered (margin: 0 auto)
* - All borders share same width/style on all sides
* - Only ONE shadow allowed (no multiple shadows)
* - Sections always horizontally centered, can use 100% width fullContainer
*
* ============================================================================
*/
(function () {
"use strict";
// ==========================================================================
// LOADING STATE - Prevent Flash of Unstyled Content (FOUC)
// ==========================================================================
// Inject loading state CSS immediately to hide content until rendered
(function injectLoadingStyles() {
const style = document.createElement('style');
style.id = 'cf-loading-styles';
style.textContent = `
/* Hide cf-page until rendered to prevent FOUC */
cf-page:not([data-rendered="true"]) {
opacity: 0 !important;
}
cf-page[data-rendered="true"] {
opacity: 1;
transition: opacity 0.1s ease-in;
}
`;
// Insert at the start of head to ensure it's applied immediately
if (document.head) {
document.head.insertBefore(style, document.head.firstChild);
} else {
document.addEventListener('DOMContentLoaded', () => {
document.head.insertBefore(style, document.head.firstChild);
});
}
})();
// ==========================================================================
// BACKGROUND STYLES - Inject CSS for background image classes
// ==========================================================================
// Inject background styles immediately
(function injectBgStyles() {
const style = document.createElement('style');
style.id = 'cf-bg-styles';
style.textContent = `
/* Background style classes - matches ClickFunnels options */
.bgCover { background-size: cover !important; background-repeat: no-repeat !important; }
.bgCoverCenter { background-size: cover !important; background-position: center center !important; background-repeat: no-repeat !important; }
.bgCoverV2 { background-attachment: fixed !important; background-size: cover !important; background-position: center center !important; background-repeat: no-repeat !important; }
.bgW100 { background-size: 100% auto !important; background-repeat: no-repeat !important; }
.bgW100H100 { background-size: 100% 100% !important; background-repeat: no-repeat !important; }
.bgNoRepeat { background-repeat: no-repeat !important; }
.bgRepeat { background-repeat: repeat !important; }
.bgRepeatX { background-repeat: repeat-x !important; }
.bgRepeatY { background-repeat: repeat-y !important; }
`;
if (document.head) {
document.head.appendChild(style);
} else {
document.addEventListener('DOMContentLoaded', () => {
document.head.appendChild(style);
});
}
})();
// ==========================================================================
// GOOGLE FONTS - Auto-load fonts from font attributes
// ==========================================================================
// System fonts that don't need to be loaded from Google
const SYSTEM_FONTS = new Set([
'sans-serif', 'serif', 'monospace', 'cursive', 'fantasy', 'system-ui',
'ui-sans-serif', 'ui-serif', 'ui-monospace', 'ui-rounded',
'arial', 'helvetica', 'times new roman', 'times', 'courier new', 'courier',
'verdana', 'georgia', 'palatino', 'garamond', 'bookman', 'tahoma',
'trebuchet ms', 'arial black', 'impact', 'comic sans ms', 'inherit'
]);
// Track which fonts have been loaded to avoid duplicates
const loadedFonts = new Set();
/**
* Extract Google Font names from the document
* Scans font attributes on cf-* elements and styleguide data
*/
function extractFontsFromDocument() {
const fonts = new Set();
// 1. Extract from font attributes on elements
document.querySelectorAll('[font]').forEach(el => {
const font = el.getAttribute('font');
if (font) {
// Clean and add font name
const cleanFont = font.replace(/["']/g, '').split(',')[0].trim();
if (cleanFont && !SYSTEM_FONTS.has(cleanFont.toLowerCase())) {
fonts.add(cleanFont);
}
}
});
// 2. Extract from styleguide data if present
const styleguideEl = document.getElementById('cf-styleguide-data');
if (styleguideEl) {
try {
const data = JSON.parse(styleguideEl.textContent);
if (data.typography) {
const { headlineFont, subheadlineFont, contentFont } = data.typography;
[headlineFont, subheadlineFont, contentFont].forEach(font => {
if (font && !SYSTEM_FONTS.has(font.toLowerCase())) {
fonts.add(font);
}
});
}
} catch (e) {
// Ignore parse errors
}
}
// 3. Extract from inline font-family styles in cf-* elements
document.querySelectorAll('cf-headline, cf-subheadline, cf-paragraph, cf-button').forEach(el => {
const style = el.getAttribute('style') || '';
const match = style.match(/font-family:\s*["']?([^"';,]+)/i);
if (match) {
const font = match[1].trim();
if (font && !SYSTEM_FONTS.has(font.toLowerCase())) {
fonts.add(font);
}
}
});
return fonts;
}
/**
* Inject Google Fonts stylesheet into document head
*/
function injectGoogleFonts(fonts) {
if (!fonts || fonts.size === 0) return;
// Filter out already loaded fonts
const newFonts = Array.from(fonts).filter(f => !loadedFonts.has(f));
if (newFonts.length === 0) return;
// Mark as loaded
newFonts.forEach(f => loadedFonts.add(f));
// Build Google Fonts URL
const fontParams = newFonts
.map(font => font.replace(/ /g, '+'))
.join('&family=');
const url = `https://fonts.googleapis.com/css2?family=${fontParams}:wght@300;400;500;600;700;800;900&display=swap`;
// Check if already loaded
if (document.querySelector(`link[href^="https://fonts.googleapis.com"][href*="${newFonts[0].replace(/ /g, '+')}"]`)) {
return;
}
// Inject link tag
const link = document.createElement('link');
link.id = 'cf-google-fonts';
link.rel = 'stylesheet';
link.href = url;
document.head.appendChild(link);
}
/**
* Auto-load Google Fonts from document
* Called before element rendering
*/
function loadGoogleFonts() {
const fonts = extractFontsFromDocument();
injectGoogleFonts(fonts);
}
// ==========================================================================
// CONSTANTS & MAPPINGS
// ==========================================================================
/**
* Shadow presets matching ClickFunnels
*/
const SHADOWS = {
none: "none",
sm: "0 1px 2px rgba(0,0,0,0.05)",
default: "0 1px 3px rgba(0,0,0,0.1)",
md: "0 4px 6px rgba(0,0,0,0.1)",
lg: "0 10px 15px rgba(0,0,0,0.1)",
xl: "0 20px 25px rgba(0,0,0,0.1)",
"2xl": "0 25px 50px rgba(0,0,0,0.25)",
};
/**
* Border radius presets
*/
const RADIUS = {
none: "0",
sm: "4px",
default: "8px",
md: "12px",
lg: "16px",
xl: "20px",
"2xl": "24px",
"3xl": "32px",
full: "9999px",
};
/**
* Line height presets (percentages for ClickFunnels)
*/
const LINE_HEIGHTS = {
none: "100%",
tight: "110%",
snug: "120%",
normal: "140%",
relaxed: "160%",
loose: "180%",
};
/**
* Font weight mappings
*/
const FONT_WEIGHTS = {
thin: "100",
extralight: "200",
light: "300",
normal: "400",
medium: "500",
semibold: "600",
bold: "700",
extrabold: "800",
black: "900",
};
/**
* Font size presets for text elements
* xl = extra large (headlines), l = large, m = medium, s = small
*/
const FONT_SIZES = {
xs: "12px",
s: "14px",
sm: "14px",
m: "16px",
md: "16px",
l: "20px",
lg: "20px",
xl: "24px",
"2xl": "32px",
"3xl": "40px",
"4xl": "48px",
"5xl": "64px",
};
/**
* Row width presets
*/
const ROW_WIDTHS = {
narrow: "800px",
medium: "960px",
wide: "1170px",
extra: "1400px",
};
/**
* Container width presets
*/
const CONTAINER_WIDTHS = {
small: "550px",
mid: "720px",
midWide: "960px",
wide: "1170px",
full: "100%",
};
/**
* Border width mappings
*/
const BORDER_WIDTHS = {
0: "0",
1: "1px",
2: "2px",
3: "3px",
4: "4px",
6: "6px",
8: "8px",
};
const BG_STYLE_CLASSES = {
cover: "bgCover",
"cover-center": "bgCoverCenter",
parallax: "bgCoverV2",
w100: "bgW100",
w100h100: "bgW100H100",
"no-repeat": "bgNoRepeat",
repeat: "bgRepeat",
"repeat-x": "bgRepeatX",
"repeat-y": "bgRepeatY",
};
/**
* Animation types available in ClickFunnels
*/
const ANIMATION_TYPES = [
'fade-in', 'glide-in', 'expand-in', 'bounce-in', 'fold-in', 'puff-in',
'spin-in', 'flip-in', 'slide-in', 'turn-in', 'float-in', 'blink',
'reveal', 'rocking', 'bouncing', 'wooble', 'elevate',
];
// ==========================================================================
// STYLEGUIDE MANAGER
// ==========================================================================
/**
* StyleguideManager - Handles styleguide CSS generation and attribute mapping
*
* Reads styleguide data from embedded JSON or external source and generates
* CSS for paint themes, buttons, shadows, borders, and corners.
*/
class StyleguideManager {
constructor() {
this.data = null;
this.styleElement = null;
}
/**
* Initialize from embedded JSON or external data
* @param {Object} styleguideData - Optional styleguide data object
*/
init(styleguideData = null) {
if (styleguideData) {
this.data = styleguideData;
} else {
// Try to load from embedded script
const scriptEl = document.getElementById("cf-styleguide-data");
if (scriptEl) {
try {
this.data = JSON.parse(scriptEl.textContent);
} catch (e) {
console.warn("FunnelWind: Failed to parse styleguide data:", e);
return;
}
}
}
if (this.data) {
this.injectCSS();
}
}
/**
* Generate and inject CSS for browser preview
*/
injectCSS() {
if (!this.data) return;
const css = this.generateCSS();
// Remove existing styleguide styles
if (this.styleElement) {
this.styleElement.remove();
}
// Inject new styles
this.styleElement = document.createElement("style");
this.styleElement.id = "cf-styleguide-styles";
this.styleElement.textContent = css;
document.head.appendChild(this.styleElement);
// Apply font data attributes to elements for pagetree parsing
this.applyFontDataAttributes();
}
/**
* Apply font and color data attributes to elements for pagetree parsing.
* This allows the parser to capture styleguide fonts and paint theme colors.
*/
applyFontDataAttributes() {
if (!this.data) return;
const { typography, paintThemes } = this.data;
// Apply typography fonts to elements without explicit fonts
if (typography) {
const { headlineFont, subheadlineFont, contentFont } = typography;
// Apply headline font to headlines without explicit font
if (headlineFont) {
document.querySelectorAll('[data-type="Headline/V1"]:not([data-font])').forEach(el => {
el.setAttribute('data-font', headlineFont);
});
}
// Apply subheadline font to subheadlines without explicit font
if (subheadlineFont) {
document.querySelectorAll('[data-type="SubHeadline/V1"]:not([data-font])').forEach(el => {
el.setAttribute('data-font', subheadlineFont);
});
}
// Apply content font to paragraphs without explicit font
if (contentFont) {
document.querySelectorAll('[data-type="Paragraph/V1"]:not([data-font])').forEach(el => {
el.setAttribute('data-font', contentFont);
});
}
}
// Helper to check if element's closest paint-themed ancestor is the given container
// This prevents applying colors to elements inside nested non-paint containers
const isDirectPaintDescendant = (el, paintContainer) => {
const closestPaint = el.closest('[data-paint-colors]');
return closestPaint === paintContainer;
};
// Apply paint theme colors to elements for pagetree parsing
// IMPORTANT: Paint themes OVERRIDE inline colors (CSS uses !important), so we must
// override data attributes too for the parser to capture the correct colors
// Only apply to elements whose closest paint ancestor is this container
if (paintThemes?.length) {
paintThemes.forEach(theme => {
const containers = document.querySelectorAll(`[data-paint-colors="${theme.id}"]`);
containers.forEach(container => {
const headlineColor = this.getColorHex(theme.headlineColorId);
const subheadlineColor = this.getColorHex(theme.subheadlineColorId);
const contentColor = this.getColorHex(theme.contentColorId);
const iconColor = this.getColorHex(theme.iconColorId);
const linkColor = theme.linkColorId ? this.getColorHex(theme.linkColorId) : null;
// Apply headline color (only to direct paint descendants)
container.querySelectorAll('[data-type="Headline/V1"]').forEach(el => {
if (isDirectPaintDescendant(el, container)) {
if (!el.hasAttribute('data-color-explicit')) {
el.setAttribute('data-color', headlineColor);
}
if (linkColor) el.setAttribute('data-link-color', linkColor);
}
});
// Apply subheadline color (only to direct paint descendants)
container.querySelectorAll('[data-type="SubHeadline/V1"]').forEach(el => {
if (isDirectPaintDescendant(el, container)) {
if (!el.hasAttribute('data-color-explicit')) {
el.setAttribute('data-color', subheadlineColor);
}
if (linkColor) el.setAttribute('data-link-color', linkColor);
}
});
// Apply content/paragraph color (only to direct paint descendants)
container.querySelectorAll('[data-type="Paragraph/V1"]').forEach(el => {
if (isDirectPaintDescendant(el, container)) {
if (!el.hasAttribute('data-color-explicit')) {
el.setAttribute('data-color', contentColor);
}
if (linkColor) el.setAttribute('data-link-color', linkColor);
}
});
// Apply icon color (only to direct paint descendants)
container.querySelectorAll('[data-type="Icon/V1"]').forEach(el => {
if (isDirectPaintDescendant(el, container)) {
if (!el.hasAttribute('data-color-explicit')) {
el.setAttribute('data-color', iconColor);
}
}
});
// Apply text color to bullet lists (only to direct paint descendants)
container.querySelectorAll('[data-type="BulletList/V1"]').forEach(el => {
if (isDirectPaintDescendant(el, container)) {
if (!el.hasAttribute('data-text-color-explicit')) {
el.setAttribute('data-text-color', contentColor);
}
if (!el.hasAttribute('data-icon-color-explicit')) {
el.setAttribute('data-icon-color', iconColor);
}
if (linkColor) el.setAttribute('data-link-color', linkColor);
}
});
});
});
}
}
/**
* Get hex color by ID from the color palette
*/
getColorHex(colorId) {
if (!this.data?.colors) return "#000000";
const color = this.data.colors.find((c) => c.id === colorId);
return color ? color.hex : "#000000";
}
/**
* Get typescale sizes calculated from baseSize and scaleRatio
* Returns object with scales for each element type (headline, subheadline, paragraph)
*
* The scale is designed so that within each size category (xl, l, m, s):
* - Headlines use the largest size
* - Subheadlines use one step down
* - Paragraphs use two steps down
*
* This matches StyleguideEditor.tsx preview layout
*/
getTypescale() {
if (!this.data?.typography) return null;
const { baseSize = 16, scaleRatio = 1.25 } = this.data.typography;
// Calculate the base scale steps
const r = scaleRatio;
const b = baseSize;
// Scale values (each is one step apart)
// With base=16, ratio=1.25: ~10, 13, 16, 20, 25, 31, 39, 49, 61, 76, 95
const scale = {
n3: Math.round(b / Math.pow(r, 3)), // ~8
n2: Math.round(b / Math.pow(r, 2)), // ~10
n1: Math.round(b / r), // ~13
base: b, // 16
p1: Math.round(b * r), // ~20
p2: Math.round(b * Math.pow(r, 2)), // ~25
p3: Math.round(b * Math.pow(r, 3)), // ~31
p4: Math.round(b * Math.pow(r, 4)), // ~39
p5: Math.round(b * Math.pow(r, 5)), // ~49
p6: Math.round(b * Math.pow(r, 6)), // ~61
p7: Math.round(b * Math.pow(r, 7)), // ~76
p8: Math.round(b * Math.pow(r, 8)), // ~95
};
return {
// Headlines get largest sizes
headline: {
"5xl": `${scale.p8}px`,
"4xl": `${scale.p7}px`,
"3xl": `${scale.p6}px`,
"2xl": `${scale.p5}px`,
xl: `${scale.p4}px`,
l: `${scale.p3}px`,
lg: `${scale.p3}px`,
m: `${scale.p2}px`,
md: `${scale.p2}px`,
s: `${scale.p1}px`,
sm: `${scale.p1}px`,
xs: `${scale.base}px`,
},
// Subheadlines get one step smaller
subheadline: {
"5xl": `${scale.p7}px`,
"4xl": `${scale.p6}px`,
"3xl": `${scale.p5}px`,
"2xl": `${scale.p4}px`,
xl: `${scale.p3}px`,
l: `${scale.p2}px`,
lg: `${scale.p2}px`,
m: `${scale.p1}px`,
md: `${scale.p1}px`,
s: `${scale.base}px`,
sm: `${scale.base}px`,
xs: `${scale.n1}px`,
},
// Paragraphs get two steps smaller
paragraph: {
"5xl": `${scale.p6}px`,
"4xl": `${scale.p5}px`,
"3xl": `${scale.p4}px`,
"2xl": `${scale.p3}px`,
xl: `${scale.p2}px`,
l: `${scale.p1}px`,
lg: `${scale.p1}px`,
m: `${scale.base}px`,
md: `${scale.base}px`,
s: `${scale.n1}px`,
sm: `${scale.n1}px`,
xs: `${scale.n2}px`,
},
};
}
/**
* Resolve a size preset (xl, l, m, s, xs) to pixel value using typescale
* Falls back to static FONT_SIZES if no styleguide or not a preset
*
* @param {string} size - Size preset (xl, l, m, s, xs) or pixel value
* @param {string} elementType - Element type: 'headline', 'subheadline', or 'paragraph'
*/
resolveSize(size, elementType = 'headline') {
// First try styleguide typescale
const typescale = this.getTypescale();
if (typescale) {
const elementScale = typescale[elementType] || typescale.headline;
if (elementScale && elementScale[size]) {
return elementScale[size];
}
}
// Return null to let caller use static fallback
return null;
}
/**
* Check if a value is a styleguide reference
* @param {string} value - The attribute value to check
* @param {string} type - Type of styleguide reference (paint, shadow, border, corner, button)
*/
isStyleguideRef(value, type) {
if (!value || !this.data) return false;
switch (type) {
case "paint":
return this.data.paintThemes?.some((t) => t.id === value);
case "shadow":
return this.data.shadows?.some((s) => s.id === value);
case "border":
return this.data.borders?.some((b) => b.id === value);
case "corner":
return this.data.corners?.some((c) => c.id === value);
case "button":
return this.data.buttons?.some((b) => b.id === value);
default:
return false;
}
}
/**
* Generate CSS from styleguide data
*/
generateCSS() {
const { colors, paintThemes, shadows, borders, corners, buttons, typography } =
this.data;
let css = "/* FunnelWind Styleguide CSS */\n\n";
// 1. CSS Variables for colors
if (colors?.length) {
css += ":root {\n";
colors.forEach((color) => {
css += ` --sg-color-${color.id}: ${color.hex};\n`;
});
css += "}\n\n";
}
// 1.5 Typography styles (fonts for headline, subheadline, content)
// Only apply when element doesn't have explicit data-font attribute
if (typography) {
css += "/* Typography styles */\n";
const { headlineFont, subheadlineFont, contentFont, headlineWeight, subheadlineWeight, contentWeight } = typography;
// Headline font (when no explicit font set)
if (headlineFont) {
css += `[data-type="Headline/V1"]:not([data-font]) h1,\n`;
css += `[data-type="Headline/V1"]:not([data-font]) h2 {\n`;
css += ` font-family: "${headlineFont}", sans-serif !important;\n`;
css += "}\n";
}
// Subheadline font (when no explicit font set)
if (subheadlineFont) {
css += `[data-type="SubHeadline/V1"]:not([data-font]) h2,\n`;
css += `[data-type="SubHeadline/V1"]:not([data-font]) h3 {\n`;
css += ` font-family: "${subheadlineFont}", sans-serif !important;\n`;
css += "}\n";
}
// Content/paragraph font (when no explicit font set)
if (contentFont) {
css += `[data-type="Paragraph/V1"]:not([data-font]) p {\n`;
css += ` font-family: "${contentFont}", sans-serif !important;\n`;
css += "}\n";
// Also apply to bullet lists (they use content font)
css += `[data-type="BulletList/V1"] li {\n`;
css += ` font-family: "${contentFont}", sans-serif !important;\n`;
css += "}\n";
}
css += "\n";
}
// 2. Paint theme styles (for sections/rows)
if (paintThemes?.length) {
paintThemes.forEach((theme) => {
const bgColor = this.getColorHex(theme.backgroundColorId);
const headlineColor = this.getColorHex(theme.headlineColorId);
const subheadlineColor = this.getColorHex(theme.subheadlineColorId);
const contentColor = this.getColorHex(theme.contentColorId);
const linkColor = this.getColorHex(theme.linkColorId);
const iconColor = this.getColorHex(theme.iconColorId);
// Container styles - set CSS variables for this paint theme
css += `[data-paint-colors="${theme.id}"] {\n`;
css += ` background-color: ${bgColor} !important;\n`;
css += ` --sg-headline-color: ${headlineColor};\n`;
css += ` --sg-subheadline-color: ${subheadlineColor};\n`;
css += ` --sg-content-color: ${contentColor};\n`;
css += ` --sg-link-color: ${linkColor};\n`;
css += ` --sg-icon-color: ${iconColor};\n`;
css += "}\n\n";
});
// Text color rules using CSS variables - these inherit from CLOSEST paint ancestor
// Only one rule needed per element type (no theme-specific selectors)
css += `/* Paint theme text colors - inherit from closest paint ancestor */\n`;
// Headline
css += `[data-paint-colors] [data-type="Headline/V1"] h1,\n`;
css += `[data-paint-colors] [data-type="Headline/V1"] h2 {\n`;
css += ` color: var(--sg-headline-color) !important;\n`;
css += "}\n";
// Subheadline
css += `[data-paint-colors] [data-type="SubHeadline/V1"] h2,\n`;
css += `[data-paint-colors] [data-type="SubHeadline/V1"] h3 {\n`;
css += ` color: var(--sg-subheadline-color) !important;\n`;
css += "}\n";
// Paragraph
css += `[data-paint-colors] [data-type="Paragraph/V1"] p {\n`;
css += ` color: var(--sg-content-color) !important;\n`;
css += "}\n";
// Links (not buttons)
css += `[data-paint-colors] a:not([data-type="Button/V1"] a) {\n`;
css += ` color: var(--sg-link-color) !important;\n`;
css += "}\n";
// Icons and bullet list icons
css += `[data-paint-colors] [data-type="Icon/V1"] i,\n`;
css += `[data-paint-colors] [data-type="BulletList/V1"] .fa_icon {\n`;
css += ` color: var(--sg-icon-color) !important;\n`;
css += "}\n";
// Bullet list text (target both li and span for proper inheritance)
css += `[data-paint-colors] [data-type="BulletList/V1"] li,\n`;
css += `[data-paint-colors] [data-type="BulletList/V1"] li span {\n`;
css += ` color: var(--sg-content-color) !important;\n`;
css += "}\n\n";
}
// 3. Shadow styles
if (shadows?.length) {
shadows.forEach((shadow) => {
const value = `${shadow.x}px ${shadow.y}px ${shadow.blur}px ${shadow.spread}px ${shadow.color}`;
css += `[data-style-guide-shadow="${shadow.id}"] {\n`;
css += ` box-shadow: ${value} !important;\n`;
css += "}\n";
});
css += "\n";
}
// 4. Border styles
if (borders?.length) {
borders.forEach((border) => {
css += `[data-style-guide-border="${border.id}"] {\n`;
css += ` border: ${border.width}px ${border.style} ${border.color} !important;\n`;
css += "}\n";
});
css += "\n";
}
// 5. Corner styles
if (corners?.length) {
corners.forEach((corner) => {
css += `[data-style-guide-corner="${corner.id}"] {\n`;
css += ` border-radius: ${corner.radius}px !important;\n`;
css += "}\n";
});
css += "\n";
}
// 6. Button styles
if (buttons?.length) {
buttons.forEach((btn) => {
// Base button style
css += `[data-style-guide-button="${btn.id}"] a {\n`;
css += ` background-color: ${
btn.regular?.bg || "#3b82f6"
} !important;\n`;
if (btn.borderRadius)
css += ` border-radius: ${btn.borderRadius}px !important;\n`;
if (btn.borderWidth > 0) {
css += ` border: ${btn.borderWidth}px ${
btn.borderStyle || "solid"
} ${btn.borderColor || "transparent"} !important;\n`;
}
if (btn.shadow?.enabled) {
const s = btn.shadow;
css += ` box-shadow: ${s.x || 0}px ${s.y || 0}px ${
s.blur || 0
}px ${s.spread || 0}px ${
s.color || "rgba(0,0,0,0.1)"
} !important;\n`;
}
css += "}\n";
// Button text color
css += `[data-style-guide-button="${btn.id}"] a span {\n`;
css += ` color: ${btn.regular?.color || "#ffffff"} !important;\n`;
css += "}\n";
// Hover state
if (btn.hover) {
css += `[data-style-guide-button="${btn.id}"] a:hover {\n`;
css += ` background-color: ${
btn.hover.bg || btn.regular?.bg || "#3b82f6"
} !important;\n`;
css += "}\n";
css += `[data-style-guide-button="${btn.id}"] a:hover span {\n`;
css += ` color: ${
btn.hover.color || btn.regular?.color || "#ffffff"
} !important;\n`;
css += "}\n";
}
// Active state
if (btn.active) {
css += `[data-style-guide-button="${btn.id}"] a:active {\n`;
css += ` background-color: ${
btn.active.bg || btn.regular?.bg || "#3b82f6"
} !important;\n`;
css += "}\n";
}
});
}
return css;
}
}
// Create global instance
const styleguideManager = new StyleguideManager();
// ==========================================================================
// BRAND ASSETS MANAGER
// ==========================================================================
/**
* Manages brand assets for dynamic image swapping
* Brand assets can be attached to cf-image elements using the brand-asset attribute
* Also supports bg-image on cf-section, cf-row, cf-col
* Valid types: logo, logo_light, logo_dark, background, pattern, icon, product_image
*/
class BrandAssetsManager {
constructor() {
this.data = null;
}
/**
* Initialize from embedded JSON or external data
* @param {Object} brandAssets - Optional brand assets data object
*/
init(brandAssets = null) {
if (brandAssets) {
this.data = brandAssets;
} else {
// Try to load from embedded script
const scriptEl = document.getElementById("cf-brand-assets");
if (scriptEl) {
try {
this.data = JSON.parse(scriptEl.textContent);
} catch (e) {
console.warn("FunnelWind: Failed to parse brand assets data:", e);
return;
}
}
}
}
/**
* Get the first active asset URL for a given type
* @param {string} assetType - Type of asset: logo, background, pattern, icon, product_image
* @returns {string|null} - The URL of the first active asset or null
*/
getAssetUrl(assetType) {
if (
!this.data ||
!this.data[assetType] ||
this.data[assetType].length === 0
) {
return null;
}
return this.data[assetType][0];
}
/**
* Get all active asset URLs for a given type
* @param {string} assetType - Type of asset
* @returns {string[]} - Array of URLs
*/
getAssetUrls(assetType) {
if (!this.data || !this.data[assetType]) {
return [];
}
return this.data[assetType];
}
/**
* Check if we have any assets of a given type
* @param {string} assetType - Type of asset
* @returns {boolean}
*/
hasAsset(assetType) {
return (
this.data && this.data[assetType] && this.data[assetType].length > 0
);
}
}
// Create global instance
const brandAssetsManager = new BrandAssetsManager();
// ==========================================================================
// UTILITY FUNCTIONS
// ==========================================================================
/**
* Get attribute with fallback
*/
function attr(el, name, fallback = null) {
const val = el.getAttribute(name);
return val !== null ? val : fallback;
}
/**
* Resolve a value - check if it's a preset key or use as-is
*/
function resolve(value, presets) {
if (!value) return null;
return presets[value] || value;
}
/**
* Build inline style string from object
*/
function buildStyle(styleObj) {
return Object.entries(styleObj)
.filter(([_, v]) => v !== null && v !== undefined && v !== "")
.map(([k, v]) => `${k}: ${v}`)
.join("; ");
}
/**
* Parse content with slot handling for Web Components
*/
function getContent(el) {
return el.innerHTML;
}
function getBgStyleClass(bgStyle) {
if (!bgStyle) return "bgCoverCenter";
return BG_STYLE_CLASSES[bgStyle] || bgStyle;
}
/**
* Helper to extract YouTube video ID from URL
*/
function extractYouTubeVideoId(url) {
if (!url) return null;
const match = url.match(/(?:youtube\.com\/watch\?v=|youtu\.be\/|youtube\.com\/embed\/)([^&\s?]+)/);
return match ? match[1] : null;
}
/**
* Build animation data attributes string from element attributes
* Returns empty string if no animation specified
*/
function buildAnimationAttrs(el) {