-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathscript.js
More file actions
685 lines (625 loc) · 24 KB
/
script.js
File metadata and controls
685 lines (625 loc) · 24 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
674
675
676
677
678
679
680
681
682
683
684
685
(() => {
"use strict";
const STORAGE_CURRENT = "ctb-current-theme-v2";
const STORAGE_SAVED = "ctb-saved-themes-v2";
const API_PORTS = [3000, 3001, 3002, 3003, 3004, 3005, 3006, 3007, 3008, 3009];
const FIELDS = [
["background", "Background", "--theme-bg"],
["foreground", "Foreground", "--theme-fg"],
["keywords", "Keywords", "--theme-keyword"],
["strings", "Strings", "--theme-string"],
["comments", "Comments", "--theme-comment"],
["functions", "Functions", "--theme-function"],
["numbers", "Numbers", "--theme-number"],
["classes", "Classes", "--theme-class"]
];
const PRESETS = {
catppuccin: {
name: "Catppuccin Mocha",
colors: {
background: "#1e1e2e",
foreground: "#cdd6f4",
keywords: "#cba6f7",
strings: "#a6e3a1",
comments: "#6c7086",
functions: "#89b4fa",
numbers: "#fab387",
classes: "#f9e2af"
}
},
dracula: {
name: "Dracula",
colors: {
background: "#282a36",
foreground: "#f8f8f2",
keywords: "#ff79c6",
strings: "#f1fa8c",
comments: "#6272a4",
functions: "#50fa7b",
numbers: "#bd93f9",
classes: "#8be9fd"
}
},
onedark: {
name: "One Dark",
colors: {
background: "#282c34",
foreground: "#abb2bf",
keywords: "#c678dd",
strings: "#98c379",
comments: "#5c6370",
functions: "#61afef",
numbers: "#d19a66",
classes: "#e5c07b"
}
},
monokai: {
name: "Monokai",
colors: {
background: "#272822",
foreground: "#f8f8f2",
keywords: "#f92672",
strings: "#e6db74",
comments: "#75715e",
functions: "#a6e22e",
numbers: "#ae81ff",
classes: "#66d9ef"
}
},
githubdark: {
name: "GitHub Dark",
colors: {
background: "#0d1117",
foreground: "#c9d1d9",
keywords: "#ff7b72",
strings: "#a5d6ff",
comments: "#8b949e",
functions: "#d2a8ff",
numbers: "#79c0ff",
classes: "#ffa657"
}
}
};
const DEFAULT_THEME = {
name: "My Custom Theme",
type: "dark",
colors: { ...PRESETS.catppuccin.colors }
};
const PREVIEWS = {
javascript: [
["comment", "// Fetch orders and render a dashboard"],
["keyword", "async"], ["plain", " "], ["keyword", "function"], ["plain", " "], ["function", "loadOrders"], ["plain", "() {"],
["keyword", "const"], ["plain", " response = "], ["keyword", "await"], ["plain", " "], ["function", "fetch"], ["plain", "("], ["string", "\"/api/orders\""], ["plain", ");"],
["keyword", "const"], ["plain", " orders = "], ["keyword", "await"], ["plain", " response."], ["function", "json"], ["plain", "();"],
["plain", "orders."], ["function", "filter"], ["plain", "((order) => order.total > "], ["number", "500"], ["plain", ")."], ["function", "forEach"], ["plain", "("], ["function", "renderOrder"], ["plain", ");"],
["plain", "}"]
],
python: [
["comment", "# Analyze average score by subject"],
["keyword", "import"], ["plain", " pandas "], ["keyword", "as"], ["plain", " pd"],
["keyword", "def"], ["plain", " "], ["function", "subject_average"], ["plain", "(path):"],
["plain", " frame = pd."], ["function", "read_csv"], ["plain", "("], ["string", "\"students.csv\""], ["plain", ")"],
["plain", " result = frame."], ["function", "groupby"], ["plain", "("], ["string", "\"subject\""], ["plain", ")["], ["string", "\"score\""], ["plain", "]."], ["function", "mean"], ["plain", "()"],
["plain", " "], ["keyword", "return"], ["plain", " result."], ["function", "round"], ["plain", "("], ["number", "2"], ["plain", ")"]
],
html: [
["comment", "<!-- Product card markup -->"],
["plain", "<"], ["keyword", "article"], ["plain", " "], ["class", "class"], ["plain", "="], ["string", "\"card\""], ["plain", ">"],
["plain", " <"], ["keyword", "h2"], ["plain", ">"], ["string", "Code Theme Builder"], ["plain", "</"], ["keyword", "h2"], ["plain", ">"],
["plain", " <"], ["keyword", "button"], ["plain", " "], ["class", "type"], ["plain", "="], ["string", "\"button\""], ["plain", ">Export</"], ["keyword", "button"], ["plain", ">"],
["plain", "</"], ["keyword", "article"], ["plain", ">"]
],
css: [
["comment", "/* Editor token colors */"],
["class", ".editor"], ["plain", " {"],
["plain", " background: "], ["string", "var(--theme-bg)"], ["plain", ";"],
["plain", " color: "], ["string", "var(--theme-fg)"], ["plain", ";"],
["plain", " border-radius: "], ["number", "12px"], ["plain", ";"],
["plain", "}"],
["class", ".token-keyword"], ["plain", " { color: "], ["string", "var(--theme-keyword)"], ["plain", "; }"]
],
java: [
["comment", "// Account service example"],
["keyword", "public"], ["plain", " "], ["keyword", "class"], ["plain", " "], ["class", "BankService"], ["plain", " {"],
["plain", " "], ["keyword", "private"], ["plain", " "], ["keyword", "final"], ["plain", " Map<String, Account> accounts = "], ["keyword", "new"], ["plain", " "], ["class", "HashMap"], ["plain", "<>();"],
["plain", " "], ["keyword", "public"], ["plain", " Account "], ["function", "findAccount"], ["plain", "(String id) {"],
["plain", " "], ["keyword", "return"], ["plain", " accounts."], ["function", "get"], ["plain", "(id);"],
["plain", " }"],
["plain", "}"]
]
};
const $ = (selector) => document.querySelector(selector);
const els = {
colorGrid: $("#color-grid"),
themeName: $("#theme-name"),
presetSelect: $("#preset-select"),
savedSelect: $("#saved-select"),
codeContent: $("#code-content"),
languageSelect: $("#language-select"),
fontSelect: $("#font-select"),
preview: $("#code-preview"),
contrastScore: $("#contrast-score"),
contrastStatus: $("#contrast-status"),
toastWrap: $("#toast-wrap"),
importInput: $("#theme-import"),
apiStatus: $("#api-status"),
gallerySelect: $("#gallery-select")
};
let theme = readJson(STORAGE_CURRENT, DEFAULT_THEME);
let backendOnline = false;
let galleryThemes = [];
let apiBase = "";
function readJson(key, fallback) {
try {
return JSON.parse(localStorage.getItem(key)) || fallback;
} catch {
return fallback;
}
}
function writeCurrent() {
localStorage.setItem(STORAGE_CURRENT, JSON.stringify(theme));
}
function clampTheme(input) {
const colors = { ...DEFAULT_THEME.colors, ...(input.colors || input) };
return {
id: input.id || null,
name: input.name || theme.name || DEFAULT_THEME.name,
type: input.type || "dark",
colors,
likes: Number(input.likes || 0),
downloads: Number(input.downloads || 0)
};
}
function initControls() {
els.colorGrid.innerHTML = FIELDS.map(([key, label]) => `
<label class="color-control" for="picker-${key}">
<span>${label}</span>
<div>
<input type="color" id="picker-${key}" data-color="${key}">
<code id="hex-${key}"></code>
</div>
</label>
`).join("");
els.presetSelect.innerHTML += Object.entries(PRESETS).map(([key, preset]) => (
`<option value="${key}">${preset.name}</option>`
)).join("");
}
function applyTheme(nextTheme, options = {}) {
theme = clampTheme(nextTheme);
els.themeName.value = theme.name;
FIELDS.forEach(([key, , cssVar]) => {
const value = theme.colors[key];
document.documentElement.style.setProperty(cssVar, value);
const picker = document.getElementById(`picker-${key}`);
const label = document.getElementById(`hex-${key}`);
if (picker) picker.value = value;
if (label) label.textContent = value;
});
renderPreview();
updateContrast();
if (!options.skipSave) writeCurrent();
}
function renderPreview() {
const tokens = PREVIEWS[els.languageSelect.value] || PREVIEWS.javascript;
let line = 1;
let output = `<span class="line-num">${String(line).padStart(2, " ")}</span>`;
tokens.forEach(([type, text]) => {
const escaped = escapeHtml(text);
if (text.includes("\n")) return;
if (type === "comment" && output !== "") {
output += `<span class="token token-${type}">${escaped}</span>\n<span class="line-num">${String(++line).padStart(2, " ")}</span>`;
return;
}
output += `<span class="token token-${type}">${escaped}</span>`;
if (text.endsWith(";") || text.endsWith("{") || text.endsWith("}") || text.startsWith("import") || text.endsWith(":") || text.endsWith(">")) {
output += `\n<span class="line-num">${String(++line).padStart(2, " ")}</span>`;
}
});
els.codeContent.innerHTML = output.replace(/\n<span class="line-num">\s+\d+<\/span>$/, "");
els.preview.style.fontFamily = `"${els.fontSelect.value}", monospace`;
}
function escapeHtml(value) {
return value.replace(/[&<>"']/g, (char) => ({
"&": "&",
"<": "<",
">": ">",
'"': """,
"'": "'"
})[char]);
}
function luminance(hex) {
const rgb = [1, 3, 5].map((start) => parseInt(hex.slice(start, start + 2), 16) / 255);
const linear = rgb.map((channel) => (
channel <= 0.03928 ? channel / 12.92 : ((channel + 0.055) / 1.055) ** 2.4
));
return 0.2126 * linear[0] + 0.7152 * linear[1] + 0.0722 * linear[2];
}
function contrastRatio(a, b) {
const light = Math.max(luminance(a), luminance(b));
const dark = Math.min(luminance(a), luminance(b));
return (light + 0.05) / (dark + 0.05);
}
function updateContrast() {
const ratio = contrastRatio(theme.colors.background, theme.colors.foreground);
els.contrastScore.textContent = `${ratio.toFixed(2)}:1`;
if (ratio >= 7) {
els.contrastStatus.textContent = "Excellent contrast for small text.";
els.contrastStatus.dataset.level = "good";
} else if (ratio >= 4.5) {
els.contrastStatus.textContent = "Passes normal text contrast.";
els.contrastStatus.dataset.level = "ok";
} else {
els.contrastStatus.textContent = "Low contrast. Adjust background or foreground.";
els.contrastStatus.dataset.level = "bad";
}
}
function shade(hex, amount) {
const next = [1, 3, 5].map((start) => {
const value = Math.max(0, Math.min(255, parseInt(hex.slice(start, start + 2), 16) + amount));
return value.toString(16).padStart(2, "0");
});
return `#${next.join("")}`;
}
function hexToRgba(hex, alpha) {
const r = parseInt(hex.slice(1, 3), 16);
const g = parseInt(hex.slice(3, 5), 16);
const b = parseInt(hex.slice(5, 7), 16);
return `rgba(${r}, ${g}, ${b}, ${alpha})`;
}
function generateVSCodeTheme() {
const c = theme.colors;
return {
"$schema": "vscode://schemas/color-theme",
name: theme.name,
type: theme.type,
colors: {
"editor.background": c.background,
"editor.foreground": c.foreground,
"editor.lineHighlightBackground": hexToRgba(c.foreground, 0.07),
"editor.selectionBackground": hexToRgba(c.functions, 0.24),
"editorCursor.foreground": c.functions,
"editorLineNumber.foreground": hexToRgba(c.comments, 0.75),
"editorLineNumber.activeForeground": c.foreground,
"sideBar.background": shade(c.background, theme.type === "dark" ? -8 : 8),
"sideBar.foreground": c.foreground,
"activityBar.background": shade(c.background, theme.type === "dark" ? -16 : 16),
"activityBar.foreground": c.foreground,
"titleBar.activeBackground": shade(c.background, theme.type === "dark" ? -16 : 16),
"titleBar.activeForeground": c.foreground,
"tab.activeBackground": c.background,
"tab.activeForeground": c.foreground,
"statusBar.background": shade(c.background, theme.type === "dark" ? -16 : 16),
"statusBar.foreground": c.foreground,
"terminal.background": c.background,
"terminal.foreground": c.foreground
},
tokenColors: [
{ name: "Comments", scope: ["comment"], settings: { foreground: c.comments, fontStyle: "italic" } },
{ name: "Keywords", scope: ["keyword", "storage.type", "storage.modifier"], settings: { foreground: c.keywords } },
{ name: "Strings", scope: ["string"], settings: { foreground: c.strings } },
{ name: "Functions", scope: ["entity.name.function", "support.function"], settings: { foreground: c.functions } },
{ name: "Numbers", scope: ["constant.numeric", "constant.language"], settings: { foreground: c.numbers } },
{ name: "Classes", scope: ["entity.name.type", "entity.name.class", "support.class"], settings: { foreground: c.classes } },
{ name: "Variables", scope: ["variable", "variable.parameter"], settings: { foreground: c.foreground } }
]
};
}
function copyText(text, message) {
navigator.clipboard.writeText(text).then(() => showToast(message)).catch(() => {
showToast("Clipboard permission was blocked");
});
}
function downloadJson() {
const json = JSON.stringify(generateVSCodeTheme(), null, 2);
const blob = new Blob([json], { type: "application/json" });
const url = URL.createObjectURL(blob);
const link = document.createElement("a");
link.href = url;
link.download = `${theme.name.toLowerCase().replace(/[^a-z0-9]+/g, "-").replace(/(^-|-$)/g, "") || "theme"}.json`;
document.body.append(link);
link.click();
link.remove();
URL.revokeObjectURL(url);
showToast("Theme JSON downloaded");
recordDownload();
}
function currentCss() {
const lines = FIELDS.map(([key, , cssVar]) => ` ${cssVar}: ${theme.colors[key]};`);
return `:root {\n${lines.join("\n")}\n}`;
}
function randomHex() {
return `#${Math.floor(Math.random() * 0xffffff).toString(16).padStart(6, "0")}`;
}
function randomPalette() {
applyTheme({
name: "Random Palette",
type: "dark",
colors: {
background: "#101018",
foreground: "#f4f4f5",
keywords: randomHex(),
strings: randomHex(),
comments: "#7b8194",
functions: randomHex(),
numbers: randomHex(),
classes: randomHex()
}
});
els.presetSelect.value = "";
showToast("Random palette generated");
}
function savedThemes() {
return readJson(STORAGE_SAVED, []);
}
function renderSavedThemes() {
const saved = savedThemes();
els.savedSelect.innerHTML = saved.length
? `<option value="">Load saved theme</option>${saved.map((item) => `<option value="${item.id}">${item.name}</option>`).join("")}`
: `<option value="">No saved themes</option>`;
}
function saveNamedTheme() {
const saved = savedThemes();
const id = theme.name.toLowerCase().replace(/[^a-z0-9]+/g, "-") || Date.now().toString();
const next = [{ ...theme, id }, ...saved.filter((item) => item.id !== id)].slice(0, 12);
localStorage.setItem(STORAGE_SAVED, JSON.stringify(next));
renderSavedThemes();
els.savedSelect.value = id;
showToast("Theme saved");
}
function deleteSavedTheme() {
const id = els.savedSelect.value;
if (!id) {
showToast("Choose a saved theme first");
return;
}
localStorage.setItem(STORAGE_SAVED, JSON.stringify(savedThemes().filter((item) => item.id !== id)));
renderSavedThemes();
showToast("Saved theme deleted");
}
async function apiRequest(path, options = {}) {
const response = await fetch(`${apiBase}${path}`, {
headers: {
"Content-Type": "application/json",
...(options.headers || {})
},
...options
});
const data = await response.json().catch(() => ({}));
if (!response.ok) {
throw new Error(data.error || "Backend request failed");
}
return data;
}
function renderBackendStatus() {
els.apiStatus.textContent = backendOnline ? "Backend online" : "Backend offline";
els.apiStatus.classList.toggle("online", backendOnline);
}
function renderGallery() {
if (!backendOnline) {
els.gallerySelect.innerHTML = `<option value="">Run backend to load gallery</option>`;
return;
}
els.gallerySelect.innerHTML = galleryThemes.length
? `<option value="">Choose backend theme</option>${galleryThemes.map((item) => (
`<option value="${item.id}">${item.name} (${item.likes || 0} likes, ${item.downloads || 0} downloads)</option>`
)).join("")}`
: `<option value="">No backend themes yet</option>`;
}
async function checkBackend() {
const bases = window.location.protocol === "file:"
? API_PORTS.map((port) => `http://localhost:${port}`)
: [""];
for (const base of bases) {
try {
apiBase = base;
await apiRequest("/api/health");
backendOnline = true;
renderBackendStatus();
await refreshGallery(false);
return;
} catch {
backendOnline = false;
}
}
apiBase = "";
renderBackendStatus();
renderGallery();
}
async function refreshGallery(showMessage = true) {
if (!backendOnline) {
showToast("Start the backend with npm start first");
return;
}
try {
galleryThemes = await apiRequest("/api/themes");
renderGallery();
if (showMessage) showToast("Backend gallery refreshed");
} catch (error) {
backendOnline = false;
renderBackendStatus();
renderGallery();
showToast(error.message);
}
}
async function publishTheme() {
if (!backendOnline) {
showToast("Start the backend with npm start first");
return;
}
try {
const saved = await apiRequest("/api/themes", {
method: "POST",
body: JSON.stringify(theme)
});
applyTheme(saved);
await refreshGallery(false);
els.gallerySelect.value = saved.id;
showToast("Theme published to backend");
} catch (error) {
showToast(error.message);
}
}
function selectedGalleryTheme() {
return galleryThemes.find((item) => item.id === els.gallerySelect.value);
}
function loadGalleryTheme() {
const selected = selectedGalleryTheme();
if (!selected) {
showToast("Choose a backend theme first");
return;
}
applyTheme(selected);
showToast("Backend theme loaded");
}
async function likeGalleryTheme() {
const selected = selectedGalleryTheme();
if (!selected) {
showToast("Choose a backend theme first");
return;
}
try {
const updated = await apiRequest(`/api/themes/${selected.id}/like`, { method: "POST" });
galleryThemes = galleryThemes.map((item) => item.id === updated.id ? updated : item);
renderGallery();
els.gallerySelect.value = updated.id;
showToast("Theme liked");
} catch (error) {
showToast(error.message);
}
}
async function deleteGalleryTheme() {
const selected = selectedGalleryTheme();
if (!selected) {
showToast("Choose a backend theme first");
return;
}
try {
await apiRequest(`/api/themes/${selected.id}`, { method: "DELETE" });
await refreshGallery(false);
showToast("Backend theme deleted");
} catch (error) {
showToast(error.message);
}
}
async function recordDownload() {
if (!backendOnline || !theme.id) return;
try {
const updated = await apiRequest(`/api/themes/${theme.id}/download`, { method: "POST" });
galleryThemes = galleryThemes.map((item) => item.id === updated.id ? updated : item);
renderGallery();
els.gallerySelect.value = updated.id;
} catch {
// Download should still work even if analytics fails.
}
}
function importTheme(file) {
const reader = new FileReader();
reader.onload = () => {
try {
const parsed = JSON.parse(String(reader.result));
const colors = parsed.colors || {};
const tokenColors = parsed.tokenColors || [];
const token = (name, fallback) => {
const match = tokenColors.find((entry) => String(entry.name || "").toLowerCase().includes(name));
return match?.settings?.foreground || fallback;
};
applyTheme({
name: parsed.name || "Imported Theme",
type: parsed.type || "dark",
colors: {
background: colors["editor.background"] || DEFAULT_THEME.colors.background,
foreground: colors["editor.foreground"] || DEFAULT_THEME.colors.foreground,
keywords: token("keyword", DEFAULT_THEME.colors.keywords),
strings: token("string", DEFAULT_THEME.colors.strings),
comments: token("comment", DEFAULT_THEME.colors.comments),
functions: token("function", DEFAULT_THEME.colors.functions),
numbers: token("number", DEFAULT_THEME.colors.numbers),
classes: token("class", DEFAULT_THEME.colors.classes)
}
});
showToast("Theme imported");
} catch {
showToast("Invalid JSON file");
}
};
reader.readAsText(file);
}
function applyUrlTheme() {
const params = new URLSearchParams(window.location.search);
const encoded = params.get("theme");
if (!encoded) return false;
try {
applyTheme(JSON.parse(atob(encoded)));
return true;
} catch {
return false;
}
}
function copyShareLink() {
const encoded = btoa(JSON.stringify(theme));
const url = `${window.location.origin}${window.location.pathname}?theme=${encoded}`;
copyText(url, "Share link copied");
}
function showToast(message) {
const toast = document.createElement("div");
toast.className = "toast";
toast.textContent = message;
els.toastWrap.append(toast);
setTimeout(() => toast.remove(), 2300);
}
function bindEvents() {
els.colorGrid.addEventListener("input", (event) => {
const input = event.target.closest("[data-color]");
if (!input) return;
theme.colors[input.dataset.color] = input.value;
applyTheme(theme);
els.presetSelect.value = "";
});
els.themeName.addEventListener("input", () => {
theme.name = els.themeName.value.trim() || DEFAULT_THEME.name;
writeCurrent();
});
els.presetSelect.addEventListener("change", () => {
const preset = PRESETS[els.presetSelect.value];
if (!preset) return;
applyTheme({ name: preset.name, type: "dark", colors: preset.colors });
showToast(`${preset.name} loaded`);
});
els.savedSelect.addEventListener("change", () => {
const found = savedThemes().find((item) => item.id === els.savedSelect.value);
if (found) applyTheme(found);
});
els.languageSelect.addEventListener("change", renderPreview);
els.fontSelect.addEventListener("change", renderPreview);
els.importInput.addEventListener("change", () => {
const file = els.importInput.files?.[0];
if (file) importTheme(file);
els.importInput.value = "";
});
$("#btn-copy-css").addEventListener("click", () => copyText(currentCss(), "CSS variables copied"));
$("#btn-copy-json").addEventListener("click", () => copyText(JSON.stringify(generateVSCodeTheme(), null, 2), "Theme JSON copied"));
$("#btn-export").addEventListener("click", downloadJson);
$("#btn-reset").addEventListener("click", () => {
applyTheme(DEFAULT_THEME);
els.presetSelect.value = "";
showToast("Theme reset");
});
$("#btn-random").addEventListener("click", randomPalette);
$("#btn-share").addEventListener("click", copyShareLink);
$("#btn-save").addEventListener("click", saveNamedTheme);
$("#btn-delete").addEventListener("click", deleteSavedTheme);
$("#btn-publish").addEventListener("click", publishTheme);
$("#btn-refresh-gallery").addEventListener("click", () => refreshGallery(true));
$("#btn-load-gallery").addEventListener("click", loadGalleryTheme);
$("#btn-like-gallery").addEventListener("click", likeGalleryTheme);
$("#btn-delete-gallery").addEventListener("click", deleteGalleryTheme);
}
function init() {
initControls();
renderSavedThemes();
if (!applyUrlTheme()) applyTheme(theme, { skipSave: true });
bindEvents();
checkBackend();
}
init();
})();