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
|
#!/usr/bin/env python3
"""
Plugin framework per CSS Cleaner - supporto per framework popolari
"""
from abc import ABC, abstractmethod
from typing import Dict, List, Set, Any, Optional
import re
import json
from pathlib import Path
class FrameworkPlugin(ABC):
"""Base class per plugin framework"""
@property
@abstractmethod
def framework_name(self) -> str:
"""Nome del framework"""
pass
@property
@abstractmethod
def supported_extensions(self) -> List[str]:
"""Estensioni file supportate"""
pass
@abstractmethod
def extract_selectors(self, file_path: str, content: str) -> Set[str]:
"""Estrae selettori specifici del framework"""
pass
@abstractmethod
def should_keep_selector(self, selector: str, context: Dict) -> bool:
"""Determina se mantenere un selettore"""
pass
class ReactPlugin(FrameworkPlugin):
"""Plugin per React e JSX"""
@property
def framework_name(self) -> str:
return "React"
@property
def supported_extensions(self) -> List[str]:
return ['.jsx', '.tsx', '.js', '.ts']
def extract_selectors(self, file_path: str, content: str) -> Set[str]:
selectors = set()
# Pattern per className in JSX
className_patterns = [
r'className\s*=\s*["\']([^"\']+)["\']',
r'className\s*=\s*{["\']([^"\']+)["\']',
r'className\s*=\s*{\s*`([^`]+)`\s*}',
r'className\s*=\s*{([^}]+)}', # Espressioni dinamiche
]
for pattern in className_patterns:
matches = re.findall(pattern, content, re.MULTILINE)
for match in matches:
# Gestisci classi multiple
class_names = match.split()
for class_name in class_names:
# Pulisci caratteri speciali da espressioni JS
cleaned = re.sub(r'[{}$`]', '', class_name).strip()
if cleaned and cleaned.isidentifier():
selectors.add(f".{cleaned}")
# CSS Modules pattern
css_modules_pattern = r'styles\.(\w+)'
css_modules_matches = re.findall(css_modules_pattern, content)
for match in css_modules_matches:
selectors.add(f".{match}")
# Styled Components pattern
styled_pattern = r'styled\.(\w+)`([^`]+)`'
styled_matches = re.findall(styled_pattern, content, re.DOTALL)
for tag, css_content in styled_matches:
# Estrai selettori dal CSS di styled-components
css_selectors = self._extract_css_selectors_from_template(css_content)
selectors.update(css_selectors)
return selectors
def should_keep_selector(self, selector: str, context: Dict) -> bool:
# Mantieni selettori comunemente usati in React
react_common = [
'.react-', '.rc-', '.ant-', '.mui-', '.chakra-', # UI libraries
'.App', '.app', '.container', '.wrapper', '.root', # Common patterns
]
return any(selector.startswith(prefix) for prefix in react_common)
def _extract_css_selectors_from_template(self, css_content: str) -> Set[str]:
"""Estrae selettori da template CSS di styled-components"""
selectors = set()
# Pattern per selettori CSS dentro template literals
selector_patterns = [
r'&\.(\w+)', # &.className
r'\.(\w+)', # .className
r'#(\w+)', # #id
]
for pattern in selector_patterns:
matches = re.findall(pattern, css_content)
for match in matches:
if pattern.startswith('&\\.'):
selectors.add(f".{match}")
elif pattern.startswith('\\.'):
selectors.add(f".{match}")
else:
selectors.add(f"#{match}")
return selectors
class VuePlugin(FrameworkPlugin):
"""Plugin per Vue.js"""
@property
def framework_name(self) -> str:
return "Vue"
@property
def supported_extensions(self) -> List[str]:
return ['.vue', '.js', '.ts']
def extract_selectors(self, file_path: str, content: str) -> Set[str]:
selectors = set()
# Pattern per Vue SFC (Single File Components)
if file_path.endswith('.vue'):
selectors.update(self._extract_from_vue_sfc(content))
else:
selectors.update(self._extract_from_vue_js(content))
return selectors
def _extract_from_vue_sfc(self, content: str) -> Set[str]:
"""Estrae selettori da Vue Single File Component"""
selectors = set()
# Estrai sezione template
template_match = re.search(r'<template[^>]*>(.*?)</template>', content, re.DOTALL)
if template_match:
template_content = template_match.group(1)
# Pattern per :class binding
class_binding_patterns = [
r':class\s*=\s*["\']([^"\']+)["\']',
r':class\s*=\s*{([^}]+)}',
r'v-bind:class\s*=\s*["\']([^"\']+)["\']',
r'class\s*=\s*["\']([^"\']+)["\']',
]
for pattern in class_binding_patterns:
matches = re.findall(pattern, template_content)
for match in matches:
if '{' not in match: # Stringa semplice
class_names = match.split()
for class_name in class_names:
selectors.add(f".{class_name}")
else: # Oggetto o espressione
# Estrai nomi classi da oggetti JavaScript
class_names = re.findall(r'["\'](\w+)["\']', match)
for class_name in class_names:
selectors.add(f".{class_name}")
# Estrai sezione style con scoped
style_matches = re.finditer(r'<style[^>]*scoped[^>]*>(.*?)</style>', content, re.DOTALL)
for style_match in style_matches:
style_content = style_match.group(1)
# In Vue scoped styles, tutti i selettori sono potenzialmente utilizzati
css_selectors = re.findall(r'\.(\w+)', style_content)
for selector in css_selectors:
selectors.add(f".{selector}")
return selectors
def _extract_from_vue_js(self, content: str) -> Set[str]:
"""Estrae selettori da file JavaScript Vue"""
selectors = set()
# Pattern per template strings in Vue components
template_pattern = r'template\s*:\s*`([^`]+)`'
template_matches = re.findall(template_pattern, content, re.DOTALL)
for template in template_matches:
# Stessi pattern del SFC template
class_matches = re.findall(r'class\s*=\s*["\']([^"\']+)["\']', template)
for match in class_matches:
class_names = match.split()
for class_name in class_names:
selectors.add(f".{class_name}")
return selectors
def should_keep_selector(self, selector: str, context: Dict) -> bool:
# Mantieni selettori Vue comuni
vue_common = [
'.v-', '.vue-', '.el-', # Vue/Element UI prefixes
'.fade-', '.slide-', '.bounce-', # Transition classes
]
return any(selector.startswith(prefix) for prefix in vue_common)
class AngularPlugin(FrameworkPlugin):
"""Plugin per Angular"""
@property
def framework_name(self) -> str:
return "Angular"
@property
def supported_extensions(self) -> List[str]:
return ['.ts', '.html', '.scss', '.css']
def extract_selectors(self, file_path: str, content: str) -> Set[str]:
selectors = set()
if file_path.endswith('.html'):
selectors.update(self._extract_from_angular_template(content))
elif file_path.endswith('.ts'):
selectors.update(self._extract_from_angular_component(content))
return selectors
def _extract_from_angular_template(self, content: str) -> Set[str]:
"""Estrae selettori da template Angular"""
selectors = set()
# Pattern per [ngClass]
ng_class_patterns = [
r'\[ngClass\]\s*=\s*["\']([^"\']+)["\']',
r'\[ngClass\]\s*=\s*{([^}]+)}',
r'ngClass\s*=\s*["\']([^"\']+)["\']',
]
for pattern in ng_class_patterns:
matches = re.findall(pattern, content)
for match in matches:
# Estrai nomi classi
class_names = re.findall(r'["\'](\w+)["\']', match)
for class_name in class_names:
selectors.add(f".{class_name}")
# Pattern per class normale
class_matches = re.findall(r'class\s*=\s*["\']([^"\']+)["\']', content)
for match in class_matches:
class_names = match.split()
for class_name in class_names:
selectors.add(f".{class_name}")
return selectors
def _extract_from_angular_component(self, content: str) -> Set[str]:
"""Estrae selettori da componente Angular TypeScript"""
selectors = set()
# Pattern per template inline
template_pattern = r'template\s*:\s*`([^`]+)`'
template_matches = re.findall(template_pattern, content, re.DOTALL)
for template in template_matches:
selectors.update(self._extract_from_angular_template(template))
# Pattern per styleUrls e styles
styles_pattern = r'styles\s*:\s*\[\s*`([^`]+)`\s*\]'
styles_matches = re.findall(styles_pattern, content, re.DOTALL)
for styles in styles_matches:
css_selectors = re.findall(r'\.(\w+)', styles)
for selector in css_selectors:
selectors.add(f".{selector}")
return selectors
def should_keep_selector(self, selector: str, context: Dict) -> bool:
# Mantieni selettori Angular comuni
angular_common = [
'.mat-', '.cdk-', '.ng-', # Angular Material/CDK
'.p-', # PrimeNG
'.ngx-', # NGX libraries
]
return any(selector.startswith(prefix) for prefix in angular_common)
class TailwindPlugin(FrameworkPlugin):
"""Plugin per Tailwind CSS"""
def __init__(self):
# Carica configurazione Tailwind se disponibile
self.config = self._load_tailwind_config()
self.utility_patterns = self._build_utility_patterns()
@property
def framework_name(self) -> str:
return "Tailwind"
@property
def supported_extensions(self) -> List[str]:
return ['.html', '.jsx', '.tsx', '.vue', '.svelte', '.php', '.twig']
def extract_selectors(self, file_path: str, content: str) -> Set[str]:
selectors = set()
# Pattern per classi Tailwind
class_patterns = [
r'class\s*=\s*["\']([^"\']+)["\']',
r'className\s*=\s*["\']([^"\']+)["\']',
r':class\s*=\s*["\']([^"\']+)["\']',
]
for pattern in class_patterns:
matches = re.findall(pattern, content)
for match in matches:
class_names = match.split()
for class_name in class_names:
if self._is_tailwind_class(class_name):
selectors.add(f".{class_name}")
return selectors
def _is_tailwind_class(self, class_name: str) -> bool:
"""Verifica se una classe è una utility Tailwind"""
# Pattern comuni Tailwind
tailwind_patterns = [
r'^(bg|text|border|p|m|w|h)-', # Background, text, border, padding, margin, width, height
r'^(flex|grid|block|inline|hidden)', # Display
r'^(justify|items|self)-', # Flexbox/Grid
r'^(rounded|shadow|opacity)-', # Effects
r'^(hover|focus|active|disabled):', # States
r'^(sm|md|lg|xl|2xl):', # Breakpoints
r'^(space|divide)-', # Space/Divide
]
return any(re.match(pattern, class_name) for pattern in tailwind_patterns)
def should_keep_selector(self, selector: str, context: Dict) -> bool:
# In Tailwind, mantieni tutte le utilities che matchano i pattern
class_name = selector[1:] # Rimuovi il punto
return self._is_tailwind_class(class_name)
def _load_tailwind_config(self) -> Dict:
"""Carica configurazione Tailwind se disponibile"""
config_files = ['tailwind.config.js', 'tailwind.config.ts']
for config_file in config_files:
if Path(config_file).exists():
try:
# Parsing semplificato della config Tailwind
with open(config_file, 'r') as f:
content = f.read()
# Estrai content paths
content_match = re.search(r'content\s*:\s*\[(.*?)\]', content, re.DOTALL)
if content_match:
content_paths = re.findall(r'["\']([^"\']+)["\']', content_match.group(1))
return {'content': content_paths}
except Exception:
pass
return {}
def _build_utility_patterns(self) -> List[str]:
"""Costruisce pattern per utilities Tailwind"""
# Pattern base per utilities Tailwind più comuni
return [
r'^bg-(slate|gray|zinc|neutral|stone|red|orange|amber|yellow|lime|green|emerald|teal|cyan|sky|blue|indigo|violet|purple|fuchsia|pink|rose)-\d+$',
r'^text-(xs|sm|base|lg|xl|2xl|3xl|4xl|5xl|6xl|7xl|8xl|9xl)$',
r'^(p|m|w|h)-\d+$',
r'^(flex|grid|block|inline-block|inline|hidden)$',
]
class FrameworkDetector:
"""Rileva automaticamente il framework utilizzato"""
def __init__(self, project_root: str):
self.project_root = Path(project_root)
self.detected_frameworks = self._detect_frameworks()
def _detect_frameworks(self) -> Dict[str, bool]:
"""Rileva framework presenti nel progetto"""
frameworks = {
'react': False,
'vue': False,
'angular': False,
'tailwind': False,
'bootstrap': False,
}
# Controlla package.json
package_json = self.project_root / 'package.json'
if package_json.exists():
try:
with open(package_json) as f:
package_data = json.load(f)
dependencies = {**package_data.get('dependencies', {}),
**package_data.get('devDependencies', {})}
if any(dep.startswith('react') for dep in dependencies):
frameworks['react'] = True
if any(dep.startswith('vue') for dep in dependencies):
frameworks['vue'] = True
if any(dep.startswith('@angular') for dep in dependencies):
frameworks['angular'] = True
if 'tailwindcss' in dependencies:
frameworks['tailwind'] = True
if 'bootstrap' in dependencies:
frameworks['bootstrap'] = True
except Exception:
pass
# Controlla file di configurazione specifici
config_files = {
'angular.json': 'angular',
'vue.config.js': 'vue',
'tailwind.config.js': 'tailwind',
'tailwind.config.ts': 'tailwind',
}
for config_file, framework in config_files.items():
if (self.project_root / config_file).exists():
frameworks[framework] = True
return frameworks
def get_recommended_plugins(self) -> List[FrameworkPlugin]:
"""Restituisce plugin raccomandati basati sui framework rilevati"""
plugins = []
if self.detected_frameworks['react']:
plugins.append(ReactPlugin())
if self.detected_frameworks['vue']:
plugins.append(VuePlugin())
if self.detected_frameworks['angular']:
plugins.append(AngularPlugin())
if self.detected_frameworks['tailwind']:
plugins.append(TailwindPlugin())
return plugins
class FrameworkAwareCSSCleaner:
"""CSS Cleaner con supporto framework avanzato"""
def __init__(self, html_dir: str, css_dir: str, output_dir: str = None, project_root: str = "."):
self.html_dir = Path(html_dir)
self.css_dir = Path(css_dir)
self.output_dir = Path(output_dir) if output_dir else self.css_dir
# Rileva framework e carica plugin
self.detector = FrameworkDetector(project_root)
self.plugins = self.detector.get_recommended_plugins()
print(f"Framework rilevati: {list(k for k, v in self.detector.detected_frameworks.items() if v)}")
print(f"Plugin caricati: {[p.framework_name for p in self.plugins]}")
def extract_framework_selectors(self) -> Set[str]:
"""Estrae selettori usando tutti i plugin framework"""
all_selectors = set()
# Scansiona tutti i file supportati
for plugin in self.plugins:
for ext in plugin.supported_extensions:
pattern = f"**/*{ext}"
# Cerca in directory HTML e altre directory del progetto
search_paths = [self.html_dir, self.html_dir.parent]
for search_path in search_paths:
if search_path.exists():
for file_path in search_path.rglob(pattern):
try:
with open(file_path, 'r', encoding='utf-8', errors='ignore') as f:
content = f.read()
selectors = plugin.extract_selectors(str(file_path), content)
all_selectors.update(selectors)
if selectors:
print(f"Trovati {len(selectors)} selettori in {file_path} usando il plugin {plugin.framework_name}")
except Exception as e:
print(f"Errore durante l'elaborazione di {file_path}: {e}")
return all_selectors
def should_keep_selector_with_plugins(self, selector: str) -> bool:
"""Verifica se mantenere un selettore consultando i plugin"""
context = {
'detected_frameworks': self.detector.detected_frameworks
}
# Se almeno un plugin dice di mantenerlo, mantienilo
for plugin in self.plugins:
if plugin.should_keep_selector(selector, context):
return True
return False
# Esempio di utilizzo completo
if __name__ == "__main__":
# Inizializza CSS Cleaner con supporto framework
cleaner = FrameworkAwareCSSCleaner(
html_dir="./src",
css_dir="./public/css",
output_dir="./dist/css",
project_root="."
)
# Estrai selettori con plugin framework
framework_selectors = cleaner.extract_framework_selectors()
print(f"Total framework selectors found: {len(framework_selectors)}")
# Esempio di utilizzo dei plugin
react_plugin = ReactPlugin()
# Test con contenuto React
react_content = """
function MyComponent() {
return (
<div className="container mx-auto">
<h1 className={`title ${isActive ? 'active' : 'inactive'}`}>
Hello World
</h1>
<Button className="btn-primary">Click me</Button>
</div>
);
}
"""
react_selectors = react_plugin.extract_selectors("Component.jsx", react_content)
print(f"React selectors: {react_selectors}")
|