Repository navigation
Expand file tree
/
Copy pathapp.js
More file actions
834 lines (790 loc) · 30.8 KB
/
Copy pathapp.js
File metadata and controls
834 lines (790 loc) · 30.8 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
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
/* Iconopolis renderer */
const $ = (id) => document.getElementById(id);
const state = {
sets: [], // full index: [{prefix,name,category,palette,total,icons[]}]
byPrefix: new Map(),
results: [], // current result list: [{prefix,name}]
rendered: 0, // how many results are in the DOM
mode: 'home', // home | results
activeSet: null, // prefix when browsing a single set
query: '',
color: 'auto',
format: 'svg',
pngSize: 256,
style: { pad: 0, bg: 'none', bgColor: '#FFFFFF' },
favs: { favorites: [], collections: {} },
activeCollection: null, // {title, keys} while viewing Favorites or a collection
selected: null, // {prefix,name}
dragPrep: null,
};
const BATCH = 180;
const MAX_RESULTS = 4000;
const svgCache = new Map(); // "prefix:name" -> svg string (cap ~6000)
// Parse an SVG string (from local Iconify data) into a real element — no innerHTML.
function svgElement(svgText) {
const doc = new DOMParser().parseFromString(svgText, 'image/svg+xml');
return document.importNode(doc.documentElement, true);
}
function setSvg(el, svgText) {
el.replaceChildren(svgElement(svgText));
}
/* ---------- Boot ---------- */
window.vault.onSetupProgress(({ phase, pct, detail }) => {
const msgs = {
metadata: 'Contacting the icon registry…',
download: `Downloading the icon collection${detail ? ' v' + detail : ''}… ${pct}%`,
extract: `Unpacking 375,000+ icons… ${pct}%`,
index: `Building the search index… ${pct}%`,
};
$('loadingmsg').textContent = msgs[phase] || 'Preparing…';
});
(async function boot() {
let raw;
try {
raw = await window.vault.getIndex();
} catch (e) {
$('loadingmsg').textContent = 'Could not download the icon collection. Check your internet connection.';
const retry = document.createElement('button');
retry.textContent = 'Try Again';
retry.className = 'retry';
retry.addEventListener('click', () => location.reload());
$('loading').appendChild(retry);
return;
}
const idx = JSON.parse(raw);
state.sets = idx.sets;
for (const s of state.sets) state.byPrefix.set(s.prefix, s);
const totalIcons = state.sets.reduce((n, s) => n + s.total, 0);
$('search').placeholder = `Search ${totalIcons.toLocaleString()} icons…`;
$('loading').classList.add('hidden');
await restoreSettings();
const favs = await window.vault.loadFavs();
if (favs) state.favs = { favorites: [], collections: {}, meta: {}, ...favs };
showHome();
if (!state.helpSeen) showHelp();
})();
/* ---------- Views ---------- */
function showHome() {
state.mode = 'home';
state.activeSet = null;
state.activeCollection = null;
$('scope').textContent = 'All sets';
$('home').classList.remove('hidden');
$('results').classList.add('hidden');
buildMySection();
if (!$('homesections').childElementCount) buildHome();
}
/* ---------- My Icons: favorites + collections on the home screen ---------- */
function buildMySection() {
const wrap = $('mysection');
wrap.replaceChildren();
const hasFavs = state.favs.favorites.length > 0;
const collNames = Object.keys(state.favs.collections);
if (!hasFavs && !collNames.length) return;
// Favorites is the daily driver — its own always-visible button, outside the dropdown.
if (hasFavs) {
const fav = document.createElement('button');
fav.className = 'mybtn';
fav.textContent = `★ Favorites · ${state.favs.favorites.length}`;
fav.addEventListener('click', () => openCollection('Favorites', state.favs.favorites));
const favRow = document.createElement('div');
favRow.className = 'myrow';
favRow.appendChild(fav);
wrap.appendChild(favRow);
}
if (collNames.length) {
const row = document.createElement('div');
row.className = 'myrow';
const btn = document.createElement('button');
btn.className = 'mybtn';
btn.textContent = `▦ Collections · ${collNames.length} ▾`;
const menu = document.createElement('div');
menu.className = 'mymenu hidden';
btn.addEventListener('click', (e) => {
e.stopPropagation();
buildMyMenu(menu);
menu.classList.toggle('hidden');
});
row.append(btn, menu);
wrap.appendChild(row);
}
}
function sortedCollNames() {
const names = Object.keys(state.favs.collections);
const meta = state.favs.meta || {};
if ((state.collSort || 'recent') === 'name') return names.sort((a, b) => a.localeCompare(b));
return names.sort((a, b) => (meta[b]?.t || 0) - (meta[a]?.t || 0));
}
function touchColl(name) {
if (!state.favs.meta) state.favs.meta = {};
state.favs.meta[name] = { t: Date.now() };
}
function buildMyMenu(menu) {
menu.replaceChildren();
const seg = document.createElement('div');
seg.className = 'sortseg';
for (const [val, label] of [['recent', 'Recent first'], ['name', 'By name']]) {
const b = document.createElement('button');
b.textContent = label;
b.classList.toggle('sel', (state.collSort || 'recent') === val);
b.addEventListener('click', (e) => {
e.stopPropagation();
state.collSort = val;
saveSettings();
buildMyMenu(menu);
});
seg.appendChild(b);
}
menu.appendChild(seg);
const addRow = (emoji, title, keys) => {
const b = document.createElement('button');
b.className = 'myrowitem';
const s = document.createElement('span');
s.textContent = `${emoji} ${title}`;
const n = document.createElement('span');
n.className = 'n';
n.textContent = keys.length;
b.append(s, n);
b.addEventListener('click', () => openCollection(title, keys));
menu.appendChild(b);
};
for (const name of sortedCollNames()) addRow('▦', name, state.favs.collections[name]);
const manage = document.createElement('button');
manage.className = 'myrowitem manage';
manage.textContent = '⚙ Manage collections…';
manage.addEventListener('click', () => {
menu.classList.add('hidden');
openManage();
});
menu.appendChild(manage);
}
/* ---------- Manage Collections: mass delete ---------- */
function openManage() {
const list = $('managelist');
list.replaceChildren();
for (const name of sortedCollNames()) {
const row = document.createElement('label');
row.className = 'managerow';
const cb = document.createElement('input');
cb.type = 'checkbox';
cb.value = name;
const label = document.createElement('span');
label.textContent = name;
const n = document.createElement('span');
n.className = 'n';
n.textContent = `${state.favs.collections[name].length} icons`;
row.append(cb, label, n);
list.appendChild(row);
}
$('manageoverlay').classList.remove('hidden');
}
$('closemanage').addEventListener('click', () => $('manageoverlay').classList.add('hidden'));
$('manageoverlay').addEventListener('click', (e) => {
if (e.target === $('manageoverlay')) $('manageoverlay').classList.add('hidden');
});
$('selallcoll').addEventListener('click', () => {
const boxes = [...document.querySelectorAll('#managelist input')];
const allChecked = boxes.every((b) => b.checked);
boxes.forEach((b) => { b.checked = !allChecked; });
});
$('delselcoll').addEventListener('click', () => {
const chosen = [...document.querySelectorAll('#managelist input:checked')].map((b) => b.value);
if (!chosen.length) { toast('Nothing selected'); return; }
if (!confirm(`Delete ${chosen.length} collection${chosen.length > 1 ? 's' : ''}?\nThe icons themselves stay in the library.`)) return;
for (const name of chosen) {
delete state.favs.collections[name];
if (state.favs.meta) delete state.favs.meta[name];
if (state.activeCollection?.title === name) state.activeCollection = null;
}
persistFavs();
toast(`Deleted ${chosen.length} collection${chosen.length > 1 ? 's' : ''}`);
if (Object.keys(state.favs.collections).length) openManage();
else $('manageoverlay').classList.add('hidden');
if (state.mode === 'home') buildMySection();
});
function openCollection(title, keys) {
state.activeSet = null;
state.activeCollection = { title, keys: [...keys] };
$('scope').textContent = title;
showResults(keys.map((k) => {
const [prefix, ...rest] = k.split(':');
return { prefix, name: rest.join(':') };
}));
}
function buildHome() {
const cats = new Map();
for (const s of state.sets) {
if (!cats.has(s.category)) cats.set(s.category, []);
cats.get(s.category).push(s);
}
const PRIORITY = ['UI 24px', 'UI 16px / 32px', 'UI Other / Mixed Grid', 'UI Multicolor',
'Material', 'Emoji', 'Flags / Maps', 'Logos', 'Programming', 'Thematic', 'Other',
'Archive / Unmaintained'];
const rank = (c) => { const i = PRIORITY.indexOf(c); return i === -1 ? 90 : i; };
const order = [...cats.keys()].sort((a, b) => rank(a) - rank(b) || a.localeCompare(b));
const frag = document.createDocumentFragment();
for (const cat of order) {
const sec = document.createElement('section');
sec.className = 'cat';
const h = document.createElement('h2');
h.textContent = `${cat} · ${cats.get(cat).length} sets`;
sec.appendChild(h);
const cards = document.createElement('div');
cards.className = 'setcards';
for (const s of cats.get(cat)) {
const b = document.createElement('button');
b.className = 'setcard';
const n = document.createElement('div');
n.className = 'sname';
n.textContent = s.name;
const c = document.createElement('div');
c.className = 'scount';
c.textContent = `${s.total.toLocaleString()} icons`;
const l = document.createElement('div');
l.className = 'slic';
l.textContent = s.license + (s.author ? ` · ${s.author}` : '');
b.append(n, c, l);
b.addEventListener('click', () => openSet(s.prefix));
cards.appendChild(b);
}
sec.appendChild(cards);
frag.appendChild(sec);
}
$('homesections').appendChild(frag);
}
function openSet(prefix) {
const s = state.byPrefix.get(prefix);
state.activeSet = prefix;
$('scope').textContent = s.name;
runSearch($('search').value.trim());
}
function showResults(list) {
state.mode = 'results';
state.gen = (state.gen || 0) + 1; // invalidates in-flight batch renders of older queries
state.results = list;
state.rendered = 0;
$('grid').textContent = '';
$('home').classList.add('hidden');
$('results').classList.remove('hidden');
$('noresults').classList.toggle('hidden', list.length > 0);
const cap = list.length >= MAX_RESULTS ? `first ${MAX_RESULTS.toLocaleString()} of many` : list.length.toLocaleString();
$('resultcount').textContent = list.length ? `${cap} icons` : '';
updateSetInfo();
renderNextBatch();
}
// Persistent set header: name, count, license (linked), author — visible whenever
// browsing a single set.
function updateSetInfo() {
const el = $('setinfo');
if (state.activeCollection) {
const { title, keys } = state.activeCollection;
const isFavs = title === 'Favorites';
const name = document.createElement('span');
name.className = 'sname';
name.textContent = title;
const count = document.createElement('span');
count.textContent = `${keys.length} icons · select an icon and use + Collection to remove it`;
const exp = document.createElement('button');
exp.className = 'exportall';
exp.textContent = 'Export All…';
exp.addEventListener('click', exportCollection);
const children = [name, count, exp];
if (!isFavs) {
const ren = document.createElement('button');
ren.className = 'ghost';
ren.textContent = 'Rename';
ren.addEventListener('click', () => renameCollection(title));
const del = document.createElement('button');
del.className = 'ghost';
del.textContent = 'Delete Collection';
del.addEventListener('click', () => deleteCollection(title));
children.push(ren, del);
}
el.replaceChildren(...children);
el.classList.remove('hidden');
$('resultcount').textContent = '';
return;
}
const s = state.activeSet && !state.query ? state.byPrefix.get(state.activeSet) : null;
if (!s) { el.classList.add('hidden'); el.replaceChildren(); return; }
const name = document.createElement('span');
name.className = 'sname';
name.textContent = s.name;
const count = document.createElement('span');
count.textContent = `${s.total.toLocaleString()} icons`;
const lic = s.licenseUrl ? document.createElement('a') : document.createElement('span');
lic.textContent = s.license;
if (s.licenseUrl) {
lic.href = s.licenseUrl;
lic.target = '_blank';
lic.title = 'Read the full license';
}
el.replaceChildren(name, count, lic);
if (s.author) {
const by = document.createElement('span');
by.textContent = `by ${s.author}`;
el.appendChild(by);
}
el.classList.remove('hidden');
$('resultcount').textContent = '';
}
/* ---------- Search ---------- */
function runSearch(qRaw) {
const raw = qRaw.trim().toLowerCase();
state.query = raw;
// Typing a query always searches ALL sets — never silently scoped to one set.
if (raw && (state.activeSet || state.activeCollection)) {
state.activeSet = null;
state.activeCollection = null;
$('scope').textContent = 'All sets';
}
if (!raw && !state.activeSet) { showHome(); return; }
if (!raw) { // browsing a whole set (opened from home)
const s = state.byPrefix.get(state.activeSet);
showResults(s.icons.slice(0, MAX_RESULTS).map((name) => ({ prefix: s.prefix, name })));
return;
}
showResults(searchIcons(state.sets, raw, MAX_RESULTS));
}
let searchTimer;
$('search').addEventListener('input', (e) => {
$('search').parentElement.classList.toggle('hasquery', !!e.target.value);
clearTimeout(searchTimer);
searchTimer = setTimeout(() => runSearch(e.target.value), 160);
});
$('clearsearch').addEventListener('click', () => {
$('search').value = '';
$('search').parentElement.classList.remove('hasquery');
state.activeSet ? runSearch('') : showHome();
$('search').focus();
});
function goHome() {
$('search').value = '';
$('search').parentElement.classList.remove('hasquery');
showHome();
}
$('back').addEventListener('click', goHome);
$('brandhome').addEventListener('click', goHome);
/* ---------- Help overlay ---------- */
function showHelp() { $('helpoverlay').classList.remove('hidden'); }
function hideHelp() {
$('helpoverlay').classList.add('hidden');
state.helpSeen = true;
saveSettings();
}
$('helpbtn').addEventListener('click', showHelp);
$('closehelp').addEventListener('click', hideHelp);
$('helpoverlay').addEventListener('click', (e) => { if (e.target === $('helpoverlay')) hideHelp(); });
/* ---------- Settings persistence ---------- */
function saveSettings() {
window.vault.saveSettings({
color: state.color,
custom: $('custcolor').value,
format: state.format,
pngSize: state.pngSize,
zoom: $('zoom').value,
style: state.style,
collSort: state.collSort || 'recent',
helpSeen: !!state.helpSeen,
});
}
async function restoreSettings() {
const s = await window.vault.loadSettings();
if (!s) return;
state.helpSeen = !!s.helpSeen;
if (s.style) state.style = { ...state.style, ...s.style };
if (s.collSort) state.collSort = s.collSort;
applyStyleUI();
if (s.custom) $('custcolor').value = s.custom;
const swatch = document.querySelector(`.swatch[data-color="${s.color}"]`);
setColor(s.color || 'auto', swatch || $('custcolor'));
setFormat(s.format === 'png' ? 'png' : 'svg');
if (s.pngSize) { state.pngSize = +s.pngSize; $('pngsize').value = s.pngSize; }
if (s.zoom) {
$('zoom').value = s.zoom;
document.documentElement.style.setProperty('--cell', `${s.zoom}px`);
}
}
/* ---------- Grid rendering ---------- */
async function renderNextBatch() {
if (state.rendered >= state.results.length) return;
const gen = state.gen; // drop this batch if a newer search starts while we fetch
const slice = state.results.slice(state.rendered, state.rendered + BATCH);
state.rendered += slice.length;
// group by prefix, fetch missing svgs from the main process
const need = new Map();
for (const it of slice) {
if (!svgCache.has(`${it.prefix}:${it.name}`)) {
if (!need.has(it.prefix)) need.set(it.prefix, []);
need.get(it.prefix).push(it.name);
}
}
await Promise.all([...need.entries()].map(async ([prefix, names]) => {
const out = await window.vault.renderIcons(prefix, names);
for (const [name, svg] of Object.entries(out)) svgCache.set(`${prefix}:${name}`, svg);
}));
if (svgCache.size > 6000) {
const drop = svgCache.size - 5000;
let i = 0;
for (const k of svgCache.keys()) { svgCache.delete(k); if (++i >= drop) break; }
}
if (gen !== state.gen) return; // stale query — a newer search owns the grid now
const frag = document.createDocumentFragment();
for (const it of slice) {
const svg = svgCache.get(`${it.prefix}:${it.name}`);
if (!svg) continue;
const cell = document.createElement('button');
cell.className = 'cell';
cell.draggable = true;
cell.title = `${it.name}\n${state.byPrefix.get(it.prefix)?.name || it.prefix}`;
cell.appendChild(svgElement(svg));
cell.addEventListener('click', () => select(it, cell));
cell.addEventListener('dblclick', () => quickCopy(it));
cell.addEventListener('mousedown', () => prepareDrag(it));
cell.addEventListener('dragstart', (e) => onDragStart(e, it));
frag.appendChild(cell);
}
$('grid').appendChild(frag);
}
new IntersectionObserver((entries) => {
if (entries[0].isIntersecting && state.mode === 'results') renderNextBatch();
}, { root: $('main'), rootMargin: '600px' }).observe($('sentinel'));
/* ---------- Selection panel ---------- */
// Preview shows the icon exactly as it will export (styling applied, theme color).
function refreshPreview() {
if (!state.selected) return;
const svg = svgCache.get(`${state.selected.prefix}:${state.selected.name}`);
if (svg) setSvg($('preview'), composeStyled(svg, state.style));
}
function select(it, cell) {
document.querySelectorAll('.cell.sel').forEach((c) => c.classList.remove('sel'));
cell.classList.add('sel');
state.selected = { ...it };
refreshPreview();
updateFavUI();
$('collmenu').classList.add('hidden');
$('codemenu').classList.add('hidden');
$('iconname').textContent = it.name;
const set = state.byPrefix.get(it.prefix);
$('iconset').textContent = `${set?.name || it.prefix} ›`;
$('iconset').title = `Browse all ${set?.total?.toLocaleString() || ''} icons in ${set?.name || it.prefix}`;
$('iconlicense').textContent = set
? `${set.license || ''}${set.author ? ' · by ' + set.author : ''}`
: '';
$('panel').classList.remove('hidden');
}
// Set name in the panel links to the icon's whole set: same style, all siblings.
$('iconset').addEventListener('click', () => {
if (!state.selected) return;
$('search').value = '';
$('search').parentElement.classList.remove('hasquery');
openSet(state.selected.prefix);
});
$('closepanel').addEventListener('click', () => {
$('panel').classList.add('hidden');
state.selected = null;
document.querySelectorAll('.cell.sel').forEach((c) => c.classList.remove('sel'));
});
/* ---------- Export helpers (shared pipeline lives in iconout.js) ---------- */
function effectiveColor() {
if (state.color !== 'auto') return state.color;
return '#000000'; // auto exports as black; on-screen it follows the theme
}
// The one true export path: color substitution + optional styling (padding/background).
function finalSVG(svg) {
return composeStyled(exportSVG(svg, effectiveColor()), state.style);
}
function finalPNG(svg, size) {
return svgToPNG(finalSVG(svg), size);
}
/* ---------- Copy / Save / Drag ---------- */
function toast(msg) {
const t = $('toast');
t.textContent = msg;
t.classList.remove('hidden');
clearTimeout(t._timer);
t._timer = setTimeout(() => t.classList.add('hidden'), 1600);
}
async function copyIcon(it) {
// Image flavors only (SVG vector + PNG) — visual apps paste the icon, never code.
const svg = svgCache.get(`${it.prefix}:${it.name}`);
const png = await finalPNG(svg, Math.max(state.pngSize, 256));
await window.vault.copyIcon({
svg: finalSVG(svg),
pngDataURL: png,
includeSVG: state.format === 'svg',
});
toast(`Copied ${it.name} — paste into any app`);
}
async function copyCode(it, kind) {
const svg = svgCache.get(`${it.prefix}:${it.name}`);
await window.vault.copyText(buildCode(kind || 'svg', finalSVG(svg), it.name));
toast(`Copied ${it.name} as ${(kind || 'svg').toUpperCase()}`);
}
function quickCopy(it) {
copyIcon(it);
}
async function saveIcon(it) {
const svg = svgCache.get(`${it.prefix}:${it.name}`);
const payload = { name: it.name, format: state.format, svg: finalSVG(svg) };
if (state.format === 'png') payload.pngDataURL = await finalPNG(svg, state.pngSize);
const ok = await window.vault.save(payload);
if (ok) toast(`Saved ${it.name}.${state.format}`);
}
/* ---------- Favorites & collections ---------- */
const iconKey = (it) => `${it.prefix}:${it.name}`;
function persistFavs() {
window.vault.saveFavs(state.favs);
if (state.mode === 'home') buildMySection();
}
function updateFavUI() {
if (!state.selected) return;
const faved = state.favs.favorites.includes(iconKey(state.selected));
$('favbtn').textContent = faved ? '★ Favorited' : '☆ Favorite';
$('favbtn').classList.toggle('faved', faved);
}
$('favbtn').addEventListener('click', () => {
if (!state.selected) return;
const k = iconKey(state.selected);
const i = state.favs.favorites.indexOf(k);
if (i === -1) state.favs.favorites.push(k);
else state.favs.favorites.splice(i, 1);
persistFavs();
updateFavUI();
if (state.activeCollection?.title === 'Favorites') openCollection('Favorites', state.favs.favorites);
toast(i === -1 ? 'Added to Favorites' : 'Removed from Favorites');
});
function buildCollMenu() {
const menu = $('collmenu');
menu.replaceChildren();
const k = state.selected ? iconKey(state.selected) : null;
for (const name of sortedCollNames()) {
const b = document.createElement('button');
const inColl = k && state.favs.collections[name].includes(k);
b.textContent = `${inColl ? '✓ ' : ''}${name}`;
b.addEventListener('click', () => {
const list = state.favs.collections[name];
const i = list.indexOf(k);
if (i === -1) { list.push(k); toast(`Added to “${name}”`); }
else { list.splice(i, 1); toast(`Removed from “${name}”`); }
touchColl(name);
persistFavs();
buildCollMenu();
// live-refresh the view when the icon was removed from the open collection
if (state.activeCollection?.title === name) openCollection(name, list);
});
menu.appendChild(b);
}
const row = document.createElement('div');
row.className = 'newrow';
const input = document.createElement('input');
input.placeholder = 'New collection…';
const add = document.createElement('button');
add.textContent = 'Add';
const create = () => {
const name = input.value.trim();
if (!name || state.favs.collections[name]) return;
state.favs.collections[name] = k ? [k] : [];
touchColl(name);
persistFavs();
buildCollMenu();
toast(`Collection “${name}” created`);
};
add.addEventListener('click', create);
input.addEventListener('keydown', (e) => { if (e.key === 'Enter') create(); });
row.append(input, add);
menu.appendChild(row);
}
$('collbtn').addEventListener('click', () => {
buildCollMenu();
$('collmenu').classList.toggle('hidden');
});
// Dropdowns close when clicking anywhere outside them.
document.addEventListener('click', (e) => {
if (!e.target.closest('#collmenu, #collbtn')) $('collmenu').classList.add('hidden');
if (!e.target.closest('#codemenu, #copycode')) $('codemenu').classList.add('hidden');
if (!e.target.closest('.myrow')) {
document.querySelectorAll('.mymenu').forEach((m) => m.classList.add('hidden'));
}
});
function renameCollection(oldName) {
const nameEl = document.querySelector('#setinfo .sname');
const input = document.createElement('input');
input.className = 'renameinput';
input.value = oldName;
nameEl.replaceWith(input);
input.focus();
input.select();
const commit = () => {
const newName = input.value.trim();
if (newName && newName !== oldName && !state.favs.collections[newName]) {
state.favs.collections[newName] = state.favs.collections[oldName];
delete state.favs.collections[oldName];
if (state.favs.meta) delete state.favs.meta[oldName];
touchColl(newName);
persistFavs();
state.activeCollection.title = newName;
$('scope').textContent = newName;
toast(`Renamed to “${newName}”`);
}
updateSetInfo();
};
input.addEventListener('keydown', (e) => {
if (e.key === 'Enter') commit();
if (e.key === 'Escape') updateSetInfo();
e.stopPropagation();
});
input.addEventListener('blur', commit);
}
function deleteCollection(title) {
if (!confirm(`Delete the collection “${title}”?\nThe icons themselves stay in the library.`)) return;
delete state.favs.collections[title];
if (state.favs.meta) delete state.favs.meta[title];
persistFavs();
toast(`Deleted “${title}”`);
goHome();
}
async function exportCollection() {
if (!state.activeCollection) return;
const items = state.activeCollection.keys.map((k) => {
const [prefix, ...rest] = k.split(':');
return { prefix, name: rest.join(':') };
});
const dir = await window.vault.pickFolder();
if (!dir) return;
// make sure every SVG is in the cache
const need = new Map();
for (const it of items) {
if (!svgCache.has(iconKey(it))) {
if (!need.has(it.prefix)) need.set(it.prefix, []);
need.get(it.prefix).push(it.name);
}
}
await Promise.all([...need.entries()].map(async ([prefix, names]) => {
const out = await window.vault.renderIcons(prefix, names);
for (const [name, svg] of Object.entries(out)) svgCache.set(`${prefix}:${name}`, svg);
}));
const payload = [];
for (const it of items) {
const svg = svgCache.get(iconKey(it));
if (!svg) continue;
const entry = { filename: `${it.prefix}-${it.name}`, format: state.format, svg: finalSVG(svg) };
if (state.format === 'png') entry.pngDataURL = await finalPNG(svg, state.pngSize);
payload.push(entry);
}
const n = await window.vault.exportFiles({ dir, items: payload });
toast(`Exported ${n} icons as ${state.format.toUpperCase()}`);
}
$('copyicon').addEventListener('click', () => state.selected && copyIcon(state.selected));
$('copycode').addEventListener('click', () => $('codemenu').classList.toggle('hidden'));
document.querySelectorAll('#codemenu button').forEach((b) => {
b.addEventListener('click', () => {
if (state.selected) copyCode(state.selected, b.dataset.kind);
$('codemenu').classList.add('hidden');
});
});
/* ---------- Export styling (padding / background) ---------- */
function applyStyleUI() {
document.querySelectorAll('#bgseg button').forEach((b) =>
b.classList.toggle('sel', b.dataset.bg === state.style.bg));
$('bgcolor').value = state.style.bgColor;
$('padslider').value = Math.round(state.style.pad * 100);
}
document.querySelectorAll('#bgseg button').forEach((b) => {
b.addEventListener('click', () => {
state.style.bg = b.dataset.bg;
applyStyleUI(); refreshPreview(); saveSettings();
});
});
$('bgcolor').addEventListener('input', (e) => {
state.style.bgColor = e.target.value;
refreshPreview(); saveSettings();
});
$('padslider').addEventListener('input', (e) => {
state.style.pad = (+e.target.value) / 100;
refreshPreview(); saveSettings();
});
$('saveicon').addEventListener('click', () => state.selected && saveIcon(state.selected));
$('copycredit').addEventListener('click', async () => {
if (!state.selected) return;
const it = state.selected;
const set = state.byPrefix.get(it.prefix);
const parts = [`Icon: "${it.name}" from ${set?.name || it.prefix}`];
if (set?.author) parts.push(`by ${set.author}`);
parts.push(`(${set?.license || 'see set license'})`);
if (set?.licenseUrl) parts.push(set.licenseUrl);
parts.push('— via Iconify');
await window.vault.copyText(parts.join(' '));
toast('Credit line copied');
});
function prepareDrag(it) {
const svg = svgCache.get(`${it.prefix}:${it.name}`);
if (!svg) return;
const size = state.format === 'png' ? state.pngSize : 128;
state.dragPrep = { key: `${it.prefix}:${it.name}`, promise: finalPNG(svg, size).catch(() => null) };
}
async function onDragStart(e, it) {
e.preventDefault(); // hand off to the native (Electron) drag session
const svg = svgCache.get(`${it.prefix}:${it.name}`);
let png = null;
if (state.dragPrep?.key === `${it.prefix}:${it.name}`) png = await state.dragPrep.promise;
if (!png) png = await finalPNG(svg, 128).catch(() => null);
if (!png) return;
window.vault.startDrag({
name: it.name,
format: state.format,
svg: finalSVG(svg),
pngDataURL: png,
});
}
// panel preview is draggable too
$('preview').addEventListener('mousedown', () => state.selected && prepareDrag(state.selected));
$('preview').setAttribute('draggable', 'true');
$('preview').addEventListener('dragstart', (e) => state.selected && onDragStart(e, state.selected));
/* ---------- Bottom controls ---------- */
document.querySelectorAll('.swatch').forEach((sw) => {
sw.addEventListener('click', () => setColor(sw.dataset.color, sw));
});
$('custcolor').addEventListener('input', (e) => setColor(e.target.value, e.target));
function isLightColor(hex) {
const m = (hex || '').match(/^#?([0-9a-f]{6})$/i);
if (!m) return false;
const n = parseInt(m[1], 16);
const lum = 0.299 * (n >> 16) + 0.587 * ((n >> 8) & 255) + 0.114 * (n & 255);
return lum > 186;
}
function setColor(color, el) {
state.color = color;
document.querySelectorAll('.swatch, #custcolor').forEach((s) => s.classList.remove('sel'));
el.classList.add('sel');
document.documentElement.style.setProperty('--icon-color', color === 'auto' ? 'var(--fg)' : color);
document.body.classList.toggle('lightink', color !== 'auto' && isLightColor(color));
saveSettings();
}
$('fmtsvg').addEventListener('click', () => setFormat('svg'));
$('fmtpng').addEventListener('click', () => setFormat('png'));
function setFormat(f) {
state.format = f;
$('fmtsvg').classList.toggle('sel', f === 'svg');
$('fmtpng').classList.toggle('sel', f === 'png');
$('pngsizegroup').style.opacity = f === 'png' ? 1 : 0.45;
saveSettings();
}
$('pngsize').addEventListener('change', (e) => { state.pngSize = +e.target.value; saveSettings(); });
$('zoom').addEventListener('input', (e) => {
document.documentElement.style.setProperty('--cell', `${e.target.value}px`);
saveSettings();
});
/* Keyboard: Esc clears / closes, Cmd+C copies selection */
window.addEventListener('keydown', (e) => {
if (e.key === 'Escape') {
if (!$('manageoverlay').classList.contains('hidden')) $('manageoverlay').classList.add('hidden');
else if (!$('helpoverlay').classList.contains('hidden')) hideHelp();
else if (state.selected) $('closepanel').click();
else if ($('search').value) $('clearsearch').click();
}
if ((e.metaKey || e.ctrlKey) && e.key === 'c' && state.selected && !window.getSelection().toString()) {
e.preventDefault();
quickCopy(state.selected);
}
});