-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathscript.js
More file actions
248 lines (248 loc) · 10.1 KB
/
Copy pathscript.js
File metadata and controls
248 lines (248 loc) · 10.1 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
"use strict";
const STORAGE_KEY = "designlens_audits";
let audits = JSON.parse(localStorage.getItem(STORAGE_KEY)) || [];
const uploadInput = document.getElementById("designUpload");
const previewImage = document.getElementById("previewImage");
const analyzeBtn = document.querySelector(".analyze-btn");
const historyContainer = document.querySelector(".history-list");
const colorPalette = document.getElementById("colorPalette");
uploadInput.addEventListener("change", event => {
const file = event.target.files[0];
if (!file) return;
if (!file.type.startsWith("image/")) {
alert("Please select a valid image.");
uploadInput.value = "";
return;
}
const reader = new FileReader();
reader.onload = e => {
previewImage.src = e.target.result;
previewImage.style.display = "block";
};
reader.readAsDataURL(file);
});
analyzeBtn.addEventListener("click", () => {
if (!previewImage.src) {
alert("Please upload a design first.");
return;
}
if (!previewImage.complete || !previewImage.naturalWidth) {
alert("Please wait for the image to finish loading.");
return;
}
startAnalysis();
});
function startAnalysis() {
analyzeBtn.innerHTML = "Analyzing Design...";
analyzeBtn.disabled = true;
const steps = ["Checking layout...", "Analyzing colors...", "Reviewing typography...", "Testing accessibility...", "Generating report..."];
let index = 0;
const loader = setInterval(() => {
analyzeBtn.innerHTML = steps[index];
index++;
if (index >= steps.length) {
clearInterval(loader);
setTimeout(() => finishAnalysis(), 500);
}
}, 600);
}
async function finishAnalysis() {
try {
const extractedColors = extractColorsFromImage(previewImage);
const score = randomNumber(75, 96);
const report = {
id: Date.now(),
title: generateTitle(),
score,
hierarchy: randomNumber(80, 95),
spacing: randomNumber(70, 90),
typography: randomNumber(75, 95),
accessibility: randomNumber(65, 90),
issues: generateIssues(),
colors: extractedColors,
created: new Date().toLocaleDateString()
};
saveAudit(report);
updateReport(report);
analyzeBtn.innerHTML = "Analyze Design";
analyzeBtn.disabled = false;
alert("Design analysis completed!");
} catch (error) {
console.error(error);
analyzeBtn.innerHTML = "Analyze Design";
analyzeBtn.disabled = false;
alert("Unable to analyze this image.");
}
}
function extractColorsFromImage(image) {
const canvas = document.createElement("canvas");
const ctx = canvas.getContext("2d", { willReadFrequently: true });
const maxSize = 140;
const ratio = Math.min(maxSize / image.naturalWidth, maxSize / image.naturalHeight, 1);
canvas.width = Math.max(1, Math.round(image.naturalWidth * ratio));
canvas.height = Math.max(1, Math.round(image.naturalHeight * ratio));
ctx.drawImage(image, 0, 0, canvas.width, canvas.height);
const data = ctx.getImageData(0, 0, canvas.width, canvas.height).data;
const buckets = new Map();
const edgeBuckets = new Map();
for (let y = 0; y < canvas.height; y++) {
for (let x = 0; x < canvas.width; x++) {
const i = (y * canvas.width + x) * 4;
const alpha = data[i + 3];
if (alpha < 180) continue;
const r = quantize(data[i]);
const g = quantize(data[i + 1]);
const b = quantize(data[i + 2]);
const key = `${r},${g},${b}`;
buckets.set(key, (buckets.get(key) || 0) + 1);
const edge = x < 4 || y < 4 || x >= canvas.width - 4 || y >= canvas.height - 4;
if (edge) edgeBuckets.set(key, (edgeBuckets.get(key) || 0) + 1);
}
}
const sorted = [...buckets.entries()].sort((a, b) => b[1] - a[1]).map(([key, count]) => ({ rgb: key.split(",").map(Number), count }));
const edgeSorted = [...edgeBuckets.entries()].sort((a, b) => b[1] - a[1]).map(([key, count]) => ({ rgb: key.split(",").map(Number), count }));
const fallback = [17, 24, 39];
const background = edgeSorted[0]?.rgb || sorted[0]?.rgb || [255, 255, 255];
const primary = findDistinctColor(sorted, background, 55, false) || sorted[0]?.rgb || fallback;
const secondary = findDistinctColor(sorted, primary, 70, false, [background]) || findDistinctColor(sorted, primary, 45, false) || [71, 85, 105];
const accent = findAccentColor(sorted, [background, primary, secondary]) || findDistinctColor(sorted, primary, 90, true, [background, secondary]) || [37, 99, 235];
return [
{ name: "Primary", value: rgbToHex(primary), usage: "Main brand or dominant interface color" },
{ name: "Secondary", value: rgbToHex(secondary), usage: "Supporting sections and secondary elements" },
{ name: "Accent", value: rgbToHex(accent), usage: "Buttons, links and important highlights" },
{ name: "Background", value: rgbToHex(background), usage: "Main page or surface background" }
];
}
function quantize(value) {
return Math.min(255, Math.round(value / 32) * 32);
}
function findDistinctColor(colors, reference, minDistance, preferSaturated = false, excluded = []) {
for (const item of colors) {
const rgb = item.rgb;
if (colorDistance(rgb, reference) < minDistance) continue;
if (excluded.some(color => colorDistance(rgb, color) < 45)) continue;
if (preferSaturated && getSaturation(rgb) < 0.25) continue;
return rgb;
}
return null;
}
function findAccentColor(colors, excluded = []) {
let best = null;
let bestScore = -Infinity;
for (const item of colors.slice(0, 80)) {
const rgb = item.rgb;
if (excluded.some(color => colorDistance(rgb, color) < 55)) continue;
const saturation = getSaturation(rgb);
const lightness = getLightness(rgb);
if (saturation < 0.3 || lightness < 0.12 || lightness > 0.9) continue;
const score = saturation * 100 + Math.log(item.count + 1) * 6;
if (score > bestScore) {
bestScore = score;
best = rgb;
}
}
return best;
}
function colorDistance(a, b) {
return Math.sqrt((a[0] - b[0]) ** 2 + (a[1] - b[1]) ** 2 + (a[2] - b[2]) ** 2);
}
function getSaturation(rgb) {
const r = rgb[0] / 255;
const g = rgb[1] / 255;
const b = rgb[2] / 255;
const max = Math.max(r, g, b);
const min = Math.min(r, g, b);
if (max === min) return 0;
const l = (max + min) / 2;
return (max - min) / (1 - Math.abs(2 * l - 1));
}
function getLightness(rgb) {
const max = Math.max(...rgb) / 255;
const min = Math.min(...rgb) / 255;
return (max + min) / 2;
}
function rgbToHex(rgb) {
return "#" + rgb.map(value => Math.max(0, Math.min(255, value)).toString(16).padStart(2, "0")).join("").toUpperCase();
}
function randomNumber(min, max) {
return Math.floor(Math.random() * (max - min + 1)) + min;
}
function generateTitle() {
const names = ["Landing Page Review", "Dashboard UI Audit", "Mobile App Analysis", "E-commerce Design Review", "SaaS Interface Audit"];
return names[Math.floor(Math.random() * names.length)];
}
function generateIssues() {
const issues = [
{ title: "Weak CTA Visibility", level: "High", text: "Improve button contrast and visual hierarchy." },
{ title: "Spacing Inconsistency", level: "Medium", text: "Increase whitespace between sections." },
{ title: "Text Density", level: "Medium", text: "Reduce long paragraphs for better readability." },
{ title: "Low Color Contrast", level: "High", text: "Improve accessibility contrast ratio." }
];
return issues.sort(() => 0.5 - Math.random()).slice(0, 2);
}
function saveAudit(report) {
audits.unshift(report);
localStorage.setItem(STORAGE_KEY, JSON.stringify(audits));
}
function updateReport(report) {
const score = document.querySelector(".score-circle strong");
const message = document.querySelector(".score-card h3");
const metrics = document.querySelectorAll(".metric-card strong");
const bars = document.querySelectorAll(".metric-card .progress span");
if (score) score.innerText = report.score;
if (message) message.innerText = getScoreMessage(report.score);
const values = [report.hierarchy, report.spacing, report.typography, report.accessibility];
metrics.forEach((metric, index) => {
if (values[index] !== undefined) metric.innerText = values[index] + "%";
});
bars.forEach((bar, index) => {
if (values[index] !== undefined) bar.style.width = values[index] + "%";
});
updateColors(report.colors);
updateHistory();
}
function updateColors(colors) {
if (!colorPalette) return;
colorPalette.innerHTML = colors.map(color => `
<div class="color-item">
<span class="color-swatch" style="background:${color.value}"></span>
<div class="color-meta">
<strong>${color.name}</strong>
<code>${color.value}</code>
<small>${color.usage}</small>
</div>
</div>`).join("");
}
function getScoreMessage(score) {
if (score >= 90) return "Outstanding Design Quality";
if (score >= 80) return "Excellent Design Quality";
if (score >= 70) return "Good Design With Improvements";
return "Needs Design Improvements";
}
function updateHistory() {
if (!historyContainer) return;
historyContainer.innerHTML = "";
audits.slice(0, 5).forEach(audit => {
const item = document.createElement("div");
item.className = "history-item";
item.innerHTML = `<strong>${audit.title}</strong><span>Score ${audit.score}</span>`;
historyContainer.appendChild(item);
});
}
function exportReport() {
const data = JSON.stringify(audits, null, 2);
const blob = new Blob([data], { type: "application/json" });
const url = URL.createObjectURL(blob);
const link = document.createElement("a");
link.href = url;
link.download = "designlens-report.json";
link.click();
URL.revokeObjectURL(url);
}
document.addEventListener("keydown", e => {
if (e.ctrlKey && e.key.toLowerCase() === "e") {
e.preventDefault();
exportReport();
}
});
updateHistory();