-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathTailwindExtractor.js
More file actions
1689 lines (1510 loc) Β· 77.8 KB
/
TailwindExtractor.js
File metadata and controls
1689 lines (1510 loc) Β· 77.8 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
/**
* Copyright (c) 2025 Bivex
*
* Author: Bivex
* Available for contact via email: support@b-b.top
* For up-to-date contact information:
* https://github.com/bivex
*
* Created: 2025-12-22T05:35:22
* Last Updated: 2025-12-22T06:26:14
*
* Licensed under the MIT License.
* Commercial licensing available upon request.
*/
/**
* Tailwind CSS Configuration Extractor (v3 & v4 Compatible)
* Drop this script into Chrome DevTools console to extract Tailwind settings from any website
*
* Features:
* - Auto-detects Tailwind v3 or v4
* - Extracts CSS variables, colors, spacing, typography, etc.
* - Generates ready-to-use config (CSS for v4, JS for v3)
* - Supports modern color spaces (oklch, hsl, rgb)
*
* Usage: Copy and paste the entire script into the console and press Enter
*/
(function() {
console.log('π Tailwind CSS Configuration Extractor (v3 & v4)');
console.log('=================================================');
// Check if Tailwind CSS is loaded with high precision
function isTailwindLoaded() {
let confidenceScore = 0;
const detectionResults = {};
// 1. Check for Tailwind CSS links (High confidence: +3)
const links = Array.from(document.querySelectorAll('link[rel="stylesheet"]'));
const tailwindLinks = links.filter(link =>
link.href && (
link.href.includes('tailwindcss.com') ||
link.href.includes('unpkg.com/tailwindcss') ||
link.href.includes('jsdelivr.net') && link.href.includes('tailwindcss')
)
);
detectionResults.tailwindLinks = tailwindLinks.length > 0;
if (detectionResults.tailwindLinks) confidenceScore += 3;
// 2. Check for Tailwind in style tags (High confidence: +3)
const styleTags = Array.from(document.querySelectorAll('style'));
const tailwindStyles = styleTags.filter(style => {
try {
const content = style.textContent || '';
return content.includes('@tailwind') ||
content.includes('@import "tailwindcss"') ||
content.includes("@import 'tailwindcss'") ||
content.includes('@theme') ||
content.includes('--tw-') ||
content.includes('--color-') || // v4 uses --color-* variables
content.includes('tailwindcss');
} catch (e) {
return false;
}
});
detectionResults.tailwindStyles = tailwindStyles.length > 0;
if (detectionResults.tailwindStyles) confidenceScore += 3;
// 3. Check for Tailwind CDN scripts (High confidence: +3)
const scripts = Array.from(document.querySelectorAll('script'));
const tailwindScripts = scripts.filter(script =>
script.src && (
script.src.includes('cdn.tailwindcss.com') ||
script.src.includes('tailwindcss.com') ||
script.src.includes('unpkg.com/tailwindcss')
)
);
detectionResults.tailwindScripts = tailwindScripts.length > 0;
if (detectionResults.tailwindScripts) confidenceScore += 3;
// 4. Check for specific Tailwind CSS variables (Very High confidence: +4)
const root = document.documentElement;
const computedStyles = getComputedStyle(root);
const cssProps = Array.from(computedStyles);
const tailwindVars = cssProps.filter(prop =>
// v3 variables
(prop.startsWith('--tw-') &&
(prop.includes('ring') || prop.includes('border') || prop.includes('bg') ||
prop.includes('text') || prop.includes('space') || prop.includes('shadow'))) ||
// v4 variables use --color-*, --font-*, --radius-*, etc.
prop.startsWith('--color-') ||
prop.startsWith('--font-') ||
prop.startsWith('--radius-') ||
prop.startsWith('--spacing-') ||
prop.startsWith('--breakpoint-')
);
detectionResults.tailwindVars = tailwindVars.length > 5; // Need multiple vars
if (detectionResults.tailwindVars) confidenceScore += 4;
// 5. Check for Tailwind-specific class patterns (Medium confidence: +2 each)
function detectTailwindClasses(element) {
if (!element || !element.className) return false;
const classes = element.className.split(/\s+/);
const tailwindClassPatterns = [
// Layout & positioning
/^container$/,
/^flex$/,
/^grid$/,
/^hidden$/,
/^block$/,
/^inline$/,
/^inline-block$/,
/^absolute$/,
/^relative$/,
/^fixed$/,
/^sticky$/,
// Spacing
/^p-\d+$/,
/^m-\d+$/,
/^px-\d+$/,
/^py-\d+$/,
/^mx-\d+$/,
/^my-\d+$/,
// Width/Height
/^w-\d+$/,
/^h-\d+$/,
/^w-full$/,
/^h-full$/,
// Colors (Tailwind specific shades)
/^bg-(red|blue|green|yellow|purple|pink|indigo)-(50|100|200|300|400|500|600|700|800|900|950)$/,
/^text-(red|blue|green|yellow|purple|pink|indigo)-(50|100|200|300|400|500|600|700|800|900|950)$/,
/^border-(red|blue|green|yellow|purple|pink|indigo)-(50|100|200|300|400|500|600|700|800|900|950)$/,
// Typography
/^text-(xs|sm|base|lg|xl|2xl|3xl|4xl|5xl|6xl|7xl|8xl|9xl)$/,
/^font-(thin|extralight|light|normal|medium|semibold|bold|extrabold|black)$/,
/^leading-(3|4|5|6|7|8|9|10|none|tight|snug|normal|relaxed|loose)$/,
// Borders
/^rounded$/,
/^rounded-(sm|md|lg|xl|2xl|3xl|full)$/,
/^border$/,
/^border-(t|r|b|l)$/,
/^border-\d+$/,
// Shadows (Tailwind specific)
/^shadow$/,
/^shadow-(sm|md|lg|xl|2xl|inner)$/,
// Responsive prefixes
/^(sm|md|lg|xl|2xl):/,
// Dark mode
/^dark:/,
// Hover states
/^hover:/,
/^focus:/,
/^active:/
];
return classes.some(cls =>
cls && tailwindClassPatterns.some(pattern => pattern.test(cls))
);
}
// Check multiple elements for better accuracy
const elementsToCheck = [
document.body,
document.documentElement,
...Array.from(document.querySelectorAll('*')).slice(0, 20), // First 20 elements
...Array.from(document.querySelectorAll('[class]')).slice(0, 10) // First 10 with classes
];
const elementsWithTailwindClasses = elementsToCheck.filter(detectTailwindClasses);
detectionResults.tailwindClasses = elementsWithTailwindClasses.length >= 2; // Need at least 2 elements
if (detectionResults.tailwindClasses) confidenceScore += 2;
// 6. Check for Tailwind config or build artifacts (Low confidence: +1)
const hasTailwindConfig = Array.from(document.querySelectorAll('script')).some(script => {
try {
return script.textContent && (
script.textContent.includes('tailwind.config') ||
script.textContent.includes('module.exports')
);
} catch (e) {
return false;
}
});
detectionResults.tailwindConfig = hasTailwindConfig;
if (detectionResults.tailwindConfig) confidenceScore += 1;
// 7. Check for common Tailwind utility combinations (Medium confidence: +2)
const commonTailwindCombos = [
['flex', 'items-center', 'justify-center'],
['w-full', 'h-full'],
['text-center', 'mx-auto'],
['bg-white', 'dark:bg-gray-900'],
['p-4', 'rounded-lg', 'shadow-md']
];
const hasCombos = elementsToCheck.some(element => {
if (!element || !element.className) return false;
const classes = new Set(element.className.split(/\s+/));
return commonTailwindCombos.some(combo =>
combo.every(cls => classes.has(cls))
);
});
detectionResults.utilityCombos = hasCombos;
if (detectionResults.utilityCombos) confidenceScore += 2;
// Calculate confidence level
let confidenceLevel = 'Low';
if (confidenceScore >= 7) confidenceLevel = 'Very High';
else if (confidenceScore >= 5) confidenceLevel = 'High';
else if (confidenceScore >= 3) confidenceLevel = 'Medium';
console.log('π Tailwind Detection Results (Enhanced Precision):');
console.log(' CSS Links:', detectionResults.tailwindLinks, tailwindLinks.length > 0 ? `(${tailwindLinks.length} found)` : '');
console.log(' Style Tags:', detectionResults.tailwindStyles, tailwindStyles.length > 0 ? `(${tailwindStyles.length} found)` : '');
console.log(' Script Tags:', detectionResults.tailwindScripts, tailwindScripts.length > 0 ? `(${tailwindScripts.length} found)` : '');
console.log(' CSS Variables:', detectionResults.tailwindVars, tailwindVars.length > 0 ? `(${tailwindVars.length} vars)` : '');
console.log(' Utility Classes:', detectionResults.tailwindClasses, elementsWithTailwindClasses.length > 0 ? `(${elementsWithTailwindClasses.length} elements)` : '');
console.log(' Config Scripts:', detectionResults.tailwindConfig);
console.log(' Utility Combos:', detectionResults.utilityCombos);
console.log(' Confidence Score:', confidenceScore, `/ 10 (${confidenceLevel})`);
// Require minimum confidence for positive detection
const isDetected = confidenceScore >= 3; // Minimum threshold
console.log(' Final Result:', isDetected ? 'β
Tailwind Detected' : 'β Tailwind Not Detected');
return isDetected;
}
// Extract CSS custom properties
function extractCSSVariables() {
const root = document.documentElement;
const computedStyles = getComputedStyle(root);
const variables = {};
const cssProps = [];
// Get all CSS properties that are custom properties
for (let i = 0; i < computedStyles.length; i++) {
const prop = computedStyles[i];
if (prop.startsWith('--')) {
const value = computedStyles.getPropertyValue(prop).trim();
if (value) { // Only include properties with values
cssProps.push({ property: prop, value: value });
}
}
}
// Group variables by category (more comprehensive)
const grouped = {
colors: cssProps.filter(p =>
p.property.includes('color') ||
p.property.startsWith('--color-') || // v4 uses --color-* naming
p.property.includes('bg') ||
p.property.includes('text') ||
p.property.includes('border') ||
p.property.includes('ring') ||
p.property.includes('shadow') && p.property.includes('color')
),
spacing: cssProps.filter(p =>
p.property.includes('spacing') ||
p.property.startsWith('--spacing-') || // v4 spacing
p.property.includes('padding') ||
p.property.includes('margin') ||
p.property.includes('gap') ||
/^--tw-space-/.test(p.property)
),
typography: cssProps.filter(p =>
p.property.includes('font') ||
p.property.startsWith('--font-') || // v4 fonts
p.property.includes('text') ||
p.property.includes('leading') ||
p.property.includes('tracking') ||
p.property.includes('letter-spacing') ||
p.property.includes('line-height') ||
p.property.includes('font-weight') ||
p.property.includes('text-decoration') ||
p.property.includes('font-feature') ||
p.property.includes('font-variation') ||
p.property.includes('ligatures') ||
p.property.includes('numerical')
),
borders: cssProps.filter(p =>
p.property.includes('border') ||
p.property.includes('radius') ||
p.property.startsWith('--radius-') || // v4 radius
p.property.includes('outline')
),
shadows: cssProps.filter(p =>
p.property.includes('shadow') &&
!p.property.includes('color')
),
animations: cssProps.filter(p =>
p.property.includes('animation') ||
p.property.includes('transition') ||
p.property.includes('transform')
),
other: cssProps.filter(p =>
!p.property.includes('color') && !p.property.includes('bg') &&
!p.property.includes('spacing') && !p.property.includes('padding') && !p.property.includes('margin') &&
!p.property.includes('gap') && !/^--tw-space-/.test(p.property) &&
!p.property.includes('font') && !p.property.includes('leading') && !p.property.includes('tracking') &&
!p.property.includes('letter-spacing') && !p.property.includes('line-height') &&
!p.property.includes('font-weight') && !p.property.includes('text-decoration') &&
!p.property.includes('font-feature') && !p.property.includes('font-variation') &&
!p.property.includes('ligatures') && !p.property.includes('numerical') &&
!p.property.includes('text') &&
!p.property.includes('border') && !p.property.includes('radius') && !p.property.includes('outline') &&
!p.property.includes('shadow') &&
!p.property.includes('animation') && !p.property.includes('transition') && !p.property.includes('transform')
)
};
return grouped;
}
// Extract Tailwind theme colors from CSS variables
function extractTailwindColors(cssVars) {
const colors = {};
// Common Tailwind color patterns (v3 and v4)
const colorPatterns = [
/^--(tw-)?ring$/,
/^--(tw-)?ring-offset$/,
/^--(color|tw-color)-([a-z]+)(?:-(\d+))?$/,
/^--color-([a-z-]+)$/, // v4 uses --color-* naming
/^--(background|foreground)$/,
/^--(primary|secondary|accent|muted|destructive|card|popover|border|input)$/,
/^--(primary|secondary|accent|muted|destructive|card|popover|border|input)-(foreground|DEFAULT)?$/
];
cssVars.colors.forEach(({ property, value }) => {
// Clean property name for both v3 and v4 conventions
const cleanProp = property
.replace(/^--(?:tw-)?/, '')
.replace(/^color-/, ''); // v4 removes color- prefix for cleaner names
colors[cleanProp] = value;
});
return colors;
}
// Extract spacing values
function extractSpacing(cssVars) {
const spacing = {};
cssVars.spacing.forEach(({ property, value }) => {
const cleanProp = property.replace(/^--(?:tw-)?/, '');
spacing[cleanProp] = value;
});
return spacing;
}
// Extract comprehensive typography settings
function extractTypography(cssVars) {
const typography = {
fonts: {},
sizes: {},
weights: {},
lineHeights: {},
letterSpacing: {},
textDecoration: {},
fontFeatures: {},
other: {}
};
cssVars.typography.forEach(({ property, value }) => {
const cleanProp = property.replace(/^--(?:tw-)?/, '');
// Font families (both v3 and v4 formats)
if (cleanProp.includes('font-family') || cleanProp.startsWith('font-') && !cleanProp.includes('size') && !cleanProp.includes('weight')) {
let fontName = cleanProp.replace('font-family-', '').replace('font-', '');
if (fontName === 'sans' || fontName === 'serif' || fontName === 'mono') {
typography.fonts[fontName] = value;
} else {
typography.fonts[fontName] = value;
}
}
// Font sizes
else if (cleanProp.includes('font-size') || (cleanProp.startsWith('text-') && /^\d/.test(cleanProp.replace('text-', '')))) {
const sizeName = cleanProp.replace('font-size-', '').replace('text-', '');
typography.sizes[sizeName] = value;
}
// Font weights
else if (cleanProp.includes('font-weight') || cleanProp.startsWith('font-') && /\b(thin|extralight|light|normal|medium|semibold|bold|extrabold|black)\b/.test(cleanProp)) {
const weightName = cleanProp.replace('font-weight-', '').replace('font-', '');
typography.weights[weightName] = value;
}
// Line heights
else if (cleanProp.includes('leading') || cleanProp.includes('line-height')) {
const leadingName = cleanProp.replace('leading-', '').replace('line-height-', '');
typography.lineHeights[leadingName] = value;
}
// Letter spacing
else if (cleanProp.includes('tracking') || cleanProp.includes('letter-spacing')) {
const trackingName = cleanProp.replace('tracking-', '').replace('letter-spacing-', '');
typography.letterSpacing[trackingName] = value;
}
// Text decoration
else if (cleanProp.includes('text-decoration') || cleanProp.includes('underline') || cleanProp.includes('overline') || cleanProp.includes('line-through')) {
const decorationName = cleanProp.replace('text-decoration-', '');
typography.textDecoration[decorationName] = value;
}
// Font features and variations
else if (cleanProp.includes('font-feature') || cleanProp.includes('font-variation') || cleanProp.includes('ligatures') || cleanProp.includes('numerical')) {
const featureName = cleanProp.replace('font-feature-settings-', '').replace('font-variation-settings-', '');
typography.fontFeatures[featureName] = value;
}
// Other typography properties
else {
typography.other[cleanProp] = value;
}
});
// Clean up empty categories
Object.keys(typography).forEach(key => {
if (Object.keys(typography[key]).length === 0) {
delete typography[key];
}
});
return typography;
}
// Extract border radius
function extractBorderRadius(cssVars) {
const radius = {};
cssVars.borders.forEach(({ property, value }) => {
if (property.includes('radius')) {
const cleanProp = property.replace(/^--(?:tw-)?/, '').replace('border-radius-', '');
radius[cleanProp] = value;
}
});
return radius;
}
// Extract screen breakpoints
function extractBreakpoints() {
const breakpoints = {};
const mediaQueries = [];
// Look for Tailwind's responsive utilities in CSS
const stylesheets = Array.from(document.styleSheets);
stylesheets.forEach(sheet => {
try {
Array.from(sheet.cssRules).forEach(rule => {
if (rule.type === CSSRule.MEDIA_RULE) {
const mediaText = rule.media.mediaText;
if (mediaText.includes('min-width')) {
mediaQueries.push(mediaText);
}
}
});
} catch (e) {
// Skip cross-origin stylesheets
}
});
// Common Tailwind breakpoints
const commonBreakpoints = {
'sm': '640px',
'md': '768px',
'lg': '1024px',
'xl': '1280px',
'2xl': '1536px'
};
// Try to extract from media queries
mediaQueries.forEach(mq => {
const match = mq.match(/min-width:\s*(\d+)px/);
if (match) {
const width = match[1] + 'px';
// Find closest common breakpoint
for (const [name, size] of Object.entries(commonBreakpoints)) {
if (size === width) {
breakpoints[name] = width;
break;
}
}
}
});
return breakpoints;
}
// Extract used Tailwind classes from the page with precision
function extractUsedClasses() {
const elements = document.querySelectorAll('*');
const classes = new Set();
// More precise Tailwind class patterns
const tailwindClassPatterns = [
// Layout & positioning
/^container$/,
/^flex$/,
/^grid$/,
/^hidden$/,
/^block$/,
/^inline$/,
/^inline-block$/,
/^absolute$/,
/^relative$/,
/^fixed$/,
/^sticky$/,
/^static$/,
// Display utilities
/^flex$/,
/^grid$/,
/^hidden$/,
/^block$/,
/^inline$/,
/^inline-block$/,
/^inline-flex$/,
/^inline-grid$/,
// Spacing
/^p-\d+$/,
/^m-\d+$/,
/^px-\d+$/,
/^py-\d+$/,
/^mx-\d+$/,
/^my-\d+$/,
/^mt-\d+$/,
/^mr-\d+$/,
/^mb-\d+$/,
/^ml-\d+$/,
// Width/Height
/^w-\d+$/,
/^h-\d+$/,
/^w-full$/,
/^h-full$/,
/^w-screen$/,
/^h-screen$/,
/^w-auto$/,
/^h-auto$/,
/^max-w-\w+$/,
/^min-w-\w+$/,
/^max-h-\w+$/,
/^min-h-\w+$/,
// Colors (Tailwind specific)
/^bg-(red|blue|green|yellow|purple|pink|indigo|gray|slate|zinc|neutral|stone)-(50|100|200|300|400|500|600|700|800|900|950)$/,
/^bg-(white|black|transparent|current)$/,
/^text-(red|blue|green|yellow|purple|pink|indigo|gray|slate|zinc|neutral|stone)-(50|100|200|300|400|500|600|700|800|900|950)$/,
/^text-(white|black|transparent|current)$/,
/^border-(red|blue|green|yellow|purple|pink|indigo|gray|slate|zinc|neutral|stone)-(50|100|200|300|400|500|600|700|800|900|950)$/,
// Typography (comprehensive)
/^text-(xs|sm|base|lg|xl|2xl|3xl|4xl|5xl|6xl|7xl|8xl|9xl)$/,
/^font-(thin|extralight|light|normal|medium|semibold|bold|extrabold|black)$/,
/^font-(sans|serif|mono)$/,
/^font-(100|200|300|400|500|600|700|800|900)$/,
/^leading-(3|4|5|6|7|8|9|10|none|tight|snug|normal|relaxed|loose)$/,
/^tracking-(tighter|tight|normal|wide|wider|widest)$/,
/^text-(left|center|right|justify)$/,
/^text-(uppercase|lowercase|capitalize)$/,
/^underline$/, /^line-through$/, /^no-underline$/,
/^italic$/, /^not-italic$/,
/^whitespace-(normal|nowrap|pre|pre-line|pre-wrap)$/,
/^break-(normal|words|all)$/,
/^truncate$/, /^text-ellipsis$/, /^text-clip$/,
// Borders
/^rounded$/,
/^rounded-(sm|md|lg|xl|2xl|3xl|full)$/,
/^rounded-(t|r|b|l)-(sm|md|lg|xl|2xl|3xl|full)$/,
/^border$/,
/^border-(t|r|b|l)$/,
/^border-\d+$/,
// Shadows
/^shadow$/,
/^shadow-(sm|md|lg|xl|2xl|inner)$/,
/^shadow-(black|white|gray|blue|red|green|yellow|purple|pink)\/\d+$/,
// Effects
/^opacity-\d+$/,
/^blur$/,
/^blur-(sm|md|lg|xl|2xl)$/,
// Responsive prefixes
/^(sm|md|lg|xl|2xl):/,
// Dark mode
/^dark:/,
// Hover/Focus states
/^hover:/,
/^focus:/,
/^active:/,
/^disabled:/,
// Z-index
/^z-\d+$/,
/^z-auto$/
];
// Check all elements, not just first 100
const elementsToCheck = Array.from(elements);
elementsToCheck.forEach(el => {
if (el.className && typeof el.className === 'string') {
el.className.split(/\s+/).forEach(cls => {
if (cls && cls.trim()) {
// Check if it matches any Tailwind pattern
const isTailwindClass = tailwindClassPatterns.some(pattern =>
pattern.test(cls)
);
if (isTailwindClass) {
classes.add(cls);
}
}
});
}
});
// Also check for classes in data attributes and dynamic content
const dataAttributes = document.querySelectorAll('[class]');
dataAttributes.forEach(el => {
if (el.className && typeof el.className === 'string') {
el.className.split(/\s+/).forEach(cls => {
if (cls && cls.trim()) {
const isTailwindClass = tailwindClassPatterns.some(pattern =>
pattern.test(cls)
);
if (isTailwindClass) {
classes.add(cls);
}
}
});
}
});
return Array.from(classes).sort();
}
// Check for dark mode configuration
function checkDarkMode() {
const html = document.documentElement;
const body = document.body;
return {
hasDarkMode: html.classList.contains('dark') || body.classList.contains('dark'),
darkModeStrategy: html.hasAttribute('data-theme') ? 'data-theme' :
html.classList.contains('dark') ? 'class' : 'unknown'
};
}
// Main extraction function
function extractTailwindConfig() {
const tailwindDetected = isTailwindLoaded();
if (!tailwindDetected) {
console.warn('β οΈ Tailwind CSS does not appear to be loaded on this page');
console.log('π Attempting fallback extraction anyway...');
// Even if detection fails, try to extract what we can
// (some sites might use Tailwind classes dynamically or in non-standard ways)
} else {
console.log('β
Tailwind CSS detected');
}
const cssVars = extractCSSVariables();
// If we have CSS variables, it's likely Tailwind or similar
const hasAnyVars = Object.values(cssVars).some(group => group.length > 0);
if (!tailwindDetected && !hasAnyVars) {
console.log('β No Tailwind-related CSS variables found either');
console.log('π‘ This page may not be using Tailwind CSS, or it might be configured differently');
return null;
}
if (!tailwindDetected && hasAnyVars) {
console.log('π Found CSS variables that might be Tailwind-related, proceeding with extraction...');
}
const config = {
darkMode: checkDarkMode(),
theme: {
colors: extractTailwindColors(cssVars),
spacing: extractSpacing(cssVars),
typography: extractTypography(cssVars),
borderRadius: extractBorderRadius(cssVars),
screens: extractBreakpoints()
},
usedClasses: extractUsedClasses(),
cssVariables: cssVars
};
return config;
}
// Display results with enhanced precision
function displayResults(config) {
if (!config) return;
console.log('\nπ― Tailwind CSS Configuration Extracted (v3/v4 Compatible):');
console.log('===========================================================');
// Summary with precision metrics
const totalVars = Object.values(config.cssVariables || {}).reduce((sum, group) => sum + (group?.length || 0), 0);
const totalCategories = Object.values(config.cssVariables || {}).filter(group => group?.length > 0).length;
console.log(`π Precision Analysis:`);
console.log(` Total Tailwind Variables: ${totalVars}`);
console.log(` Active Categories: ${totalCategories}/8`);
console.log(` Verified Classes: ${config.usedClasses.length}`);
// Version detection attempt
const versionIndicators = detectTailwindVersion(config);
if (versionIndicators.version) {
console.log(` Detected Version: ${versionIndicators.version} (${versionIndicators.confidence})`);
}
console.log('\nπ Dark Mode Configuration:');
console.log(` Strategy: ${config.darkMode.darkModeStrategy}`);
console.log(` Currently Active: ${config.darkMode.hasDarkMode}`);
// Colors (enhanced display)
if (config.cssVariables?.colors?.length > 0) {
console.log('\nπ¨ Color System Variables:');
const colorGroups = groupColorsByType(config.cssVariables.colors);
Object.entries(colorGroups).forEach(([type, colors]) => {
console.log(` ${type}:`);
colors.slice(0, 8).forEach(({ property, value }) => {
console.log(` ${property}: ${value}`);
});
if (colors.length > 8) {
console.log(` ... and ${colors.length - 8} more ${type.toLowerCase()}`);
}
});
}
// Spacing (enhanced)
if (config.cssVariables?.spacing?.length > 0) {
console.log('\nπ Spacing & Layout Variables:');
const spacingByType = groupSpacingByType(config.cssVariables.spacing);
Object.entries(spacingByType).forEach(([type, vars]) => {
console.log(` ${type}: ${vars.length} variables`);
});
// Show sample spacing values
config.cssVariables.spacing.slice(0, 6).forEach(({ property, value }) => {
console.log(` ${property}: ${value}`);
});
}
// Typography (comprehensive)
if (config.cssVariables?.typography?.length > 0) {
console.log('\nπ Typography System:');
const typographyByType = groupTypographyByType(config.cssVariables.typography);
Object.entries(typographyByType).forEach(([type, vars]) => {
console.log(` ${type}: ${vars.length} variables`);
if (vars.length > 0) {
// Show different preview based on category
if (type === 'Font Families') {
vars.slice(0, 4).forEach(({ property, value }) => {
const fontName = property.replace(/^--(?:tw-)?(?:font-)?(?:family-)?/, '');
console.log(` ${fontName}: ${value}`);
});
} else if (type === 'Font Sizes') {
vars.slice(0, 6).forEach(({ property, value }) => {
const sizeName = property.replace(/^--(?:tw-)?(?:font-size-|text-)/, '');
console.log(` ${sizeName}: ${value}`);
});
} else if (type === 'Font Weights') {
vars.slice(0, 5).forEach(({ property, value }) => {
const weightName = property.replace(/^--(?:tw-)?(?:font-weight-|font-)/, '');
console.log(` ${weightName}: ${value}`);
});
} else {
vars.slice(0, 3).forEach(({ property, value }) => {
const propName = property.replace(/^--(?:tw-)?/, '');
console.log(` ${propName}: ${value}`);
});
}
if (vars.length > (type === 'Font Families' ? 4 : type === 'Font Sizes' ? 6 : 3)) {
console.log(` ... and ${vars.length - (type === 'Font Families' ? 4 : type === 'Font Sizes' ? 6 : 3)} more`);
}
}
});
}
// Layout utilities
if (config.cssVariables?.layout?.length > 0) {
console.log('\nπ Layout Variables:');
console.log(` Size utilities: ${config.cssVariables?.layout?.length || 0} variables`);
config.cssVariables.layout.slice(0, 4).forEach(({ property, value }) => {
console.log(` ${property}: ${value}`);
});
}
// Effects & animations
const effectsCount = (config.cssVariables?.effects?.length || 0) + (config.cssVariables?.animations?.length || 0);
if (effectsCount > 0) {
console.log('\n⨠Effects & Animations:');
console.log(` Shadow effects: ${config.cssVariables?.effects?.length || 0}`);
console.log(` Animation/Transition: ${config.cssVariables?.animations?.length || 0}`);
}
// Borders
if (config.cssVariables?.borders?.length > 0) {
console.log('\nπ² Border & Radius System:');
console.log(` Border utilities: ${config.cssVariables?.borders?.length || 0} variables`);
}
console.log('\nπ± Responsive Breakpoints:');
if (Object.keys(config.theme.screens).length > 0) {
Object.entries(config.theme.screens).forEach(([key, value]) => {
console.log(` ${key}: ${value}`);
});
} else {
console.log(' No custom breakpoints detected (using defaults)');
}
// Used classes with categorization
if (config.usedClasses.length > 0) {
console.log('\nπ·οΈ Verified Tailwind Classes:');
const classCategories = categorizeClasses(config.usedClasses);
Object.entries(classCategories).forEach(([category, classes]) => {
if (classes.length > 0) {
console.log(` ${category}: ${classes.length} classes`);
classes.slice(0, 8).forEach(cls => {
console.log(` ${cls}`);
});
if (classes.length > 8) {
console.log(` ... and ${classes.length - 8} more`);
}
}
});
}
console.log('\nπΎ Detailed Variable Summary:');
const summary = [
`π¨ Colors: ${config.cssVariables?.colors?.length || 0}`,
`π Spacing: ${config.cssVariables?.spacing?.length || 0}`,
`π Typography: ${config.cssVariables?.typography?.length || 0} (fonts, sizes, weights, spacing)`,
`π Layout: ${config.cssVariables?.layout?.length || 0}`,
`β¨ Effects: ${config.cssVariables?.effects?.length || 0}`,
`π Animations: ${config.cssVariables?.animations?.length || 0}`,
`π² Borders: ${config.cssVariables?.borders?.length || 0}`,
`β Other: ${config.cssVariables?.other?.length || 0}`
];
summary.forEach(line => console.log(` ${line}`));
// Make config available globally for further inspection
window.extractedTailwindConfig = config;
console.log('\nπ Full config available as: window.extractedTailwindConfig');
// Provide export functionality
console.log('\nπ€ Export Options:');
console.log(' Copy to clipboard: copy(window.extractedTailwindConfig)');
console.log(' Download as JSON: downloadTailwindConfig()');
console.log(' π Download complete tailwind.config.js: downloadTailwindConfigFile()');
console.log(' π Generate tailwind.config.js: generateTailwindConfigFile()');
console.log(' π¨π Copy Colors & Typography (Full Markdown): copyColorsAndTypography()');
console.log(' Generate v4 config (CSS): generateTailwindConfig("v4")');
console.log(' Generate v3 config (JS): generateTailwindConfig("v3")');
console.log(' Auto-detect version: generateTailwindConfig()');
// Add enhanced download function
window.downloadTailwindConfig = function() {
const dataStr = JSON.stringify(config, null, 2);
const dataUri = 'data:application/json;charset=utf-8,'+ encodeURIComponent(dataStr);
const exportFileDefaultName = `tailwind-config-${window.location.hostname}-${new Date().toISOString().split('T')[0]}.json`;
const linkElement = document.createElement('a');
linkElement.setAttribute('href', dataUri);
linkElement.setAttribute('download', exportFileDefaultName);
linkElement.click();
};
// Generate complete tailwind.config.js file
function generateTailwindConfigFile(extractedConfig) {
const today = new Date().toISOString().split('T')[0];
const config = {
darkMode: extractedConfig.darkMode.darkModeStrategy === 'class' ? 'class' : 'media',
content: ['./src/**/*.{html,ts,js,jsx,tsx,vue,svelte}'], // Default content paths
theme: {
extend: {}
},
plugins: []
};
// Process colors with comprehensive palette detection
if (extractedConfig.cssVariables.colors && extractedConfig.cssVariables.colors.length > 0) {
const colorMap = {};
const customPalettes = {};
extractedConfig.cssVariables.colors.forEach(({ property, value }) => {
const propName = property.replace(/^--(?:tw-)?color-/, '').replace(/^--/, '');
// Handle semantic colors
if (propName === 'background') colorMap.background = value;
else if (propName === 'foreground') colorMap.foreground = value;
else if (propName === 'primary') colorMap.primary = { DEFAULT: value };
else if (propName === 'secondary') colorMap.secondary = { DEFAULT: value };
else if (propName === 'accent') colorMap.accent = { DEFAULT: value };
else if (propName === 'muted') colorMap.muted = { DEFAULT: value };
else if (propName === 'destructive') colorMap.destructive = { DEFAULT: value };
else if (propName === 'border') colorMap.border = value;
else if (propName === 'input') colorMap.input = value;
else if (propName === 'ring') colorMap.ring = value;
else if (propName === 'card') colorMap.card = { DEFAULT: value };
else if (propName === 'popover') colorMap.popover = { DEFAULT: value };
// Handle sidebar colors (if present)
else if (propName.startsWith('sidebar')) {
if (!colorMap.sidebar) colorMap.sidebar = {};
const sidebarProp = propName.replace('sidebar-', '').replace('-', '_');
colorMap.sidebar[sidebarProp] = value;
}
// Handle chart colors (if present)
else if (propName.startsWith('chart-')) {
if (!colorMap.chart) colorMap.chart = {};
const chartNum = propName.replace('chart-', '');
colorMap.chart[chartNum] = value;
}
// Handle custom color palettes (detect by pattern)
else {
const colorMatch = propName.match(/^([a-z-]+)-(\d+)$/);
if (colorMatch) {
const [, paletteName, shade] = colorMatch;
if (!customPalettes[paletteName]) customPalettes[paletteName] = {};
customPalettes[paletteName][shade] = value;
}
}
});
// Add semantic colors
if (Object.keys(colorMap).length > 0) {
config.theme.extend.colors = { ...config.theme.extend.colors, ...colorMap };
}
// Add custom palettes
Object.entries(customPalettes).forEach(([paletteName, palette]) => {
if (!config.theme.extend.colors) config.theme.extend.colors = {};
config.theme.extend.colors[paletteName] = palette;
});
}
// Process comprehensive typography
if (extractedConfig.cssVariables.typography && extractedConfig.cssVariables.typography.length > 0) {
const fontMap = {};
const textSizeMap = {};
const fontWeightMap = {};
const lineHeightMap = {};
const letterSpacingMap = {};
extractedConfig.cssVariables.typography.forEach(({ property, value }) => {
const propName = property.replace(/^--(?:tw-)?/, '');
// Font families
if (propName.includes('font-family') || (propName.startsWith('font-') && !propName.includes('size') && !propName.includes('weight'))) {
const fontName = propName.replace('font-family-', '').replace('font-', '');
fontMap[fontName] = value.replace(/"/g, '').split(', ');
}
// Font sizes
else if (propName.includes('font-size') || (propName.startsWith('text-') && /^\d/.test(propName.replace('text-', '')))) {
const size = propName.replace('font-size-', '').replace('text-', '');
textSizeMap[size] = value;
}
// Font weights
else if (propName.includes('font-weight') || propName.startsWith('font-') && /\b(thin|extralight|light|normal|medium|semibold|bold|extrabold|black)\b/.test(propName)) {
const weightName = propName.replace('font-weight-', '').replace('font-', '');
fontWeightMap[weightName] = value;
}
// Line heights
else if (propName.includes('leading') || propName.includes('line-height')) {
const leadingName = propName.replace('leading-', '').replace('line-height-', '');
lineHeightMap[leadingName] = value;
}
// Letter spacing
else if (propName.includes('tracking') || propName.includes('letter-spacing')) {
const trackingName = propName.replace('tracking-', '').replace('letter-spacing-', '');
letterSpacingMap[trackingName] = value;
}
});
if (Object.keys(fontMap).length > 0) {
config.theme.extend.fontFamily = fontMap;
}
if (Object.keys(textSizeMap).length > 0) {
config.theme.extend.fontSize = textSizeMap;
}
if (Object.keys(fontWeightMap).length > 0) {
config.theme.extend.fontWeight = fontWeightMap;
}
if (Object.keys(lineHeightMap).length > 0) {
config.theme.extend.lineHeight = lineHeightMap;
}
if (Object.keys(letterSpacingMap).length > 0) {
config.theme.extend.letterSpacing = letterSpacingMap;
}
}
// Process border radius
if (extractedConfig.cssVariables.borders && extractedConfig.cssVariables.borders.length > 0) {
const radiusMap = {};
extractedConfig.cssVariables.borders.forEach(({ property, value }) => {
if (property.includes('radius')) {
const radiusName = property.replace(/^--(?:tw-)?/, '').replace('border-radius-', '').replace('radius-', '');
radiusMap[radiusName] = value;