-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathpopup.js
More file actions
525 lines (461 loc) · 16.2 KB
/
Copy pathpopup.js
File metadata and controls
525 lines (461 loc) · 16.2 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
const unsupportedPrefixes = ["chrome://", "edge://", "about:", "chrome-extension://", "moz-extension://"];
const elements = {
statusCard: document.getElementById("statusCard"),
statusBadge: document.getElementById("statusBadge"),
statusTitle: document.getElementById("statusTitle"),
statusMessage: document.getElementById("statusMessage"),
retryButton: document.getElementById("retryButton"),
summarySection: document.getElementById("summarySection"),
summaryText: document.getElementById("summaryText"),
tokenGrid: document.getElementById("tokenGrid"),
componentsSection: document.getElementById("componentsSection"),
componentsList: document.getElementById("componentsList"),
skillSection: document.getElementById("skillSection"),
skillOutput: document.getElementById("skillOutput"),
errorHelpSection: document.getElementById("errorHelpSection"),
suggestionList: document.getElementById("suggestionList"),
copyButton: document.getElementById("copyButton"),
exportMdButton: document.getElementById("exportMdButton"),
exportJsonButton: document.getElementById("exportJsonButton"),
pageHost: document.getElementById("pageHost")
};
let latestPayload = null;
elements.retryButton.addEventListener("click", () => {
analyzeActiveTab();
});
elements.copyButton.addEventListener("click", async () => {
if (!latestPayload?.skillText) {
return;
}
try {
await navigator.clipboard.writeText(latestPayload.skillText);
setStatus("success", "已复制 Skill", "Skill Markdown 已复制到剪贴板,可以直接粘贴复用。");
} catch (_error) {
setStatus("error", "复制失败", "浏览器未允许写入剪贴板,请手动复制下方 Markdown 内容。", [
"手动选中下方 Skill Markdown 并复制。",
"检查浏览器是否禁用了剪贴板权限。"
]);
}
});
elements.exportMdButton.addEventListener("click", () => {
if (!latestPayload?.skillText) {
return;
}
downloadFile(`${buildSkillFileBaseName(latestPayload.analysis)}.md`, latestPayload.skillText, "text/markdown");
});
elements.exportJsonButton.addEventListener("click", () => {
if (!latestPayload?.structuredSkill) {
return;
}
downloadFile(
`${buildSkillFileBaseName(latestPayload.analysis)}.json`,
JSON.stringify(latestPayload.structuredSkill, null, 2),
"application/json"
);
});
document.addEventListener("DOMContentLoaded", () => {
analyzeActiveTab();
});
async function analyzeActiveTab() {
hideResults();
setButtonsDisabled(true);
setStatus("loading", "分析中", "正在扫描当前页面的颜色、字体、间距、组件模式和布局规则...");
try {
const [tab] = await chrome.tabs.query({
active: true,
currentWindow: true
});
if (!tab?.id || !tab.url) {
throw createUserError("未找到当前激活标签页。", [
"请先切换到一个普通网页标签页。",
"确认当前窗口不是浏览器设置页或扩展管理页。"
]);
}
ensureTabIsSupported(tab.url);
await chrome.scripting.executeScript({
target: {
tabId: tab.id
},
files: ["content.js"]
});
const response = await chrome.tabs.sendMessage(tab.id, {
type: "ANALYZE_UI_STYLE"
});
if (!response?.ok) {
throw normalizeRemoteError(response?.error);
}
const analysis = response.data;
const structuredSkill = buildStructuredSkill(analysis);
const skillText = buildSkillText(structuredSkill);
latestPayload = {
analysis,
structuredSkill,
skillText
};
renderSuccess({
analysis,
structuredSkill,
skillText
});
} catch (error) {
latestPayload = null;
renderError(normalizeLocalError(error));
} finally {
setButtonsDisabled(false);
}
}
function renderSuccess(payload) {
const { analysis, structuredSkill, skillText } = payload;
elements.summarySection.classList.remove("hidden");
elements.componentsSection.classList.remove("hidden");
elements.skillSection.classList.remove("hidden");
elements.pageHost.textContent = analysis.meta.host || "当前页面";
elements.summaryText.textContent = analysis.summary;
elements.skillOutput.value = skillText;
renderTokens(analysis.tokens);
renderComponents(analysis.componentPatterns);
setStatus(
"success",
"分析完成",
`已分析 ${analysis.meta.sampledElementCount} 个代表性元素,并生成可复制导出的 Skill。`
);
if (structuredSkill.usageAdvice.length) {
showSuggestions(structuredSkill.usageAdvice);
} else {
hideSuggestions();
}
}
function renderError(error) {
hideResults();
setStatus("error", error.title, error.message, error.suggestions);
showSuggestions(error.suggestions);
}
function renderTokens(tokens) {
const entries = [
{
label: "主色/高频色",
value: formatTokenValues(tokens.colors, 3),
swatches: tokens.colors.slice(0, 3).map((item) => item.value)
},
{
label: "强调色",
value: formatTokenValues(tokens.accentColors || [], 3),
swatches: (tokens.accentColors || []).slice(0, 3).map((item) => item.value)
},
{
label: "图标色",
value: formatTokenValues(tokens.iconColors || [], 3),
swatches: (tokens.iconColors || []).slice(0, 3).map((item) => item.value)
},
{
label: "文字色",
value: formatTokenValues(tokens.textColors, 2),
swatches: tokens.textColors.slice(0, 2).map((item) => item.value)
},
{
label: "背景色",
value: formatTokenValues(tokens.backgrounds, 2),
swatches: tokens.backgrounds.slice(0, 2).map((item) => item.value)
},
{
label: "字体",
value: formatTokenValues(tokens.fontFamilies, 2)
},
{
label: "字号趋势",
value: formatTokenValues(tokens.fontSizes, 4)
},
{
label: "间距趋势",
value: formatTokenValues(tokens.spacing, 4)
},
{
label: "圆角趋势",
value: formatTokenValues(tokens.radii, 4)
},
{
label: "阴影趋势",
value: formatTokenValues(tokens.shadows, 2)
}
];
elements.tokenGrid.innerHTML = entries
.map((entry) => {
const swatches = entry.swatches?.length
? `<div class="swatch-row">${entry.swatches
.map((value) => `<span class="swatch" style="background:${escapeAttribute(value)}"></span>`)
.join("")}</div>`
: "";
return `
<article class="token-card">
<h3>${escapeHtml(entry.label)}</h3>
<p class="token-value">${escapeHtml(entry.value || "未识别")}</p>
${swatches}
</article>
`;
})
.join("");
}
function renderComponents(patterns) {
if (!patterns.length) {
elements.componentsList.innerHTML = '<article class="component-card"><h3>未识别明显组件</h3><p class="component-description">当前页面的组件风格较分散,建议结合 Skill 文本里的通用规则手动补充。</p></article>';
return;
}
elements.componentsList.innerHTML = patterns
.map((pattern) => {
return `
<article class="component-card">
<h3>${escapeHtml(pattern.name)}</h3>
<p class="component-description">${escapeHtml(pattern.description)}</p>
</article>
`;
})
.join("");
}
function buildStructuredSkill(analysis) {
const colors = analysis.tokens.colors.slice(0, 5).map((item) => item.value);
const accentColors = (analysis.tokens.accentColors || []).slice(0, 4).map((item) => item.value);
const iconColors = (analysis.tokens.iconColors || []).slice(0, 4).map((item) => item.value);
const fonts = analysis.tokens.fontFamilies.slice(0, 3).map((item) => item.value);
const fontSizes = analysis.tokens.fontSizes.slice(0, 5).map((item) => item.value);
const spacing = analysis.tokens.spacing.slice(0, 5).map((item) => item.value);
const radii = analysis.tokens.radii.slice(0, 5).map((item) => item.value);
const shadows = analysis.tokens.shadows.slice(0, 3).map((item) => item.value);
return {
name: `${analysis.meta.title} UI Style Skill`,
source: {
title: analysis.meta.title,
url: analysis.meta.url,
host: analysis.meta.host,
analyzedAt: analysis.meta.analyzedAt
},
styleOverview: analysis.summary,
designTokens: {
colors,
accentColors,
iconColors,
textColors: analysis.tokens.textColors.slice(0, 4).map((item) => item.value),
backgrounds: analysis.tokens.backgrounds.slice(0, 4).map((item) => item.value),
fontFamilies: fonts,
fontSizes,
spacing,
radii,
shadows
},
componentRules: analysis.componentPatterns.map((pattern) => ({
name: pattern.name,
rule: pattern.description
})),
layoutRules: analysis.layoutRules.notes,
usageAdvice: buildUsageAdvice(analysis)
};
}
function buildUsageAdvice(analysis) {
const advice = [];
const hasFlex = analysis.layoutRules.displayTrends.includes("flex");
const hasGrid = analysis.layoutRules.displayTrends.includes("grid");
const mainFont = analysis.tokens.fontFamilies[0]?.value;
const mainColor = analysis.tokens.accentColors?.[0]?.value || analysis.tokens.colors[0]?.value;
if (mainColor) {
advice.push(`优先把 ${mainColor} 作为品牌主色或高频强调色使用。`);
}
if (mainFont) {
advice.push(`正文与标题尽量统一使用 ${mainFont} 字体体系。`);
}
if (hasFlex) {
advice.push("布局上优先使用 Flex 完成横向对齐、工具栏和按钮组排列。");
}
if (hasGrid) {
advice.push("多卡片区域可优先考虑 Grid,保持列宽和间距的一致性。");
}
if (!analysis.componentPatterns.length) {
advice.push("组件样式分布较散,建议在生成代码前手动补充核心组件约束。");
}
advice.push("先复用高频字号、圆角和阴影,再按业务微调个别特殊模块。");
return advice.slice(0, 5);
}
function buildSkillText(skill) {
const lines = [
`# ${skill.name}`,
"",
"## 风格概述",
skill.styleOverview,
"",
"## 设计令牌",
`- 主色与高频色: ${joinOrFallback(skill.designTokens.colors)}`,
`- 强调色: ${joinOrFallback(skill.designTokens.accentColors)}`,
`- 图标色: ${joinOrFallback(skill.designTokens.iconColors)}`,
`- 文字色: ${joinOrFallback(skill.designTokens.textColors)}`,
`- 背景色: ${joinOrFallback(skill.designTokens.backgrounds)}`,
`- 字体族: ${joinOrFallback(skill.designTokens.fontFamilies)}`,
`- 字号层级: ${joinOrFallback(skill.designTokens.fontSizes)}`,
`- 间距趋势: ${joinOrFallback(skill.designTokens.spacing)}`,
`- 圆角趋势: ${joinOrFallback(skill.designTokens.radii)}`,
`- 阴影趋势: ${joinOrFallback(skill.designTokens.shadows)}`,
"",
"## 组件规则",
...(skill.componentRules.length
? skill.componentRules.map((item) => `- ${item.name}: ${item.rule}`)
: ["- 未识别到稳定的组件模式,建议手动补充按钮、表单和卡片规则。"]),
"",
"## 布局规则",
...(skill.layoutRules.length
? skill.layoutRules.map((item) => `- ${item}`)
: ["- 页面布局较常规,可优先采用内容居中和块状分区的方式。"]),
"",
"## 使用建议",
...skill.usageAdvice.map((item) => `- ${item}`),
"",
"## 来源",
`- 页面标题: ${skill.source.title}`,
`- 页面地址: ${skill.source.url}`,
`- 分析时间: ${new Date(skill.source.analyzedAt).toLocaleString("zh-CN")}`
];
return lines.join("\n");
}
function setStatus(state, title, message, suggestions = []) {
elements.statusCard.dataset.state = state;
elements.statusBadge.textContent = statusLabelFor(state);
elements.statusTitle.textContent = title;
elements.statusMessage.textContent = message;
if (state === "error") {
showSuggestions(suggestions);
}
}
function showSuggestions(items) {
if (!items?.length) {
hideSuggestions();
return;
}
elements.errorHelpSection.classList.remove("hidden");
elements.suggestionList.innerHTML = items.map((item) => `<li>${escapeHtml(item)}</li>`).join("");
}
function hideSuggestions() {
elements.errorHelpSection.classList.add("hidden");
elements.suggestionList.innerHTML = "";
}
function hideResults() {
elements.summarySection.classList.add("hidden");
elements.componentsSection.classList.add("hidden");
elements.skillSection.classList.add("hidden");
elements.tokenGrid.innerHTML = "";
elements.componentsList.innerHTML = "";
elements.skillOutput.value = "";
elements.pageHost.textContent = "";
hideSuggestions();
}
function setButtonsDisabled(disabled) {
elements.copyButton.disabled = disabled || !latestPayload?.skillText;
elements.exportMdButton.disabled = disabled || !latestPayload?.skillText;
elements.exportJsonButton.disabled = disabled || !latestPayload?.structuredSkill;
}
function statusLabelFor(state) {
if (state === "loading") {
return "分析中";
}
if (state === "success") {
return "已完成";
}
if (state === "error") {
return "失败";
}
return "待开始";
}
function formatTokenValues(list, limit) {
return list
.slice(0, limit)
.map((item) => item.value)
.join(" / ");
}
function joinOrFallback(values) {
return values?.length ? values.join(" / ") : "未识别";
}
function ensureTabIsSupported(url) {
if (unsupportedPrefixes.some((prefix) => url.startsWith(prefix))) {
throw createUserError("当前页面不支持分析。", [
"请切换到普通网站页面后再试。",
"浏览器设置页、扩展页、应用商店页属于受限页面,插件无法读取。"
]);
}
if (!/^https?:\/\//.test(url)) {
throw createUserError("当前页面不是普通网页。", [
"请打开一个 http 或 https 网站页面。",
"本地文件页、浏览器内置页和部分特殊协议页面都不支持分析。"
]);
}
}
function normalizeRemoteError(error) {
return createUserError(
error?.message || "分析过程失败。",
error?.suggestions || ["请刷新页面后重试。", "若页面限制脚本访问,请换一个普通网页。"]
);
}
function normalizeLocalError(error) {
if (error?.isUserFacing) {
return error;
}
const message = typeof error?.message === "string" ? error.message : "插件内部执行失败。";
if (message.includes("Receiving end does not exist")) {
return createUserError("当前页面脚本未成功连接。", [
"请刷新当前网页后重新打开插件。",
"如果刚安装或刚更新插件,原页面通常需要刷新一次。"
]);
}
if (message.includes("Cannot access") || message.includes("Cannot load")) {
return createUserError("当前页面没有访问权限。", [
"请确认当前页面是普通网站,而不是浏览器限制页。",
"必要时关闭 popup,刷新页面后重试。"
]);
}
return createUserError(message, [
"请刷新当前页面后重试。",
"如果问题持续存在,请换一个普通网页验证插件是否正常。"
]);
}
function createUserError(message, suggestions) {
return {
isUserFacing: true,
title: "分析失败",
message,
suggestions
};
}
function downloadFile(filename, content, mimeType) {
const blob = new Blob([content], { type: `${mimeType};charset=utf-8` });
const objectUrl = URL.createObjectURL(blob);
const link = document.createElement("a");
link.href = objectUrl;
link.download = filename;
link.style.display = "none";
document.body.appendChild(link);
link.click();
link.remove();
window.setTimeout(() => URL.revokeObjectURL(objectUrl), 1000);
}
function buildSkillFileBaseName(analysis) {
const rawHost = analysis?.meta?.host || extractHostFromUrl(analysis?.meta?.url) || "website";
return `${buildSafeFileName(rawHost)}_Design_Skill`;
}
function buildSafeFileName(name) {
return (name || "page")
.replace(/[\\/:*?"<>|]+/g, "-")
.replace(/\s+/g, "-")
.slice(0, 60);
}
function extractHostFromUrl(url) {
try {
return new URL(url).host;
} catch (_error) {
return "";
}
}
function escapeHtml(value) {
return String(value ?? "")
.replace(/&/g, "&")
.replace(/</g, "<")
.replace(/>/g, ">")
.replace(/"/g, """)
.replace(/'/g, "'");
}
function escapeAttribute(value) {
return String(value ?? "").replace(/"/g, """);
}