-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathREVERSE CASCADE.js
More file actions
336 lines (272 loc) Β· 10.6 KB
/
REVERSE CASCADE.js
File metadata and controls
336 lines (272 loc) Β· 10.6 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
/**
* CSS Cascade Inspector
* Analyzes which styles won the cascade battle for a given element
* @param {string|Element} target - CSS selector or DOM element
* @param {Object} options - Configuration options
*/
(function inspectCascade(target, options) {
'use strict';
target = target || 'a';
options = options || {};
const config = {
showAllProps: false,
groupByProperty: true,
includeInherited: false,
filterProps: null,
verbose: true,
outputMarkdown: true,
autoCopy: true,
...options
};
// ============================================================================
// ELEMENT RESOLUTION
// ============================================================================
const element = typeof target === 'string'
? document.querySelector(target)
: target;
if (!element) {
console.error('β Element not found:', target);
return null;
}
// ============================================================================
// SPECIFICITY CALCULATION (W3C spec-compliant)
// ============================================================================
function calculateSpecificity(selector) {
let normalized = selector.replace(/::[a-z-]+/gi, '');
normalized = normalized.replace(/:where\([^)]*\)/g, '');
normalized = normalized.replace(/:(?:not|is|has)\(([^)]*)\)/g, '$1');
const counts = { ids: 0, classes: 0, elements: 0 };
counts.ids = (normalized.match(/#[a-z0-9_-]+/gi) || []).length;
counts.classes = (normalized.match(/(\.[a-z0-9_-]+|\[[^\]]+\]|:[a-z-]+(?!\())/gi) || []).length;
counts.elements = (normalized.match(/(?:^|[\s>+~])(?![:,#\.\[])[a-z0-9_-]+/gi) || []).length;
return {
value: [counts.ids, counts.classes, counts.elements],
toString() { return this.value.join(','); },
compare(other) {
for (let i = 0; i < 3; i++) {
if (this.value[i] !== other.value[i]) {
return this.value[i] - other.value[i];
}
}
return 0;
}
};
}
// ============================================================================
// STYLE COLLECTION
// ============================================================================
const computed = getComputedStyle(element);
const declarations = new Map();
class Declaration {
constructor(data) {
Object.assign(this, data);
this.specificity = data.specificity || calculateSpecificity(data.selector);
}
compareTo(other) {
if (this.isInline && !other.isInline) return !this.important && other.important ? -1 : 1;
if (!this.isInline && other.isInline) return this.important && !other.important ? 1 : -1;
if (this.important && !other.important) return 1;
if (!this.important && other.important) return -1;
const specDiff = this.specificity.compare(other.specificity);
if (specDiff !== 0) return specDiff;
return this.order - other.order;
}
}
let globalOrder = 0;
[...document.styleSheets].forEach((sheet) => {
let rules;
try {
rules = [...sheet.cssRules];
} catch (e) {
console.warn('β οΈ Cannot access stylesheet:', sheet.href, e.message);
return;
}
rules.forEach((rule) => {
if (rule instanceof CSSStyleRule) {
if (!element.matches(rule.selectorText)) return;
[...rule.style].forEach(prop => {
if (config.filterProps && !config.filterProps.includes(prop)) return;
if (!declarations.has(prop)) declarations.set(prop, []);
declarations.get(prop).push(new Declaration({
property: prop,
value: rule.style.getPropertyValue(prop),
important: rule.style.getPropertyPriority(prop) === 'important',
selector: rule.selectorText,
source: sheet.href || (sheet.ownerNode?.id ? '<style id="' + sheet.ownerNode.id + '">' : '<style>'),
isInline: false,
order: globalOrder++
}));
});
}
});
});
[...element.style].forEach(prop => {
if (config.filterProps && !config.filterProps.includes(prop)) return;
if (!declarations.has(prop)) declarations.set(prop, []);
declarations.get(prop).push(new Declaration({
property: prop,
value: element.style.getPropertyValue(prop),
important: element.style.getPropertyPriority(prop) === 'important',
selector: 'style=""',
source: 'Inline',
isInline: true,
specificity: { value: [Infinity, 0, 0], toString: () => 'β,0,0', compare: () => 1 },
order: globalOrder++
}));
});
// ============================================================================
// ANALYSIS
// ============================================================================
const results = {
element: element,
selector: target,
overriddenProps: 0,
totalDeclarations: 0,
properties: {}
};
declarations.forEach((decls, prop) => {
const sorted = decls.sort((a, b) => b.compareTo(a));
const winner = sorted[0];
const computedValue = computed.getPropertyValue(prop);
results.totalDeclarations += decls.length;
if (decls.length > 1) {
results.overriddenProps++;
}
if (!config.showAllProps && decls.length === 1) return;
results.properties[prop] = {
computed: computedValue,
winner: winner,
cascade: sorted,
overrideCount: decls.length - 1
};
});
// ============================================================================
// MARKDOWN GENERATION
// ============================================================================
function generateMarkdown() {
let md = '# CSS Cascade Report\n\n';
md += '**Element:** `' + target + '`\n\n';
md += '**Stats:**\n';
md += '- Properties with overrides: ' + results.overriddenProps + '\n';
md += '- Total declarations: ' + results.totalDeclarations + '\n\n';
md += '---\n\n';
Object.entries(results.properties).forEach(([prop, data]) => {
const { computed, cascade, overrideCount } = data;
md += '## `' + prop + '`\n\n';
md += '**Computed value:** `' + computed + '`\n\n';
if (overrideCount > 0) {
md += '**Override count:** ' + overrideCount + '\n\n';
}
md += '| Status | Value | Selector | Specificity | Source |\n';
md += '|--------|-------|----------|-------------|--------|\n';
cascade.forEach((decl, index) => {
const isWinner = index === 0;
const status = isWinner ? 'β
APPLIED' : 'β OVERRIDDEN';
const value = '`' + decl.value + (decl.important ? ' !important' : '') + '`';
const selector = '`' + decl.selector + '`';
const specificity = '`' + decl.specificity.toString() + '`';
const source = decl.source.startsWith('http')
? '[Link](' + decl.source + ')'
: '`' + decl.source + '`';
md += '| ' + status + ' | ' + value + ' | ' + selector + ' | ' + specificity + ' | ' + source + ' |\n';
});
md += '\n';
});
return md;
}
// ============================================================================
// COPY TO CLIPBOARD (with fallback)
// ============================================================================
function copyToClipboard(text) {
// Modern Clipboard API (requires user interaction + focus)
if (navigator.clipboard && window.isSecureContext) {
return navigator.clipboard.writeText(text)
.then(() => {
console.log('π Markdown report copied to clipboard!');
return true;
})
.catch(() => {
return fallbackCopy(text);
});
} else {
return fallbackCopy(text);
}
}
function fallbackCopy(text) {
// Fallback: create temporary textarea
const textarea = document.createElement('textarea');
textarea.value = text;
textarea.style.position = 'fixed';
textarea.style.left = '-9999px';
textarea.style.top = '-9999px';
document.body.appendChild(textarea);
try {
textarea.focus();
textarea.select();
const successful = document.execCommand('copy');
document.body.removeChild(textarea);
if (successful) {
console.log('π Markdown report copied to clipboard (fallback method)!');
return Promise.resolve(true);
} else {
throw new Error('execCommand failed');
}
} catch (err) {
document.body.removeChild(textarea);
console.warn('β οΈ Could not copy to clipboard. Copy manually from the log below:');
console.log('\n' + text + '\n');
return Promise.resolve(false);
}
}
// ============================================================================
// CONSOLE OUTPUT
// ============================================================================
console.group('π― CSS Cascade for ' + target);
console.log('Element:', element);
console.log('Stats:', {
'Properties with overrides': results.overriddenProps,
'Total declarations': results.totalDeclarations
});
Object.entries(results.properties).forEach(([prop, data]) => {
const { computed, cascade, overrideCount } = data;
if (overrideCount === 0 && !config.showAllProps) return;
console.group(
'%c' + prop + '%c: ' + computed + ' %c(' + overrideCount + ' override' + (overrideCount === 1 ? '' : 's') + ')',
'font-weight:bold;color:#0066cc',
'color:inherit',
'color:#666;font-size:0.9em'
);
cascade.forEach((decl, index) => {
const isWinner = index === 0;
const icon = isWinner ? 'β
' : 'β';
const label = isWinner ? 'APPLIED' : 'OVERRIDDEN';
const logData = {
value: decl.value + (decl.important ? ' !important' : ''),
selector: decl.selector,
specificity: decl.specificity.toString()
};
if (config.verbose) {
logData.source = decl.source;
logData.order = decl.order;
}
console.log(icon + ' ' + label, logData);
});
console.groupEnd();
});
console.groupEnd();
// ============================================================================
// MARKDOWN OUTPUT & CLIPBOARD
// ============================================================================
if (config.outputMarkdown) {
const markdown = generateMarkdown();
results.markdown = markdown;
if (config.autoCopy) {
copyToClipboard(markdown);
}
// Provide manual copy method
results.copy = function() {
return copyToClipboard(this.markdown);
};
}
return results;
})();