Repository navigation
Expand file tree
/
Copy pathscript.js
More file actions
2596 lines (2267 loc) · 97.9 KB
/
Copy pathscript.js
File metadata and controls
2596 lines (2267 loc) · 97.9 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
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
const colors = [
'#3b82f6', // Blue
'#9333ea', // Purple
'#ef4444', // Red
'#f97316', // Orange
'#10b981', // Emerald
'#06b6d4', // Cyan
'#f59e0b', // Amber
];
const APP_CONFIG = {
shape: { url: 'shape', default: 'circle', type: 'string' },
color: { url: 'color', default: '#3b82f6', type: 'color' },
icon: { url: 'icon', default: 'users', type: 'string' },
baseSize: { url: 'bsize', default: 80, type: 'int' },
badgeSize: { url: 'size', default: 40, type: 'int' },
innerScale: { url: 'scale', default: 70, type: 'int' },
rotation: { url: 'rot', default: 0, type: 'int' },
badgePosition: { url: 'pos', default: 'bottom-right', type: 'string' },
showShadows: { url: 'shadows', default: true, type: 'bool' },
baseShape: { url: 'bshape', default: 'squircle', type: 'string' },
baseColor: { url: 'bcolor', default: '#3b82f6', type: 'color' },
baseColor2: { url: 'bcolor2', default: '#1D0945', type: 'color' },
gradientType: { url: 'gt', default: 'linear', type: 'string' },
gradientAngle: { url: 'ga', default: 135, type: 'int' },
baseText: { url: 'bt', default: 'YOUR TEXT', type: 'string' },
baseTextColor: { url: 'btc', default: '#ffffff', type: 'color' },
baseFrame: { url: 'bf', default: 'none', type: 'string' },
baseNoise: { url: 'bn', default: false, type: 'bool' },
baseGlow: { url: 'bglow', default: false, type: 'bool' },
baseVignette: { url: 'bv', default: false, type: 'bool' },
baseDeepFried: { url: 'bdf', default: false, type: 'bool' },
baseCRT: { url: 'bcrt', default: false, type: 'bool' },
baseMono: { url: 'bm', default: false, type: 'bool' },
baseZoom: { url: 'bz', default: 100, type: 'int' },
baseContentType: { url: 'btype', default: 'image', type: 'string' },
baseIconName: { url: 'bicon', default: 'sparkles', type: 'string' },
baseIconColor: { url: 'biconc', default: '#ffffff', type: 'color' },
baseIconScale: { url: 'bicons', default: 70, type: 'int' },
};
// Initialize state from config defaults
const state = Object.keys(APP_CONFIG).reduce((acc, key) => {
acc[key] = APP_CONFIG[key].default;
return acc;
}, {
customBaseIcon: localStorage.getItem('iconStudio_baseIcon') || null
});
let deferredPrompt = null;
let desktopPromptType = null; // 'chromium' or 'safari'
let suppressHaptic = false;
function syncStateToURL() {
const url = new URL(window.location);
const params = new URLSearchParams(url.search);
const setOrDelete = (urlKey, val, def) => {
let displayVal = val;
let compareDef = def;
// Handle color hex stripping for cleaner URLs
if (urlKey === 'color' || urlKey === 'bcolor' || urlKey === 'bcolor2' || urlKey === 'btc') {
if (typeof val === 'string' && val.startsWith('#')) displayVal = val.slice(1);
if (typeof def === 'string' && def.startsWith('#')) compareDef = def.slice(1);
}
if (displayVal !== undefined && displayVal !== null && String(displayVal) !== String(compareDef)) {
params.set(urlKey, displayVal);
} else {
params.delete(urlKey);
}
};
// Sync all standard config properties
Object.keys(APP_CONFIG).forEach(key => {
const config = APP_CONFIG[key];
setOrDelete(config.url, state[key], config.default);
});
if (document.body.classList.contains('screenshot-mode')) {
params.set('mode', 'screenshot');
} else {
params.delete('mode');
}
if (state.customBaseIcon && state.customBaseIcon.startsWith('http')) {
let displayUrl = state.customBaseIcon;
const prefix = 'https://res.cloudinary.com/rm20abcd26/image/upload/';
if (displayUrl.startsWith(prefix)) {
displayUrl = 'cld:' + displayUrl.replace(prefix, '');
}
params.set('img', displayUrl);
} else {
params.delete('img');
}
const shareUrl = `${window.location.origin}/s/?${params.toString()}`;
const newSearch = params.toString();
const newUrl = window.location.pathname + (newSearch ? '?' + newSearch : '');
// Share button is now always visible via HTML
if (window.location.search !== (newSearch ? '?' + newSearch : '')) {
window.history.replaceState({}, '', newUrl);
}
}
function loadStateFromURL() {
const params = new URLSearchParams(window.location.search);
Object.keys(APP_CONFIG).forEach(key => {
const config = APP_CONFIG[key];
if (params.has(config.url)) {
const val = params.get(config.url);
if (config.type === 'int') {
state[key] = parseInt(val);
} else if (config.type === 'bool') {
state[key] = val === 'true';
} else if (config.type === 'color') {
state[key] = val.startsWith('#') ? val : '#' + val;
} else {
state[key] = val;
}
}
});
if (params.has('img')) {
let val = params.get('img');
if (val.startsWith('cld:')) {
val = 'https://res.cloudinary.com/rm20abcd26/image/upload/' + val.replace('cld:', '');
}
state.customBaseIcon = val;
}
if (!params.has('btype') && !params.has('img')) {
state.baseContentType = 'text';
}
if (params.get('mode') === 'screenshot') {
document.body.classList.add('screenshot-mode');
}
}
function init() {
suppressHaptic = true; // Suppress haptics during initial render/restore
// Detect Standalone Mode (already added to home screen / PWA)
const isStandalone = window.navigator.standalone === true ||
window.matchMedia('(display-mode: standalone)').matches;
if (isStandalone) {
document.body.classList.add('standalone-mode');
}
// Detect touch-primary or touch-emulated devices (like iPad, mobile)
if ('ontouchstart' in window || navigator.maxTouchPoints > 0 || navigator.msMaxTouchPoints > 0) {
document.body.classList.add('touch-device');
}
loadStateFromURL();
// Render colors
const colorContainer = document.getElementById('color-presets');
colors.forEach(c => {
const swatch = document.createElement('div');
swatch.className = 'color-swatch';
swatch.style.backgroundColor = c;
swatch.onclick = () => setColor(c);
if (c === state.color) swatch.classList.add('active');
colorContainer.appendChild(swatch);
});
// Render base icon colors
const baseIconColorContainer = document.getElementById('base-icon-color-presets');
if (baseIconColorContainer) {
colors.forEach(c => {
const swatch = document.createElement('div');
swatch.className = 'color-swatch';
swatch.style.backgroundColor = c;
swatch.onclick = () => setBaseIconColor(c);
if (c === state.baseIconColor) swatch.classList.add('active');
baseIconColorContainer.appendChild(swatch);
});
}
// Initialize visual state
setShape(state.shape);
setColor(state.color);
setIcon(state.icon);
setBaseSize(state.baseSize);
setBadgeSize(state.badgeSize);
setInnerScale(state.innerScale);
setBadgeRotation(state.rotation);
setBadgePosition(state.badgePosition);
toggleShadows(state.showShadows);
setBaseShape(state.baseShape);
setBaseColor1(state.baseColor);
setBaseColor2(state.baseColor2);
setBaseGradientType(state.gradientType);
setBaseGradientAngle(state.gradientAngle);
setBaseText(state.baseText);
setBaseTextColor(state.baseTextColor);
setBaseFrame(state.baseFrame);
setBaseImageZoom(state.baseZoom);
setBaseContentType(state.baseContentType);
setBaseIconName(state.baseIconName);
setBaseIconColor(state.baseIconColor);
setBaseIconScale(state.baseIconScale);
applyBaseEffects();
if (state.customBaseIcon) {
// Clear base text if it's the default "YOUR TEXT" when an image is present
if (state.baseText === APP_CONFIG.baseText.default) {
setBaseText('');
}
document.getElementById('base-img').src = state.customBaseIcon;
document.getElementById('remove-base-icon').style.display = 'flex';
}
updateBaseControls();
lucide.createIcons();
// Disable right-click on the capture area
document.getElementById('capture-area').addEventListener('contextmenu', (e) => e.preventDefault());
// Setup dynamic scaling
window.addEventListener('resize', updateAppScale);
updateAppScale();
// Auto-highlight base icon text on focus and tap/click
const baseIconInputEl = document.getElementById('base-icon-input');
if (baseIconInputEl) {
let preventClearSelection = false;
baseIconInputEl.addEventListener('focus', function () {
showBaseIconSuggestions();
preventClearSelection = true;
setTimeout(() => {
this.select();
}, 0);
});
baseIconInputEl.addEventListener('click', function () {
showBaseIconSuggestions();
});
baseIconInputEl.addEventListener('mouseup', function (e) {
if (preventClearSelection) {
e.preventDefault();
preventClearSelection = false;
}
});
baseIconInputEl.addEventListener('touchend', function (e) {
if (preventClearSelection) {
e.preventDefault();
preventClearSelection = false;
}
});
// Hide dropdown when clicking outside
document.addEventListener('click', function (e) {
const dropdown = document.getElementById('base-icon-dropdown');
if (dropdown && !baseIconInputEl.contains(e.target) && !dropdown.contains(e.target)) {
dropdown.classList.remove('active');
baseIconInputEl.setAttribute('aria-expanded', 'false');
baseIconSelectedIndex = -1;
}
});
}
// Subtle feedback for character limit
const baseTextInput = document.getElementById('base-text-input');
if (baseTextInput) {
baseTextInput.addEventListener('keydown', (e) => {
// If at limit and typing a normal character (length 1)
if (baseTextInput.value.length >= 30 && e.key.length === 1 && !e.ctrlKey && !e.metaKey) {
baseTextInput.classList.remove('shake');
void baseTextInput.offsetWidth; // Trigger reflow
baseTextInput.classList.add('shake');
}
});
}
// Setup Drag and Drop + Paste
setupDragAndDrop();
setupPaste();
// Sticky Mobile Preview logic
setupStickyMobilePreview();
// Set canonical URL to the clean root path so that macOS/iOS Safari "Add to Dock/Home Screen" uses a parameter-free URL
let canonical = document.querySelector('link[rel="canonical"]');
if (!canonical) {
canonical = document.createElement('link');
canonical.rel = 'canonical';
document.head.appendChild(canonical);
}
canonical.href = window.location.origin + window.location.pathname;
// PWA & iOS Custom Installer Prompts initialization
registerServiceWorker();
initIosPwaPrompt();
initDesktopPwaPrompt();
suppressHaptic = false; // Restore haptics after load
}
function setupStickyMobilePreview() {
const previewSection = document.querySelector('.preview-section');
if (!previewSection) return;
// Reset old sticky variables to ensure clean slate
document.documentElement.style.removeProperty('--sticky-scale');
document.documentElement.style.removeProperty('--sticky-opacity');
document.documentElement.style.removeProperty('--sticky-pointer');
document.documentElement.style.removeProperty('--sticky-margin');
document.documentElement.style.removeProperty('--sticky-actions-h');
document.documentElement.style.removeProperty('--sticky-actions-m');
previewSection.style.paddingTop = '';
previewSection.style.paddingBottom = '';
// Set up ResizeObserver to track exact height of preview-section
const resizeObserver = new ResizeObserver(entries => {
for (let entry of entries) {
const height = entry.target.clientHeight;
document.documentElement.style.setProperty('--preview-height', `${height}px`);
if (!document.body.classList.contains('scrolled')) {
document.documentElement.style.setProperty('--non-shrunk-height', `${height}px`);
}
}
});
resizeObserver.observe(previewSection);
function handleMobileScroll() {
if (window.innerWidth <= 1150) {
const scrollY = window.scrollY;
const maxScroll = 80;
const scrollProgress = Math.min(1, Math.max(0, scrollY / maxScroll));
document.documentElement.style.setProperty('--scroll-progress', scrollProgress);
if (scrollY > 40) {
if (!document.body.classList.contains('scrolled')) {
document.body.classList.add('scrolled');
}
} else {
document.body.classList.remove('scrolled');
}
} else {
document.body.classList.remove('scrolled');
document.documentElement.style.setProperty('--scroll-progress', 0);
}
}
window.addEventListener('scroll', handleMobileScroll, { passive: true });
window.addEventListener('resize', handleMobileScroll, { passive: true });
handleMobileScroll();
}
function updateAppScale() {
const container = document.getElementById('tool-container');
if (!container || document.body.classList.contains('screenshot-mode')) {
document.documentElement.style.setProperty('--app-scale', '1');
return;
}
const isMobile = window.innerWidth <= 1150;
if (isMobile) {
if (window.innerWidth < 450) {
const scale = (window.innerWidth - 20) / 420;
document.documentElement.style.setProperty('--app-scale', Math.max(0.85, Math.min(1, scale)));
} else {
document.documentElement.style.setProperty('--app-scale', '1');
}
return;
}
// Full-screen desktop scaling: focuses on content density with 600px canvas
const targetWidth = 1400;
let scale = window.innerWidth / targetWidth;
// Clamp scale: keep UI comfortable and readable
scale = Math.min(Math.max(scale, 0.75), 1.25);
document.documentElement.style.setProperty('--app-scale', scale);
// Ensure text and badges scale correctly on resize now that we use px-based font sizing
updateBasePreview();
if (state.icon && !document.querySelector('#badge-icon-target svg')) {
setIcon(state.icon, false);
}
}
let ALL_ICONS = [
'users', 'user', 'settings', 'mail', 'bell', 'search', 'home', 'star', 'heart', 'check', 'x', 'plus', 'minus',
'upload-cloud', 'download', 'maximize', 'share-2', 'external-link', 'copy', 'trash-2', 'upload', 'sliders',
'chevron-down', 'refresh-cw', 'info', 'shield', 'camera', 'image', 'lock', 'key', 'edit-3', 'trash', 'save',
'download-cloud', 'share', 'link', 'calendar', 'clock', 'battery', 'wifi', 'globe', 'headphones', 'megaphone',
'play', 'pause', 'stop', 'film', 'music', 'video', 'map-pin', 'flag', 'bookmark', 'book-open', 'shopping-cart',
'credit-card', 'gift', 'anchor', 'rocket', 'sun', 'moon', 'cloud', 'leaf', 'fire', 'thumbs-up', 'thumbs-down',
'battery-charging', 'battery', 'download-cloud', 'upload-cloud', 'brush', 'palette', 'layers'
];
async function fetchIconList() {
// Local icon list is already populated to avoid unnecessary network dependencies.
return;
}
function handleIconInput(val) {
setIcon(val, false);
filterSuggestions(val);
}
function showSuggestions() {
const dropdown = document.getElementById('icon-dropdown');
dropdown.classList.add('active');
const input = document.getElementById('icon-input');
if (input) input.setAttribute('aria-expanded', 'true');
filterSuggestions(input.value);
}
let selectedIndex = -1;
function filterSuggestions(val) {
const dropdown = document.getElementById('icon-dropdown');
const query = val.toLowerCase();
const filtered = ALL_ICONS
.filter(icon => icon.includes(query))
.sort((a, b) => {
// 1. Exact match first
if (a === query) return -1;
if (b === query) return 1;
// 2. Starts with query second
const aStarts = a.startsWith(query);
const bStarts = b.startsWith(query);
if (aStarts && !bStarts) return -1;
if (bStarts && !aStarts) return 1;
// 3. Alphabetical otherwise
return a.localeCompare(b);
})
.slice(0, 48);
if (filtered.length === 0) {
dropdown.classList.remove('active');
const input = document.getElementById('icon-input');
if (input) input.setAttribute('aria-expanded', 'false');
selectedIndex = -1;
return;
}
dropdown.innerHTML = filtered.map((icon, idx) => `
<div class="dropdown-item ${idx === selectedIndex ? 'selected' : ''}" onclick="setIcon('${icon}')" title="${icon}" data-index="${idx}">
<i data-lucide="${icon}"></i>
</div>
`).join('');
dropdown.classList.add('active');
const input = document.getElementById('icon-input');
if (input) input.setAttribute('aria-expanded', 'true');
lucide.createIcons();
}
// Auto-highlight text on focus and tap/click
const iconInputEl = document.getElementById('icon-input');
if (iconInputEl) {
let preventClearSelection = false;
iconInputEl.addEventListener('focus', function () {
showSuggestions();
preventClearSelection = true;
setTimeout(() => {
this.select();
}, 0);
});
iconInputEl.addEventListener('click', function () {
showSuggestions();
});
iconInputEl.addEventListener('mouseup', function (e) {
if (preventClearSelection) {
e.preventDefault();
preventClearSelection = false;
}
});
iconInputEl.addEventListener('touchend', function (e) {
if (preventClearSelection) {
e.preventDefault();
preventClearSelection = false;
}
});
}
// Keyboard navigation
document.getElementById('icon-input').addEventListener('keydown', (e) => {
const dropdown = document.getElementById('icon-dropdown');
const items = dropdown.querySelectorAll('.dropdown-item');
if (!dropdown.classList.contains('active') || items.length === 0) {
if (e.key === 'ArrowDown') showSuggestions();
return;
}
if (e.key === 'ArrowDown') {
e.preventDefault();
selectedIndex = (selectedIndex + 1) % items.length;
updateSelection(items);
} else if (e.key === 'ArrowUp') {
e.preventDefault();
selectedIndex = (selectedIndex - 1 + items.length) % items.length;
updateSelection(items);
} else if (e.key === 'Enter') {
if (selectedIndex >= 0) {
e.preventDefault();
const iconName = items[selectedIndex].title;
setIcon(iconName);
}
} else if (e.key === 'Escape') {
dropdown.classList.remove('active');
e.target.setAttribute('aria-expanded', 'false');
}
});
function updateSelection(items) {
items.forEach((item, idx) => {
item.classList.toggle('selected', idx === selectedIndex);
if (idx === selectedIndex) {
item.scrollIntoView({ block: 'nearest' });
}
});
}
// Close dropdown when clicking outside
document.addEventListener('click', (e) => {
if (!e.target.closest('.icon-picker-wrapper')) {
const dropdown = document.getElementById('icon-dropdown');
if (dropdown) dropdown.classList.remove('active');
const input = document.getElementById('icon-input');
if (input) input.setAttribute('aria-expanded', 'false');
}
});
function updateRemoveButtonVisibility() {
const btn = document.getElementById('remove-base-icon');
if (state.customBaseIcon) {
btn.style.display = 'flex';
} else {
btn.style.display = 'none';
}
}
function updateBaseControls() {
const type = state.baseContentType || 'image';
const hasCustomIcon = !!state.customBaseIcon;
const gradientControls = document.getElementById('base-gradient-controls');
const imageControls = document.getElementById('base-image-controls');
if (type === 'image') {
if (gradientControls) gradientControls.classList.toggle('hidden', hasCustomIcon);
if (imageControls) imageControls.classList.toggle('hidden', !hasCustomIcon);
} else {
// Text or Icon: always show gradient controls, hide image controls
if (gradientControls) gradientControls.classList.remove('hidden');
if (imageControls) imageControls.classList.add('hidden');
}
}
function setBaseImageZoom(v) {
state.baseZoom = v;
const valEl = document.getElementById('base-zoom-val');
const input = document.getElementById('base-zoom-input');
const img = document.getElementById('base-img');
if (valEl) valEl.innerText = v;
if (input) input.value = v;
if (img) {
img.style.transform = `scale(${v / 100})`;
}
syncStateToURL();
}
function setShape(s) {
triggerHaptic();
state.shape = s;
const shapeEl = document.getElementById('badge-shape');
const iconEl = document.getElementById('badge-icon-target');
shapeEl.className = 'badge-shape ' + s;
// Special scaling for diamond to fit icons better
iconEl.classList.toggle('diamond-scaling', s === 'diamond');
const select = document.getElementById('badge-shape-select');
if (select) select.value = s;
document.querySelectorAll('.shape-btn').forEach(btn => {
if (btn.dataset.shape) btn.classList.toggle('active', btn.dataset.shape === s);
});
syncStateToURL();
}
function setBaseContentType(type) {
triggerHaptic();
state.baseContentType = type;
// Toggle active state on buttons
document.querySelectorAll('[data-base-content-type]').forEach(btn => {
btn.classList.toggle('active', btn.dataset.baseContentType === type);
});
// Update visibility of control groups
const imageUploadGroup = document.getElementById('base-image-upload-group');
const imageControls = document.getElementById('base-image-controls');
const textControls = document.getElementById('base-text-controls');
const iconControls = document.getElementById('base-icon-controls');
if (imageUploadGroup) imageUploadGroup.style.display = type === 'image' ? 'block' : 'none';
if (imageControls) imageControls.style.display = type === 'image' ? 'block' : 'none';
if (textControls) textControls.style.display = type === 'text' ? 'block' : 'none';
if (iconControls) iconControls.style.display = type === 'icon' ? 'block' : 'none';
updateBasePreview();
updateBaseBackground();
updateBaseControls();
syncStateToURL();
}
function setBaseShape(s) {
triggerHaptic();
state.baseShape = s;
const shapes = ['square', 'squircle', 'roundrect', 'circle'];
const elements = [
document.getElementById('base-img'),
document.getElementById('base-bg'),
document.getElementById('base-frame'),
document.getElementById('base-effects'),
document.getElementById('base-overlay')
];
elements.forEach(el => {
if (!el) return;
shapes.forEach(sh => el.classList.remove(sh));
el.classList.add(s);
});
document.querySelectorAll('[data-base-shape]').forEach(btn => {
btn.classList.toggle('active', btn.dataset.baseShape === s);
});
syncStateToURL();
}
function setBaseFrame(f) {
triggerHaptic();
state.baseFrame = f;
const frame = document.getElementById('base-frame');
const bg = document.getElementById('base-bg');
if (frame) {
frame.className = `base-frame ${f} ${state.baseShape}`;
frame.style.display = f === 'none' ? 'none' : 'block';
}
if (bg) {
// Remove existing frame classes
bg.classList.forEach(cls => {
if (cls.startsWith('frame-')) bg.classList.remove(cls);
});
if (f !== 'none') bg.classList.add('frame-' + f);
}
document.querySelectorAll('[data-base-frame]').forEach(btn => {
btn.classList.toggle('active', btn.dataset.baseFrame === f);
});
updateBaseBackground();
syncStateToURL();
}
function toggleBaseEffect(eff) {
triggerHaptic();
if (eff === 'noise') state.baseNoise = !state.baseNoise;
if (eff === 'glow') state.baseGlow = !state.baseGlow;
if (eff === 'vignette') state.baseVignette = !state.baseVignette;
if (eff === 'deep-fried') state.baseDeepFried = !state.baseDeepFried;
if (eff === 'crt') state.baseCRT = !state.baseCRT;
if (eff === 'mono') state.baseMono = !state.baseMono;
applyBaseEffects();
syncStateToURL();
}
function applyBaseEffects() {
const base = document.getElementById('base-bg');
const effects = document.getElementById('base-effects');
const overlay = document.getElementById('base-overlay');
if (effects) {
effects.classList.toggle('effect-glow', state.baseGlow);
effects.classList.toggle('effect-vignette', state.baseVignette);
effects.classList.toggle('effect-crt', state.baseCRT);
}
if (overlay) {
overlay.classList.toggle('noise', state.baseNoise);
}
if (base) {
base.classList.toggle('effect-deep-fried', state.baseDeepFried);
base.classList.toggle('effect-monochrome', state.baseMono);
}
// Update button active states
document.getElementById('effect-noise').classList.toggle('active', state.baseNoise);
document.getElementById('effect-glow').classList.toggle('active', state.baseGlow);
document.getElementById('effect-vignette').classList.toggle('active', state.baseVignette);
document.getElementById('effect-deep-fried').classList.toggle('active', state.baseDeepFried);
document.getElementById('effect-crt').classList.toggle('active', state.baseCRT);
document.getElementById('effect-mono').classList.toggle('active', state.baseMono);
}
function setBaseColor1(c) {
state.baseColor = c;
const picker = document.getElementById('base-bg-color-1');
if (picker) {
picker.value = c;
picker.parentElement.style.setProperty('--swatch-color', c);
}
updateBaseBackground();
updateBaseIconFilter();
syncStateToURL();
}
function setBaseColor2(c) {
state.baseColor2 = c;
const picker = document.getElementById('base-bg-color-2');
if (picker) {
picker.value = c;
picker.parentElement.style.setProperty('--swatch-color', c);
}
updateBaseBackground();
syncStateToURL();
}
function setBaseGradientType(t) {
triggerHaptic();
state.gradientType = t;
// Update active state for buttons
document.querySelectorAll('[data-grad-type]').forEach(btn => {
btn.classList.toggle('active', btn.dataset.gradType === t);
});
const angleGroup = document.getElementById('base-angle-group');
if (angleGroup) {
angleGroup.classList.toggle('hidden', !(t === 'linear' || t === 'conic'));
}
updateBaseBackground();
syncStateToURL();
}
function setBaseGradientAngle(a) {
state.gradientAngle = a;
const val = document.getElementById('base-angle-val');
const input = document.getElementById('base-angle-input');
if (val) val.innerText = a;
if (input) input.value = a;
updateBaseBackground();
syncStateToURL();
}
function setBaseText(val) {
state.baseText = val;
const input = document.getElementById('base-text-input');
if (input) input.value = val;
const countEl = document.getElementById('base-text-count');
if (countEl) {
countEl.innerText = `${val.length}/30`;
countEl.classList.toggle('at-limit', val.length >= 30);
}
const textColorUi = document.getElementById('base-text-color-ui');
if (textColorUi) {
if (val.trim() !== '') {
textColorUi.style.display = 'flex';
} else {
textColorUi.style.display = 'none';
}
}
updateBasePreview();
syncStateToURL();
}
function setBaseTextColor(color) {
state.baseTextColor = color;
const picker = document.getElementById('base-text-color');
const ui = document.getElementById('base-text-color-ui');
if (picker) picker.value = color;
if (ui) ui.style.setProperty('--swatch-color', color);
updateBasePreview();
syncStateToURL();
}
function setBaseIconName(name, shouldHideDropdown = true) {
triggerHaptic();
if (shouldHideDropdown) {
const dropdown = document.getElementById('base-icon-dropdown');
if (dropdown) dropdown.classList.remove('active');
baseIconSelectedIndex = -1;
}
state.baseIconName = name;
const input = document.getElementById('base-icon-input');
if (input) input.value = name;
// Update preview
updateBasePreview();
syncStateToURL();
}
function setBaseIconColor(color) {
state.baseIconColor = color;
const customColorInput = document.getElementById('base-icon-color');
if (customColorInput) customColorInput.value = color;
const customColorUi = document.getElementById('base-icon-color-ui');
if (customColorUi) customColorUi.style.setProperty('--swatch-color', color);
let matchedPreset = false;
document.querySelectorAll('#base-icon-color-presets .color-swatch').forEach(sw => {
const isActive = sw.style.backgroundColor === color || sw.style.backgroundColor.toLowerCase() === color.toLowerCase();
sw.classList.toggle('active', isActive);
if (isActive) matchedPreset = true;
});
if (customColorUi) customColorUi.classList.toggle('active', !matchedPreset);
// Update preview
updateBasePreview();
syncStateToURL();
}
function setBaseIconScale(scale) {
state.baseIconScale = parseInt(scale);
const valEl = document.getElementById('base-icon-scale-val');
if (valEl) valEl.innerText = scale;
const input = document.getElementById('base-icon-scale-input');
if (input) input.value = scale;
// Update preview
updateBasePreview();
syncStateToURL();
}
let baseIconSelectedIndex = -1;
function handleBaseIconInput(val) {
setBaseIconName(val, false);
filterBaseIconSuggestions(val);
}
function showBaseIconSuggestions() {
const dropdown = document.getElementById('base-icon-dropdown');
if (!dropdown) return;
dropdown.classList.add('active');
const input = document.getElementById('base-icon-input');
if (input) input.setAttribute('aria-expanded', 'true');
filterBaseIconSuggestions(input.value);
}
function filterBaseIconSuggestions(val) {
const dropdown = document.getElementById('base-icon-dropdown');
if (!dropdown) return;
const query = val.toLowerCase();
const filtered = ALL_ICONS
.filter(icon => icon.includes(query))
.sort((a, b) => {
if (a === query) return -1;
if (b === query) return 1;
const aStarts = a.startsWith(query);
const bStarts = b.startsWith(query);
if (aStarts && !bStarts) return -1;
if (bStarts && !aStarts) return 1;
return a.localeCompare(b);
})
.slice(0, 48);
if (filtered.length === 0) {
dropdown.classList.remove('active');
const input = document.getElementById('base-icon-input');
if (input) input.setAttribute('aria-expanded', 'false');
baseIconSelectedIndex = -1;
return;
}
dropdown.innerHTML = filtered.map((icon, idx) => `
<div class="dropdown-item ${idx === baseIconSelectedIndex ? 'selected' : ''}" onclick="setBaseIconName('${icon}')" title="${icon}" data-index="${idx}">
<i data-lucide="${icon}"></i>
</div>
`).join('');
dropdown.classList.add('active');
const input = document.getElementById('base-icon-input');
if (input) input.setAttribute('aria-expanded', 'true');
lucide.createIcons();
}
function calculateDynamicFontSize(text, canvasWidth) {
const textLength = text.length;
const words = text.split(/\s+/);
const longestWordLength = Math.max(...words.map(w => w.length));
// charFactor determines how "tightly" we fit the characters.
const charFactor = 0.85;
// Calculate font size as a percentage of the container width
// A base of 20 is more balanced for icon design than the previous 25
let fontSizeBase = Math.min(20, 20 / (longestWordLength * charFactor / 4));
const maxTotalFontSize = (20 * 3.5) / (textLength * charFactor / 4);
fontSizeBase = Math.min(fontSizeBase, maxTotalFontSize);
// Scale by the user's baseSize setting
fontSizeBase = fontSizeBase * (state.baseSize / 80);
// Minimum legible size
if (fontSizeBase < 4) fontSizeBase = 4;
// Convert percentage to actual pixels
return (fontSizeBase * canvasWidth) / 100;
}
function updateBasePreview() {
const imgEl = document.getElementById('base-img');
const textEl = document.getElementById('base-text');
const baseIconEl = document.getElementById('base-icon-target');
const type = state.baseContentType || 'image';
if (imgEl) imgEl.style.display = 'none';
if (textEl) textEl.style.display = 'none';
if (baseIconEl) baseIconEl.style.display = 'none';
if (type === 'image') {
const hasCustomIcon = !!state.customBaseIcon;
if (hasCustomIcon && imgEl) {
imgEl.style.display = 'block';
if (imgEl.src !== state.customBaseIcon) {
imgEl.src = state.customBaseIcon;
}
}
} else if (type === 'text') {
const hasText = state.baseText && state.baseText.trim() !== '';
if (hasText && textEl) {
textEl.style.display = 'flex';
const textToShow = state.baseText;
textEl.innerText = textToShow;
textEl.style.color = state.baseTextColor;
const canvas = document.getElementById('icon-canvas');
const canvasWidth = canvas ? canvas.offsetWidth : 320;
const fontSizePx = calculateDynamicFontSize(textToShow, canvasWidth);
textEl.style.fontSize = fontSizePx + 'px';
textEl.style.lineHeight = '0.95';
const shadow = state.showShadows ? '0 10px 15px rgba(0,0,0,0.3)' : 'none';
textEl.style.textShadow = shadow;
}
} else if (type === 'icon') {
if (baseIconEl) {
baseIconEl.style.display = 'flex';
const name = state.baseIconName || 'sparkles';
baseIconEl.innerHTML = `<i data-lucide="${name}"></i>`;
lucide.createIcons();
const scale = state.baseIconScale || 70;
baseIconEl.style.setProperty('--base-icon-size', scale + '%');
baseIconEl.style.setProperty('--base-icon-color', state.baseIconColor || '#ffffff');
}
}
}
function updateBaseBackground() {
const bg = document.getElementById('base-bg');
if (!bg) return;
// If there's a custom icon and we are in image mode, hide the background gradient
const type = state.baseContentType || 'image';
if (type === 'image' && state.customBaseIcon) {
bg.style.background = 'transparent';
return;
}
let color1 = state.baseColor;
let color2 = state.baseColor2;
// Apply transparency for glass mode
if (state.baseFrame === 'glass') {