-
Notifications
You must be signed in to change notification settings - Fork 9
Expand file tree
/
Copy pathscript.js
More file actions
527 lines (450 loc) · 16.2 KB
/
script.js
File metadata and controls
527 lines (450 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
526
const colorInput = document.getElementById("colorInput");
const generateBtn = document.getElementById("generateBtn");
const colorPicker = document.getElementById("colorPicker");
const selectedColor = document.getElementById("selectedColor");
const modeToggle = document.getElementById("modeToggle");
const palettesContainer = document.getElementById("palettesContainer");
const snapshotModal = document.getElementById("snapshotModal");
const shareSnapshotModal = document.getElementById("shareSnapshotModal");
const closeModal = document.getElementsByClassName("close-modal")[0];
const usernameInput = document.getElementById("usernameInput");
const snapshotCanvas = document.getElementById("snapshotCanvas");
const downloadBtn = document.getElementById("downloadBtn");
const shareFacebook = document.getElementById("shareFacebook");
const shareTwitter = document.getElementById("shareTwitter");
const shareInstagram = document.getElementById("shareInstagram");
const sharePinterest = document.getElementById("sharePinterest");
const colorCodesDiv = document.getElementById('copy-palette-codes');
const copyButton = document.getElementById('copyToClipboard');
//delete button
const deleteBtn = document.getElementById('deleteBtn');
let palettes = [];
// Color extraction function
function extractColors(input) {
const colorRegex =
/(#(?:[0-9a-f]{3}){1,2}|rgb\(\s*\d+\s*,\s*\d+\s*,\s*\d+\s*\)|[a-z]+)/gi;
return input.match(colorRegex) || [];
}
// Color generation based on mood or theme
function generateColorsFromMood(mood) {
const moodColors = {
happy: ["#FFD700", "#FFA500", "#FF4500", "#FF6347", "#FF69B4"],
calm: ["#E0FFFF", "#B0E0E6", "#87CEEB", "#4682B4", "#6495ED"],
energetic: ["#FF0000", "#FF4500", "#FFA500", "#FFFF00", "#00FF00"],
elegant: ["#000000", "#FFFFFF", "#C0C0C0", "#808080", "#A9A9A9"],
natural: ["#228B22", "#32CD32", "#90EE90", "#8FBC8F", "#006400"],
};
return moodColors[mood.toLowerCase()] || generateRandomColors(5);
}
// Random color generation
function generateRandomColors(count) {
const colors = [];
for (let i = 0; i < count; i++) {
colors.push(
"#" +
Math.floor(Math.random() * 16777215)
.toString(16)
.padStart(6, "0")
);
}
return colors;
}
// Palette generation
function generatePalette() {
const input = colorInput.value.trim();
let colors;
if (input.startsWith("#") || input.startsWith("rgb")) {
colors = extractColors(input);
} else if (
["happy", "calm", "energetic", "elegant", "natural"].includes(
input.toLowerCase()
)
) {
colors = generateColorsFromMood(input);
} else {
colors = generateRandomColors(5);
}
const palette = {
id: Date.now(),
colors: colors,
};
palettes.unshift(palette);
renderPalettes();
colorCodesDiv.textContent = colors.join(', ');
}
// Render palettes
function renderPalettes() {
palettesContainer.innerHTML = "";
const savedPalettes = JSON.parse(localStorage.getItem("savedPalettes")) || [];
palettes.forEach((palette) => {
const paletteCard = document.createElement("div");
paletteCard.className = "palette-card glassmorphism";
paletteCard.setAttribute("data-aos", "fade-up");
paletteCard.setAttribute("data-aos-delay", "300");
const colorsDiv = document.createElement("div");
colorsDiv.className = "palette-colors";
palette.colors.forEach((color) => {
const colorSwatch = document.createElement("div");
colorSwatch.className = "color-swatch";
colorSwatch.style.backgroundColor = color;
colorSwatch.title = color;
colorSwatch.addEventListener("click", () => copyToClipboard(color));
colorsDiv.appendChild(colorSwatch);
});
const actionsDiv = document.createElement("div");
actionsDiv.className = "palette-actions";
const saveBtn = document.createElement("button");
// Check if the palette is already saved
const isSaved = savedPalettes.some(p => p.id === palette.id);
saveBtn.innerHTML = isSaved ? '<i class="fas fa-times"></i> Unsave' : '<i class="fas fa-save"></i> Save';
saveBtn.addEventListener("click", () => savePalette(palette, saveBtn));
//delete button
const deleteBtn = document.createElement('button');
deleteBtn.innerHTML = '<i class="fa-solid fa-trash"></i> Delete';
deleteBtn.addEventListener('click', () => deletePalette(palette));
const shareBtn = document.createElement("button");
shareBtn.innerHTML = '<i class="fas fa-share-alt"></i> Share';
shareBtn.addEventListener("click", () => openSnapshotModal(palette));
actionsDiv.appendChild(saveBtn);
actionsDiv.appendChild(shareBtn);
actionsDiv.appendChild(deleteBtn);
paletteCard.appendChild(colorsDiv);
paletteCard.appendChild(actionsDiv);
palettesContainer.appendChild(paletteCard);
});
}
function showToast(message, type = 'info') {
const toasterContainer = document.getElementById('toaster-container');
const toaster = document.createElement('div');
toaster.className = 'toaster glassmorphism';
const icon = document.createElement('i');
icon.className = 'toaster-icon';
switch (type) {
case 'success':
icon.className += ' fas fa-check-circle';
break;
case 'error':
icon.className += ' fas fa-exclamation-circle';
break;
default:
icon.className += ' fas fa-info-circle';
}
const messageSpan = document.createElement('span');
messageSpan.textContent = message;
const closeBtn = document.createElement('span');
closeBtn.innerHTML = '×';
closeBtn.className = 'toaster-close';
closeBtn.onclick = () => toaster.remove();
toaster.appendChild(icon);
toaster.appendChild(messageSpan);
toaster.appendChild(closeBtn);
toasterContainer.appendChild(toaster);
setTimeout(() => {
toaster.remove();
}, 3000);
}
// Copy color to clipboard
function copyToClipboard(text) {
navigator.clipboard.writeText(text).then(
() => {
showToast(`Copied ${text} to clipboard!`, 'success');
},
(err) => {
console.error("Could not copy text: ", err);
showToast("Failed to copy to clipboard", 'error');
}
);
}
function savePalette(palette, saveBtn) {
let savedPalettes = JSON.parse(localStorage.getItem("savedPalettes")) || [];
// Check if the palette is already saved
const paletteIndex = savedPalettes.findIndex(p => p.id === palette.id);
if (paletteIndex !== -1) {
// If the palette is already saved, remove it (unsave)
savedPalettes.splice(paletteIndex, 1);
localStorage.setItem("savedPalettes", JSON.stringify(savedPalettes));
showToast("Palette unsaved!", 'info');
// Update button text to "Save"
saveBtn.innerHTML = '<i class="fas fa-save"></i> Save';
} else {
// If the palette is not saved, save it
savedPalettes.push(palette);
localStorage.setItem("savedPalettes", JSON.stringify(savedPalettes));
showToast("Palette saved successfully!", 'success');
// Update button text to "Unsave"
saveBtn.innerHTML = '<i class="fas fa-times"></i> Unsave';
}
}
// Delete palette
function deletePalette(selectedPalette) {
// Show confirmation dialog using SweetAlert2
Swal.fire({
title: "Are you sure?",
text: "This action cannot be undone!",
icon: "warning",
showCancelButton: true,
confirmButtonColor: "#3085d6",
cancelButtonColor: "#d33",
confirmButtonText: "Yes, delete it!",
cancelButtonText: "No, cancel",
}).then((result) => {
if (result.isConfirmed) {
// If confirmed, delete the palette
const savedPalettes = JSON.parse(localStorage.getItem('savedPalettes')) || [];
const updatedPalettes = savedPalettes.filter((palette) => palette.id !== selectedPalette.id);
localStorage.setItem('savedPalettes', JSON.stringify(updatedPalettes));
// Update the UI
palettes = palettes.filter((palette) => palette.id !== selectedPalette.id);
renderPalettes();
// Show success toast
Swal.fire("Deleted!", "Your palette has been deleted.", "success");
}
});
}
// Open snapshot modal
function openSnapshotModal(palette) {
SnapshotModal.style.display = "block";
// Add event listener for the username input field
usernameInput.addEventListener("keypress", (event) => {
if (event.key === "Enter") {
event.preventDefault(); // Prevent form submission if within a form
const username = usernameInput.value.trim();
renderSnapshotCanvas(palette, username);
usernameInput.blur(); // Remove focus from the input field
}
});
// Enter Button Event Listner
let enterBtn = document.getElementById("enterBtn");
enterBtn.addEventListener("click", () => {
const username = usernameInput.value.trim();
renderSnapshotCanvas(palette, username); // Pass the last palette and username to the render function
});
// Delete Button Event Listener
let deleteBtn = document.getElementById("deleteBtn");
deleteBtn.addEventListener("click", () => {
const username = '';
usernameInput.value = '';
renderSnapshotCanvas(palette, username); // Pass the last palette and username to the render function
});
// Edit Button Event Listener
let editBtn = document.getElementById("editBtn");
editBtn.addEventListener("click", () => {
const currentUsername = usernameInput.value.trim();
usernameInput.value = currentUsername;
usernameInput.focus();
usernameInput.select();
// Update the snapshot when the user finishes editing
usernameInput.addEventListener("blur", () => {
const newUsername = usernameInput.value.trim();
if (newUsername !== currentUsername) {
renderSnapshotCanvas(palette, newUsername);
}
});
});
renderSnapshotCanvas(palette);
}
function openSnapshotModal(palette) {
shareSnapshotModal.style.display = "flex";
renderSnapshotCanvas(palette);
}
copyButton.addEventListener('click',() => {copyToClipboard(colorCodesDiv.textContent)});
// Render snapshot canvas
function renderSnapshotCanvas(palette, username) {
const ctx = snapshotCanvas.getContext("2d");
const width = 600;
const height = 400;
snapshotCanvas.width = width;
snapshotCanvas.height = height;
// Background
ctx.fillStyle = "#f0f0f0";
ctx.fillRect(0, 0, width, height);
// Title
ctx.fillStyle = "#333";
ctx.font = "bold 24px Arial";
ctx.textAlign = "center";
ctx.fillText("ChromaVerse Palette", width / 2, 40);
// Username
let userName;
if (username) {
userName = username;
} else {
userName = "Anonymous";
}
ctx.font = "16px Arial";
ctx.fillText(`Created by: ${userName}`, width / 2, 70);
// Color swatches
const swatchSize = 80;
const startX = (width - swatchSize * palette.colors.length) / 2;
const startY = 100;
palette.colors.forEach((color, index) => {
ctx.fillStyle = color;
ctx.fillRect(startX + index * swatchSize, startY, swatchSize, swatchSize);
ctx.fillStyle = "#333";
ctx.font = "12px Arial";
ctx.textAlign = "center";
ctx.fillText(
color,
startX + index * swatchSize + swatchSize / 2,
startY + swatchSize + 20
);
});
// Website URL
ctx.fillStyle = "#666";
ctx.font = "14px Arial";
ctx.textAlign = "center";
ctx.fillText("www.chromaverse.com", width / 2, height - 20);
}
// Download snapshot
function downloadSnapshot() {
const dataUrl = snapshotCanvas.toDataURL("image/png");
const link = document.createElement("a");
link.href = dataUrl;
link.download = "chromaverse_palette.png";
link.click();
}
// Share on social media
function shareOnSocialMedia(platform) {
const dataUrl = snapshotCanvas.toDataURL("image/png");
let shareUrl;
switch (platform) {
case "facebook":
shareUrl = `https://www.facebook.com/sharer/sharer.php?u=${encodeURIComponent(dataUrl)}`;
break;
case "twitter":
shareUrl = `https://twitter.com/intent/tweet?text=Check%20out%20my%20ChromaVerse%20palette!&url=${encodeURIComponent(dataUrl)}`;
break;
case "instagram":
showToast("To share on Instagram, please download the image and upload it manually to your Instagram account.", 'info');
return;
case "pinterest":
shareUrl = `https://pinterest.com/pin/create/button/?url=${encodeURIComponent(window.location.href)}&media=${encodeURIComponent(dataUrl)}&description=My%20ChromaVerse%20Palette`;
break;
}
if (shareUrl) {
window.open(shareUrl, "_blank");
showToast(`Sharing on ${platform.charAt(0).toUpperCase() + platform.slice(1)}`, 'success');
}
}
// Event listeners
generateBtn.addEventListener("click", generatePalette);
colorPicker.addEventListener("input", (e) => {
selectedColor.textContent = e.target.value;
selectedColor.style.backgroundColor = e.target.value;
const rValue = parseInt(e.target.value.slice(1, 3), 16);
selectedColor.style.color = rValue <= 128 ? 'white' : 'black';
});
modeToggle.addEventListener("click", () => {
document.body.classList.toggle("dark-mode");
const icon = modeToggle.querySelector("i");
icon.classList.toggle("fa-moon");
icon.classList.toggle("fa-sun");
// Save the current mode to localStorage
const isDarkMode = document.body.classList.contains("dark-mode");
localStorage.setItem("theme", isDarkMode ? "dark" : "light");
});
closeModal.addEventListener("click", () => {
shareSnapshotModal.style.display = "none";
});
downloadBtn.addEventListener("click", downloadSnapshot);
shareFacebook.addEventListener("click", () => shareOnSocialMedia("facebook"));
shareTwitter.addEventListener("click", () => shareOnSocialMedia("twitter"));
shareInstagram.addEventListener("click", () => shareOnSocialMedia("instagram"));
sharePinterest.addEventListener("click", () => shareOnSocialMedia("pinterest"));
// Color harmonization function
function harmonizeColors(baseColor, count = 5) {
const hsl = hexToHSL(baseColor);
const harmonizedColors = [];
for (let i = 0; i < count; i++) {
const newHue = (hsl.h + i * (360 / count)) % 360;
harmonizedColors.push(hslToHex(newHue, hsl.s, hsl.l));
}
return harmonizedColors;
}
// Helper functions for color conversion
function hexToHSL(hex) {
let r = 0,
g = 0,
b = 0;
if (hex.length === 4) {
r = parseInt(hex[1] + hex[1], 16);
g = parseInt(hex[2] + hex[2], 16);
b = parseInt(hex[3] + hex[3], 16);
} else if (hex.length === 7) {
r = parseInt(hex.substr(1, 2), 16);
g = parseInt(hex.substr(3, 2), 16);
b = parseInt(hex.substr(5, 2), 16);
}
(r /= 255), (g /= 255), (b /= 255);
const max = Math.max(r, g, b),
min = Math.min(r, g, b);
let h,
s,
l = (max + min) / 2;
if (max === min) {
h = s = 0;
} else {
const d = max - min;
s = l > 0.5 ? d / (2 - max - min) : d / (max + min);
switch (max) {
case r:
h = (g - b) / d + (g < b ? 6 : 0);
break;
case g:
h = (b - r) / d + 2;
break;
case b:
h = (r - g) / d + 4;
break;
}
h /= 6;
}
return { h: h * 360, s: s * 100, l: l * 100 };
}
function hslToHex(h, s, l) {
h /= 360;
s /= 100;
l /= 100;
let r, g, b;
if (s === 0) {
r = g = b = l;
} else {
const hue2rgb = (p, q, t) => {
if (t < 0) t += 1;
if (t > 1) t -= 1;
if (t < 1 / 6) return p + (q - p) * 6 * t;
if (t < 1 / 2) return q;
if (t < 2 / 3) return p + (q - p) * (2 / 3 - t) * 6;
return p;
};
const q = l < 0.5 ? l * (1 + s) : l + s - l * s;
const p = 2 * l - q;
r = hue2rgb(p, q, h + 1 / 3);
g = hue2rgb(p, q, h);
b = hue2rgb(p, q, h - 1 / 3);
}
const toHex = (x) => {
const hex = Math.round(x * 255).toString(16);
return hex.length === 1 ? "0" + hex : hex;
};
return `#${toHex(r)}${toHex(g)}${toHex(b)}`;
}
// Initialize the app
function init() {
const savedTheme = localStorage.getItem("theme");
// Apply the saved theme if it exists
if (savedTheme === "dark") {
document.body.classList.add("dark-mode");
const icon = modeToggle.querySelector("i");
icon.classList.remove("fa-moon");
icon.classList.add("fa-sun");
} else {
document.body.classList.remove("dark-mode");
const icon = modeToggle.querySelector("i");
icon.classList.remove("fa-sun");
icon.classList.add("fa-moon");
}
const savedPalettes = JSON.parse(localStorage.getItem("savedPalettes")) || [];
palettes = savedPalettes;
renderPalettes();
}
init();