-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathcontent.js
More file actions
673 lines (575 loc) · 19 KB
/
Copy pathcontent.js
File metadata and controls
673 lines (575 loc) · 19 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
(function installUiSkillAnalyzer() {
if (window.__uiSkillAnalyzerInstalled) {
return;
}
window.__uiSkillAnalyzerInstalled = true;
chrome.runtime.onMessage.addListener((message, _sender, sendResponse) => {
if (!message || message.type !== "ANALYZE_UI_STYLE") {
return;
}
try {
const result = analyzeCurrentPage();
sendResponse({
ok: true,
data: result
});
} catch (error) {
sendResponse({
ok: false,
error: buildErrorPayload("脚本执行失败,无法完成页面分析。", [
"请刷新当前页面后重试。",
"如果页面刚刚跳转,请等待页面完全加载后再试。",
"若页面来自浏览器内置页面或扩展商店,这类页面本身不支持分析。"
], error)
});
}
return true;
});
function analyzeCurrentPage() {
ensurePageIsSupported();
const elements = collectRepresentativeElements();
if (!elements.length) {
throw new Error("页面中没有可分析的可见元素");
}
const tokenStats = buildTokenStats(elements);
const componentPatterns = detectComponentPatterns();
const layoutRules = inferLayoutRules(elements);
const summary = buildSummary(tokenStats, componentPatterns, layoutRules);
const representativeColors = buildRepresentativeColors(tokenStats.colors, 6);
const accentColors = buildAccentColors(tokenStats.colors, 4);
return {
meta: {
title: document.title || "未命名页面",
url: location.href,
host: location.host,
sampledElementCount: elements.length,
analyzedAt: new Date().toISOString()
},
summary,
tokens: {
colors: representativeColors.map(([value, count]) => ({
value,
count
})),
accentColors: accentColors.map(([value, count]) => ({
value,
count
})),
iconColors: topEntries(tokenStats.iconColors, 4).map(([value, count]) => ({
value,
count
})),
textColors: topEntries(tokenStats.textColors, 4).map(([value, count]) => ({
value,
count
})),
backgrounds: topEntries(tokenStats.backgrounds, 4).map(([value, count]) => ({
value,
count
})),
fontFamilies: topEntries(tokenStats.fontFamilies, 4).map(([value, count]) => ({
value,
count
})),
fontSizes: topEntries(tokenStats.fontSizes, 5).map(([value, count]) => ({
value,
count
})),
spacing: topEntries(tokenStats.spacing, 6).map(([value, count]) => ({
value,
count
})),
radii: topEntries(tokenStats.radii, 5).map(([value, count]) => ({
value,
count
})),
shadows: topEntries(tokenStats.shadows, 4).map(([value, count]) => ({
value,
count
}))
},
layoutRules,
componentPatterns
};
}
function ensurePageIsSupported() {
const unsupportedPrefixes = ["chrome:", "edge:", "about:", "moz-extension:", "chrome-extension:"];
const href = location.href;
if (unsupportedPrefixes.some((prefix) => href.startsWith(prefix))) {
throw new Error("当前页面属于浏览器限制页面");
}
if (!document.body) {
throw new Error("页面主体尚未渲染完成");
}
}
function collectRepresentativeElements() {
const selector = [
"main",
"header",
"footer",
"section",
"article",
"nav",
"aside",
"button",
"a",
"input",
"textarea",
"select",
"label",
"div",
"span",
"li",
"p",
"h1",
"h2",
"h3",
"h4"
].join(",");
const nodes = Array.from(document.querySelectorAll(selector));
return nodes
.filter(isUsefulVisibleElement)
.slice(0, 280);
}
function isUsefulVisibleElement(element) {
if (!(element instanceof HTMLElement)) {
return false;
}
const tag = element.tagName.toLowerCase();
if (["script", "style", "noscript", "meta", "link", "svg", "path"].includes(tag)) {
return false;
}
if (element.closest("script, style, noscript")) {
return false;
}
const rect = element.getBoundingClientRect();
if (rect.width < 8 || rect.height < 8) {
return false;
}
const style = getComputedStyle(element);
if (
style.display === "none" ||
style.visibility === "hidden" ||
Number(style.opacity || "1") < 0.05
) {
return false;
}
if (tag === "div" && !element.textContent?.trim() && style.backgroundColor === "rgba(0, 0, 0, 0)") {
return false;
}
return true;
}
function buildTokenStats(elements) {
const stats = {
colors: new Map(),
iconColors: new Map(),
textColors: new Map(),
backgrounds: new Map(),
fontFamilies: new Map(),
fontSizes: new Map(),
spacing: new Map(),
radii: new Map(),
shadows: new Map()
};
elements.forEach((element) => {
const style = getComputedStyle(element);
addColor(stats.colors, normalizeColor(style.color));
addColor(stats.colors, normalizeColor(style.backgroundColor));
addColor(stats.colors, normalizeColor(style.borderTopColor));
addColor(stats.textColors, normalizeColor(style.color));
addColor(stats.backgrounds, normalizeColor(style.backgroundColor));
addStat(stats.fontFamilies, normalizeFontFamily(style.fontFamily));
addStat(stats.fontSizes, normalizePx(style.fontSize));
[
style.paddingTop,
style.paddingLeft,
style.marginTop,
style.marginBottom,
style.gap,
style.rowGap,
style.columnGap
]
.map(normalizePx)
.forEach((value) => addStat(stats.spacing, value));
[
style.borderRadius,
style.borderTopLeftRadius,
style.borderTopRightRadius
]
.map(normalizePx)
.forEach((value) => addStat(stats.radii, value));
addStat(stats.shadows, normalizeShadow(style.boxShadow));
});
collectAndMergeIconColors(stats);
return stats;
}
function detectComponentPatterns() {
const rules = [];
pushComponentRule(rules, "按钮", querySamples("button, [role='button'], input[type='button'], input[type='submit'], a[class*='btn']"));
pushComponentRule(rules, "输入框", querySamples("input:not([type='hidden']):not([type='submit']), textarea, select"));
pushComponentRule(rules, "卡片", querySamples("article, section, div[class*='card'], div[class*='panel'], li[class*='card']"));
pushComponentRule(rules, "导航", querySamples("nav, header, [role='navigation'], aside"));
pushComponentRule(rules, "标签", querySamples("[class*='tag'], [class*='chip'], [class*='badge'], [data-tag], [data-chip]"));
pushComponentRule(rules, "弹窗", querySamples("dialog, [role='dialog'], [class*='modal'], [class*='dialog'], [aria-modal='true']"));
return rules.slice(0, 6);
}
function pushComponentRule(target, name, elements) {
const visible = elements.filter(isUsefulVisibleElement).slice(0, 3);
if (!visible.length) {
return;
}
const sampleStyles = visible.map(describeElementStyle);
const descriptor = summarizeComponentStyle(sampleStyles);
target.push({
name,
sampleCount: visible.length,
description: descriptor,
samples: sampleStyles
});
}
function querySamples(selector) {
try {
return Array.from(document.querySelectorAll(selector));
} catch (_error) {
return [];
}
}
function describeElementStyle(element) {
const style = getComputedStyle(element);
return {
tag: element.tagName.toLowerCase(),
text: normalizeText(element.innerText || element.textContent || "").slice(0, 60),
background: normalizeColor(style.backgroundColor),
color: normalizeColor(style.color),
border: normalizeBorder(style),
radius: normalizePx(style.borderRadius),
shadow: normalizeShadow(style.boxShadow),
padding: compactValues([
normalizePx(style.paddingTop),
normalizePx(style.paddingRight),
normalizePx(style.paddingBottom),
normalizePx(style.paddingLeft)
]),
font: normalizeFontFamily(style.fontFamily),
fontSize: normalizePx(style.fontSize)
};
}
function summarizeComponentStyle(samples) {
const first = samples[0];
return [
`常见背景 ${first.background || "透明"}`,
`文字 ${first.color || "继承页面主色"}`,
`圆角 ${first.radius || "0px"}`,
`内边距 ${first.padding || "未识别"}`,
`阴影 ${first.shadow || "无"}`,
`边框 ${first.border || "无"}`
].join(",");
}
function inferLayoutRules(elements) {
const displays = new Map();
let wideContainers = 0;
let centeredBlocks = 0;
elements.forEach((element) => {
const style = getComputedStyle(element);
addStat(displays, style.display);
const rect = element.getBoundingClientRect();
const widthRatio = rect.width / Math.max(window.innerWidth, 1);
if (widthRatio > 0.55 && rect.width > 260) {
wideContainers += 1;
}
if (isCenteredContentBlock(element, style, rect)) {
centeredBlocks += 1;
}
});
const displayLeaders = topEntries(displays, 4).map(([value]) => value);
return {
displayTrends: displayLeaders,
hasStrongGrid: displayLeaders.includes("grid"),
hasStrongFlex: displayLeaders.includes("flex"),
wideContainerBias: wideContainers > Math.max(6, elements.length * 0.08),
centeredContentBias: centeredBlocks > Math.max(3, elements.length * 0.04),
notes: buildLayoutNotes(displayLeaders, wideContainers, centeredBlocks, elements.length)
};
}
function isCenteredContentBlock(element, style, rect) {
if (!(element instanceof HTMLElement) || !style || !rect) {
return false;
}
const viewportWidth = Math.max(window.innerWidth, 1);
const marginLeftValue = style.marginLeft || "";
const marginRightValue = style.marginRight || "";
const marginLeft = parseFloat(marginLeftValue || "0");
const marginRight = parseFloat(marginRightValue || "0");
const hasAutoMargins = isAutoMargin(marginLeftValue) && isAutoMargin(marginRightValue);
const hasExplicitSideMargins = marginLeft > 0 && marginRight > 0;
const hasHorizontalWhitespace = rect.width < viewportWidth - 24;
const centerOffset = Math.abs(rect.left + rect.width / 2 - viewportWidth / 2);
const isVisuallyCentered = centerOffset <= Math.max(24, viewportWidth * 0.04);
const isContainerLike = rect.width > 180 && rect.height > 24;
const styleAllowsCentering = ["block", "flex", "grid", "table"].includes(style.display);
return (
styleAllowsCentering &&
isContainerLike &&
hasHorizontalWhitespace &&
isVisuallyCentered &&
(hasAutoMargins || hasExplicitSideMargins)
);
}
function isAutoMargin(value) {
return typeof value === "string" && value.trim() === "auto";
}
function buildLayoutNotes(displayLeaders, wideContainers, centeredBlocks, totalCount) {
const notes = [];
if (displayLeaders.includes("flex")) {
notes.push("页面中较多区域使用 Flex 做横向排布或对齐。");
}
if (displayLeaders.includes("grid")) {
notes.push("页面存在 Grid 结构,适合复用多列卡片或面板布局。");
}
if (wideContainers > Math.max(6, totalCount * 0.08)) {
notes.push("大容器占比较高,整体偏内容区块化布局。");
}
if (centeredBlocks > Math.max(3, totalCount * 0.04)) {
notes.push("页面常用左右留白形成居中内容区域。");
}
if (!notes.length) {
notes.push("页面布局较常规,未观察到非常强的单一布局模式。");
}
return notes;
}
function buildSummary(tokenStats, componentPatterns, layoutRules) {
const mainColor = topEntries(tokenStats.backgrounds, 2)
.map(([value]) => value)
.find(Boolean);
const textColor = topEntries(tokenStats.textColors, 2)
.map(([value]) => value)
.find(Boolean);
const font = topEntries(tokenStats.fontFamilies, 1)
.map(([value]) => value)[0];
const radius = topEntries(tokenStats.radii, 1)
.map(([value]) => value)[0];
return [
`页面整体以 ${mainColor || "浅色/透明"} 背景体系为主`,
textColor ? `常见文字颜色为 ${textColor}` : "文字颜色对比较稳定",
font ? `主要字体偏向 ${font}` : "字体使用较统一",
radius ? `圆角常见于 ${radius}` : "圆角使用较克制",
componentPatterns.length ? `识别到 ${componentPatterns.length} 类典型组件模式` : "组件模式不算集中",
layoutRules.notes[0]
].join(",");
}
function buildErrorPayload(message, suggestions, error) {
return {
message,
details: error instanceof Error ? error.message : String(error || ""),
suggestions
};
}
function addColor(map, value) {
if (!value || value === "transparent") {
return;
}
addStat(map, value);
}
function addWeightedColor(map, value, weight) {
if (!value || value === "transparent") {
return;
}
map.set(value, (map.get(value) || 0) + weight);
}
function collectAndMergeIconColors(stats) {
const iconNodes = Array.from(document.querySelectorAll("svg, svg *"));
iconNodes.forEach((node) => {
if (!isUsefulIconNode(node)) {
return;
}
const style = getComputedStyle(node);
const colors = [
normalizeColor(style.color),
normalizeColor(style.fill),
normalizeColor(style.stroke)
];
colors.forEach((color) => {
if (!color) {
return;
}
addColor(stats.iconColors, color);
addWeightedColor(stats.colors, color, 3);
});
});
}
function isUsefulIconNode(node) {
if (!(node instanceof SVGElement)) {
return false;
}
const rect = typeof node.getBoundingClientRect === "function" ? node.getBoundingClientRect() : null;
if (!rect || rect.width < 6 || rect.height < 6) {
return false;
}
const style = getComputedStyle(node);
if (
style.display === "none" ||
style.visibility === "hidden" ||
Number(style.opacity || "1") < 0.05
) {
return false;
}
return true;
}
function addStat(map, value) {
if (!value || value === "0px" || value === "none") {
return;
}
map.set(value, (map.get(value) || 0) + 1);
}
function topEntries(map, limit) {
return Array.from(map.entries())
.sort((a, b) => b[1] - a[1])
.slice(0, limit);
}
function buildRepresentativeColors(colorMap, limit) {
const entries = mapColorEntries(colorMap);
const result = [];
pushDistinctColorEntries(result, entries.filter((entry) => !entry.isNeutral).sort(compareAccentEntries), Math.min(2, limit));
pushDistinctColorEntries(result, entries.sort(compareRepresentativeEntries), limit);
return result
.slice(0, limit)
.map((entry) => [entry.value, entry.count]);
}
function buildAccentColors(colorMap, limit) {
const result = [];
const entries = mapColorEntries(colorMap)
.filter((entry) => !entry.isNeutral && entry.lightness > 0.12 && entry.lightness < 0.88)
.sort(compareAccentEntries);
pushDistinctColorEntries(result, entries, limit);
return result.map((entry) => [entry.value, entry.count]);
}
function mapColorEntries(colorMap) {
return Array.from(colorMap.entries())
.map(([value, count]) => ({
value,
count,
...getColorMetrics(value)
}))
.filter((entry) => Boolean(entry.value));
}
function compareRepresentativeEntries(a, b) {
const scoreA = a.count + a.saturation * 12 + (a.isNeutral ? 0 : 3);
const scoreB = b.count + b.saturation * 12 + (b.isNeutral ? 0 : 3);
return scoreB - scoreA;
}
function compareAccentEntries(a, b) {
const scoreA = a.count * 1.5 + a.saturation * 100;
const scoreB = b.count * 1.5 + b.saturation * 100;
return scoreB - scoreA;
}
function pushDistinctColorEntries(target, entries, limit) {
entries.forEach((entry) => {
if (target.length >= limit) {
return;
}
const alreadyIncluded = target.some((existing) => areColorsSimilar(existing.value, entry.value));
if (!alreadyIncluded) {
target.push(entry);
}
});
}
function getColorMetrics(color) {
const rgb = hexToRgb(color);
if (!rgb) {
return {
saturation: 0,
lightness: 0,
isNeutral: false
};
}
const [r, g, b] = rgb;
const max = Math.max(r, g, b);
const min = Math.min(r, g, b);
const delta = max - min;
const lightness = (max + min) / 510;
const saturation = max === min ? 0 : delta / (255 - Math.abs(max + min - 255));
return {
saturation,
lightness,
isNeutral: saturation < 0.12 || delta < 18
};
}
function hexToRgb(color) {
if (!/^#[\da-f]{6}$/i.test(color)) {
return null;
}
return [
Number.parseInt(color.slice(1, 3), 16),
Number.parseInt(color.slice(3, 5), 16),
Number.parseInt(color.slice(5, 7), 16)
];
}
function areColorsSimilar(first, second) {
const firstRgb = hexToRgb(first);
const secondRgb = hexToRgb(second);
if (!firstRgb || !secondRgb) {
return first === second;
}
const distance = Math.sqrt(
(firstRgb[0] - secondRgb[0]) ** 2 +
(firstRgb[1] - secondRgb[1]) ** 2 +
(firstRgb[2] - secondRgb[2]) ** 2
);
return distance < 30;
}
function normalizeColor(value) {
if (!value || value === "rgba(0, 0, 0, 0)" || value === "transparent") {
return "";
}
const matches = value.match(/\d+(\.\d+)?/g);
if (!matches) {
return value.trim();
}
const numbers = matches.slice(0, 3).map((part) => Number(part));
if (numbers.length < 3) {
return value.trim();
}
return `#${numbers.map((n) => n.toString(16).padStart(2, "0")).join("")}`;
}
function normalizePx(value) {
if (!value) {
return "";
}
const numeric = parseFloat(value);
if (!Number.isFinite(numeric) || numeric <= 0) {
return "";
}
return `${Math.round(numeric)}px`;
}
function normalizeFontFamily(value) {
if (!value) {
return "";
}
return value
.split(",")
.map((part) => part.trim().replace(/^["']|["']$/g, ""))
.filter(Boolean)
.slice(0, 2)
.join(", ");
}
function normalizeShadow(value) {
if (!value || value === "none") {
return "";
}
return value.replace(/\s+/g, " ").trim();
}
function normalizeBorder(style) {
if (!style.borderTopWidth || style.borderTopStyle === "none") {
return "";
}
return [normalizePx(style.borderTopWidth), style.borderTopStyle, normalizeColor(style.borderTopColor)]
.filter(Boolean)
.join(" ");
}
function compactValues(values) {
return values.filter(Boolean).join(" / ");
}
function normalizeText(value) {
return value.replace(/\s+/g, " ").trim();
}
})();