-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathapp.js
More file actions
2126 lines (1863 loc) · 90.1 KB
/
Copy pathapp.js
File metadata and controls
2126 lines (1863 loc) · 90.1 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
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
// Image Converter Pro - Main Application Logic
class ImageConverter {
constructor() {
this.images = [];
this.convertedImages = [];
this.currentPreset = 'none';
this.presetSizes = this.initializePresets();
this.userPresets = this.loadUserPresets();
this.conversionHistory = this.loadHistory();
this.customSizesList = []; // User-defined custom sizes
this.editingSizeIndex = null; // Index of size being edited
this.initializeElements();
this.setupEventListeners();
this.checkFormatSupport();
this.setupKeyboardShortcuts();
this.loadThemePreference();
}
initializePresets() {
return {
'none': [],
'custom-list': [], // Custom size list - user builds this
'logo': [
{ width: 512, height: 512, name: '512x512' },
{ width: 256, height: 256, name: '256x256' },
{ width: 128, height: 128, name: '128x128' },
{ width: 64, height: 64, name: '64x64' },
{ width: 32, height: 32, name: '32x32' }
],
'favicon': [
{ width: 16, height: 16, name: '16x16' },
{ width: 32, height: 32, name: '32x32' },
{ width: 48, height: 48, name: '48x48' },
{ width: 64, height: 64, name: '64x64' }
],
'android': [
{ width: 48, height: 48, name: 'mdpi_48x48' },
{ width: 72, height: 72, name: 'hdpi_72x72' },
{ width: 96, height: 96, name: 'xhdpi_96x96' },
{ width: 144, height: 144, name: 'xxhdpi_144x144' },
{ width: 192, height: 192, name: 'xxxhdpi_192x192' },
{ width: 512, height: 512, name: 'playstore_512x512' }
],
'ios': [
{ width: 60, height: 60, name: '60x60' },
{ width: 120, height: 120, name: '120x120' },
{ width: 180, height: 180, name: '180x180' },
{ width: 1024, height: 1024, name: 'appstore_1024x1024' }
],
'social': [
{ width: 1080, height: 1080, name: 'instagram_1080x1080' },
{ width: 1200, height: 630, name: 'facebook_1200x630' },
{ width: 1280, height: 720, name: 'youtube_1280x720' },
{ width: 1200, height: 675, name: 'twitter_1200x675' }
],
'all': [
{ width: 512, height: 512, name: '512x512' },
{ width: 256, height: 256, name: '256x256' },
{ width: 128, height: 128, name: '128x128' },
{ width: 64, height: 64, name: '64x64' },
{ width: 32, height: 32, name: '32x32' },
{ width: 16, height: 16, name: '16x16' },
{ width: 1024, height: 1024, name: '1024x1024' },
{ width: 192, height: 192, name: '192x192' },
{ width: 180, height: 180, name: '180x180' },
{ width: 144, height: 144, name: '144x144' },
{ width: 120, height: 120, name: '120x120' },
{ width: 96, height: 96, name: '96x96' },
{ width: 72, height: 72, name: '72x72' },
{ width: 60, height: 60, name: '60x60' },
{ width: 48, height: 48, name: '48x48' }
]
};
}
initializeElements() {
this.uploadArea = document.getElementById('uploadArea');
this.fileInput = document.getElementById('fileInput');
this.mainDashboard = document.getElementById('mainDashboard');
this.imagesGridSection = document.getElementById('imagesGridSection');
this.gridContainer = document.getElementById('gridContainer');
this.progressSection = document.getElementById('progressSection');
this.progressContainer = document.getElementById('progressContainer');
this.resultsSection = document.getElementById('resultsSection');
this.resultsContainer = document.getElementById('resultsContainer');
this.convertBtn = document.getElementById('convertBtn');
this.clearBtn = document.getElementById('clearBtn');
this.downloadAllBtn = document.getElementById('downloadAllBtn');
this.outputFormat = document.getElementById('outputFormat');
this.quality = document.getElementById('quality');
this.qualityValue = document.getElementById('qualityValue');
this.resizeMode = document.getElementById('resizeMode');
this.resizeWidth = document.getElementById('resizeWidth');
this.resizeHeight = document.getElementById('resizeHeight');
this.resizeDimensions = document.getElementById('resizeDimensions');
this.keepAspectRatio = document.getElementById('keepAspectRatio');
this.preserveTransparency = document.getElementById('preserveTransparency');
this.removeMetadata = document.getElementById('removeMetadata');
this.zipFormat = document.getElementById('zipFormat');
this.presetButtons = document.querySelectorAll('.preset-btn');
this.presetInfo = document.getElementById('presetInfo');
this.autoSharpening = document.getElementById('autoSharpening');
this.resizeType = document.getElementById('resizeType');
this.pixelDimensions = document.getElementById('pixelDimensions');
this.percentageDimensions = document.getElementById('percentageDimensions');
this.resizePercentage = document.getElementById('resizePercentage');
this.percentageValue = document.getElementById('percentageValue');
this.customNaming = document.getElementById('customNaming');
this.customNamingPattern = document.getElementById('customNamingPattern');
this.folderImport = document.getElementById('folderImport');
this.themeToggle = document.getElementById('themeToggle');
this.themeIcon = this.themeToggle?.querySelector('.theme-icon');
this.imageCount = document.getElementById('imageCount');
this.shortcutsBtn = document.getElementById('shortcutsBtn');
this.shortcutsPanel = document.getElementById('shortcutsPanel');
this.presetModal = document.getElementById('presetModal');
this.presetName = document.getElementById('presetName');
this.savePresetConfirmBtn = document.getElementById('savePresetConfirmBtn');
this.cancelPresetBtn = document.getElementById('cancelPresetBtn');
// Background groups and others might be missing in new HTML, handle gracefully
this.backgroundColorGroup = document.getElementById('backgroundColorGroup') || { style: {} };
this.backgroundColor = document.getElementById('backgroundColor') || { value: '#ffffff' };
// Critical: Initialize potentially missing elements to null if not found
this.folderInput = document.getElementById('folderInput');
this.convertMultipleFormats = document.getElementById('convertMultipleFormats');
this.formatOptions = document.querySelectorAll('.format-option');
this.autoPadding = document.getElementById('autoPadding');
this.autoBackground = document.getElementById('autoBackground');
this.cropShape = document.getElementById('cropShape');
this.dpi = document.getElementById('dpi');
// Resize and advanced options groups
this.maxFileSizeGroup = document.getElementById('maxFileSizeGroup');
this.maxDimensionsGroup = document.getElementById('maxDimensionsGroup');
this.zipOptionsGroup = document.getElementById('zipOptionsGroup');
this.formatSelection = document.querySelector('.format-selection') || { style: {} };
this.customSizeListSection = document.getElementById('customSizeListSection');
this.advancedOptions = document.getElementById('advancedOptions');
// Missing inputs
this.maxFileSize = document.getElementById('maxFileSize');
this.maxWidth = document.getElementById('maxWidth');
this.maxHeight = document.getElementById('maxHeight');
// New Background Fill Elements
this.backgroundFillMode = document.getElementById('backgroundFillMode');
this.bgColorControls = document.getElementById('bgColorControls');
this.bgImageControls = document.getElementById('bgImageControls');
this.bgImageInput = document.getElementById('bgImageInput');
this.bgImageBtn = document.getElementById('bgImageBtn');
this.bgImagePreview = document.getElementById('bgImagePreview');
this.customBgImage = null; // Store the uploaded background image object
// Button groups
this.percentButtons = document.querySelectorAll('.percent-btn');
this.bgPresetButtons = document.querySelectorAll('.bg-preset-btn');
// Custom Size List UI
this.customSizesListContainer = document.getElementById('customSizesListContainer');
this.addSizeBtn = document.getElementById('addSizeBtn');
this.newSizeWidth = document.getElementById('newSizeWidth');
this.newSizeHeight = document.getElementById('newSizeHeight');
this.newSizeKeepAspect = document.getElementById('newSizeKeepAspect');
this.clearSizeListBtn = document.getElementById('clearSizeListBtn');
this.saveSizeListPresetBtn = document.getElementById('saveSizeListPresetBtn');
// Edit Modal UI
this.editSizeModal = document.getElementById('editSizeModal');
this.editSizeWidth = document.getElementById('editSizeWidth');
this.editSizeHeight = document.getElementById('editSizeHeight');
this.editSizeFormat = document.getElementById('editSizeFormat');
this.editSizeQuality = document.getElementById('editSizeQuality');
this.editQualityValue = document.getElementById('editQualityValue');
this.editSizeKeepAspect = document.getElementById('editSizeKeepAspect');
this.editSizeBackground = document.getElementById('editSizeBackground');
this.editSizeResizeMode = document.getElementById('editSizeResizeMode');
this.saveSizeEditBtn = document.getElementById('saveSizeEditBtn');
this.cancelSizeEditBtn = document.getElementById('cancelSizeEditBtn');
// Extra buttons
this.savePresetBtn = document.getElementById('savePresetBtn');
this.historyBtn = document.getElementById('historyBtn');
this.clearHistoryBtn = document.getElementById('clearHistoryBtn');
this.historySection = document.getElementById('historySection');
// User Presets (Missing in HTML)
this.userPresetsList = document.getElementById('userPresetsList');
this.userPresetsSection = document.getElementById('userPresetsSection');
// Settings Panel (Class in HTML)
this.settingsPanel = document.querySelector('.settings-panel');
this.imagesGrid = document.querySelector('.images-grid') || document.getElementById('imagesGridSection');
// Watermark Controls
this.addWatermark = document.getElementById('addWatermark');
this.watermarkSettings = document.getElementById('watermarkSettings');
this.watermarkText = document.getElementById('watermarkText');
this.watermarkColor = document.getElementById('watermarkColor');
this.watermarkOpacity = document.getElementById('watermarkOpacity');
this.watermarkOpacityValue = document.getElementById('watermarkOpacityValue');
this.watermarkOpacityValue = document.getElementById('watermarkOpacityValue');
this.watermarkPosition = document.getElementById('watermarkPosition');
// Image Filters
this.filterBrightness = document.getElementById('filterBrightness');
this.filterContrast = document.getElementById('filterContrast');
this.filterSaturation = document.getElementById('filterSaturation');
this.filterWarmth = document.getElementById('filterWarmth');
this.filterSharpening = document.getElementById('filterSharpening');
this.filterGrayscale = document.getElementById('filterGrayscale');
this.filterSepia = document.getElementById('filterSepia');
this.brightnessValue = document.getElementById('brightnessValue');
this.contrastValue = document.getElementById('contrastValue');
this.saturationValue = document.getElementById('saturationValue');
this.warmthValue = document.getElementById('warmthValue');
this.sharpeningValue = document.getElementById('sharpeningValue');
// Notifications
this.toastContainer = document.getElementById('toastContainer');
}
initializePresets() {
return {
'none': [],
'custom-list': [], // Custom size list - user builds this
'logo': [
{ width: 512, height: 512, name: '512x512' },
{ width: 256, height: 256, name: '256x256' },
{ width: 128, height: 128, name: '128x128' },
{ width: 64, height: 64, name: '64x64' },
{ width: 32, height: 32, name: '32x32' }
],
'favicon': [
{ width: 16, height: 16, name: '16x16' },
{ width: 32, height: 32, name: '32x32' },
{ width: 48, height: 48, name: '48x48' },
{ width: 64, height: 64, name: '64x64' }
],
'android': [
{ width: 48, height: 48, name: 'mdpi_48x48' },
{ width: 72, height: 72, name: 'hdpi_72x72' },
{ width: 96, height: 96, name: 'xhdpi_96x96' },
{ width: 144, height: 144, name: 'xxhdpi_144x144' },
{ width: 192, height: 192, name: 'xxxhdpi_192x192' },
{ width: 512, height: 512, name: 'playstore_512x512' }
],
'ios': [
{ width: 60, height: 60, name: '60x60' },
{ width: 120, height: 120, name: '120x120' },
{ width: 180, height: 180, name: '180x180' },
{ width: 1024, height: 1024, name: 'appstore_1024x1024' }
],
'social': [
{ width: 1080, height: 1080, name: 'instagram_1080x1080' },
{ width: 1200, height: 630, name: 'facebook_1200x630' },
{ width: 1280, height: 720, name: 'youtube_1280x720' },
{ width: 1200, height: 675, name: 'twitter_1200x675' }
],
'all': [
{ width: 512, height: 512, name: '512x512' },
{ width: 256, height: 256, name: '256x256' },
{ width: 128, height: 128, name: '128x128' },
{ width: 64, height: 64, name: '64x64' },
{ width: 32, height: 32, name: '32x32' },
{ width: 16, height: 16, name: '16x16' },
{ width: 1024, height: 1024, name: '1024x1024' },
{ width: 192, height: 192, name: '192x192' },
{ width: 180, height: 180, name: '180x180' },
{ width: 144, height: 144, name: '144x144' },
{ width: 120, height: 120, name: '120x120' },
{ width: 96, height: 96, name: '96x96' },
{ width: 72, height: 72, name: '72x72' },
{ width: 60, height: 60, name: '60x60' },
{ width: 48, height: 48, name: '48x48' }
]
};
}
setupEventListeners() {
// Upload area events
if (this.uploadArea) {
this.uploadArea.addEventListener('click', () => this.fileInput.click());
this.uploadArea.addEventListener('dragover', this.handleDragOver.bind(this));
this.uploadArea.addEventListener('dragleave', this.handleDragLeave.bind(this));
this.uploadArea.addEventListener('drop', this.handleDrop.bind(this));
}
// File input
if (this.fileInput) this.fileInput.addEventListener('change', (e) => this.handleFiles(e.target.files));
if (this.folderInput) this.folderInput.addEventListener('change', (e) => this.handleFiles(e.target.files));
// Global Paste Support
window.addEventListener('paste', (e) => this.handlePaste(e));
// Resize type change
if (this.resizeType) {
this.resizeType.addEventListener('change', (e) => {
const type = e.target.value;
if (this.pixelDimensions) this.pixelDimensions.style.display = type === 'pixels' ? 'block' : 'none';
if (this.percentageDimensions) this.percentageDimensions.style.display = type === 'percentage' ? 'block' : 'none';
if (this.maxFileSizeGroup) this.maxFileSizeGroup.style.display = type === 'maxfilesize' ? 'block' : 'none';
if (this.maxDimensionsGroup) this.maxDimensionsGroup.style.display = type === 'maxdimensions' ? 'block' : 'none';
});
}
// Percentage slider
if (this.resizePercentage) {
this.resizePercentage.addEventListener('input', (e) => {
if (this.percentageValue) this.percentageValue.textContent = e.target.value;
});
}
// Percentage preset buttons
this.percentButtons.forEach(btn => {
btn.addEventListener('click', (e) => {
const percent = e.target.dataset.percent;
if (this.resizePercentage) this.resizePercentage.value = percent;
if (this.percentageValue) this.percentageValue.textContent = percent;
});
});
// Multiple formats
if (this.convertMultipleFormats) {
this.convertMultipleFormats.addEventListener('change', (e) => {
if (this.formatSelection) this.formatSelection.style.display = e.target.checked ? 'block' : 'none';
});
}
// Custom naming
if (this.customNaming) {
this.customNaming.addEventListener('change', (e) => {
if (this.customNamingPattern) this.customNamingPattern.style.display = e.target.value === 'custom' ? 'block' : 'none';
});
}
// ZIP format change
if (this.zipFormat) {
this.zipFormat.addEventListener('change', (e) => {
if (this.zipOptionsGroup) this.zipOptionsGroup.style.display = e.target.value === 'zip' ? 'block' : 'none';
});
}
// Folder import
if (this.folderImport) {
this.folderImport.addEventListener('change', (e) => {
if (this.fileInput) {
if (e.target.checked) {
this.fileInput.setAttribute('webkitdirectory', '');
} else {
this.fileInput.removeAttribute('webkitdirectory');
}
}
});
}
// Preset buttons
if (this.savePresetBtn) this.savePresetBtn.addEventListener('click', () => this.showPresetModal());
if (this.savePresetConfirmBtn) this.savePresetConfirmBtn.addEventListener('click', () => this.saveCurrentPreset());
if (this.cancelPresetBtn) this.cancelPresetBtn.addEventListener('click', () => this.closePresetModal());
if (this.historyBtn) this.historyBtn.addEventListener('click', () => this.toggleHistory());
if (this.clearHistoryBtn) this.clearHistoryBtn.addEventListener('click', () => this.clearHistory());
// Custom size list
if (this.addSizeBtn) this.addSizeBtn.addEventListener('click', () => this.addCustomSize());
if (this.newSizeWidth) this.newSizeWidth.addEventListener('keypress', (e) => { if (e.key === 'Enter') this.addCustomSize(); });
if (this.newSizeHeight) this.newSizeHeight.addEventListener('keypress', (e) => { if (e.key === 'Enter') this.addCustomSize(); });
if (this.clearSizeListBtn) this.clearSizeListBtn.addEventListener('click', () => this.clearCustomSizesList());
if (this.saveSizeListPresetBtn) this.saveSizeListPresetBtn.addEventListener('click', () => this.saveSizeListAsPreset());
if (this.saveSizeEditBtn) this.saveSizeEditBtn.addEventListener('click', () => this.saveSizeEdit());
if (this.cancelSizeEditBtn) this.cancelSizeEditBtn.addEventListener('click', () => this.closeSizeEditModal());
if (this.editSizeQuality) {
this.editSizeQuality.addEventListener('input', (e) => {
if (this.editQualityValue) this.editQualityValue.textContent = e.target.value;
});
}
// Close modals on outside click
if (this.presetModal) {
this.presetModal.addEventListener('click', (e) => {
if (e.target === this.presetModal) {
this.closePresetModal();
}
});
}
if (this.editSizeModal) {
this.editSizeModal.addEventListener('click', (e) => {
if (e.target === this.editSizeModal) {
this.closeSizeEditModal();
}
});
}
// Settings
if (this.quality) {
this.quality.addEventListener('input', (e) => {
if (this.qualityValue) this.qualityValue.textContent = e.target.value;
});
}
if (this.resizeMode) {
this.resizeMode.addEventListener('change', (e) => {
const showDimensions = e.target.value === 'custom' || e.target.value === 'fit' || e.target.value === 'fill';
if (this.resizeDimensions) this.resizeDimensions.style.display = showDimensions ? 'block' : 'none';
if (this.resizeHeightGroup) this.resizeHeightGroup.style.display = showDimensions ? 'block' : 'none';
});
}
if (this.outputFormat) {
this.outputFormat.addEventListener('change', (e) => {
const needsBackground = e.target.value === 'jpg' || e.target.value === 'jpeg';
if (this.backgroundColorGroup) this.backgroundColorGroup.style.display = needsBackground ? 'block' : 'none';
});
}
if (this.resizeMode) {
this.resizeMode.addEventListener('change', (e) => {
const isCircular = e.target.value === 'circular';
if (this.advancedOptions) this.advancedOptions.style.display = isCircular ? 'block' : 'none';
});
}
// Preset buttons
this.presetButtons.forEach(btn => {
btn.addEventListener('click', (e) => {
const preset = e.target.dataset.preset;
this.selectPreset(preset);
});
});
// Background color preset buttons
this.bgPresetButtons.forEach(btn => {
btn.addEventListener('click', (e) => {
const color = e.target.dataset.color;
if (color === 'transparent') {
if (this.preserveTransparency) this.preserveTransparency.checked = true;
if (this.outputFormat) this.outputFormat.value = 'png';
} else {
if (this.backgroundColor) this.backgroundColor.value = color;
}
});
});
// Background Fill Mode toggle
if (this.backgroundFillMode) {
this.backgroundFillMode.addEventListener('change', (e) => {
const mode = e.target.value;
if (this.bgColorControls) this.bgColorControls.style.display = mode === 'color' ? 'flex' : 'none';
if (this.bgImageControls) this.bgImageControls.style.display = mode === 'image' ? 'block' : 'none';
});
}
// Background Image Upload
if (this.bgImageBtn) this.bgImageBtn.addEventListener('click', () => this.bgImageInput.click());
if (this.bgImageInput) {
this.bgImageInput.addEventListener('change', (e) => {
const file = e.target.files[0];
if (file) {
const reader = new FileReader();
reader.onload = (event) => {
const img = new Image();
img.onload = () => {
this.customBgImage = img;
if (this.bgImagePreview) {
this.bgImagePreview.style.display = 'block';
this.bgImagePreview.textContent = `BG: ${file.name}`;
}
this.showNotification('Background image loaded!', 'success');
};
img.src = event.target.result;
};
reader.readAsDataURL(file);
}
});
}
// Auto Background toggle visibility
if (this.autoBackground) {
this.autoBackground.addEventListener('change', () => this.updateBackgroundVisibility());
}
// Action buttons
if (this.convertBtn) this.convertBtn.addEventListener('click', () => this.convertAll());
if (this.clearBtn) this.clearBtn.addEventListener('click', () => this.clearAll());
if (this.downloadAllBtn) this.downloadAllBtn.addEventListener('click', () => this.downloadAll());
// Theme toggle
this.themeToggle?.addEventListener('click', () => this.toggleTheme());
// Load saved theme preference
this.loadThemePreference();
// Initial format check
if (this.outputFormat) {
this.outputFormat.addEventListener('change', () => this.updateBackgroundVisibility());
}
// Final initialization
this.updateBackgroundVisibility();
if (this.resizeType) this.resizeType.dispatchEvent(new Event('change'));
if (this.zipFormat) this.zipFormat.dispatchEvent(new Event('change'));
this.selectPreset('none');
this.updateUserPresetsUI();
}
updateBackgroundVisibility() {
const format = this.outputFormat ? this.outputFormat.value : 'png';
const needsBackground = format === 'jpg' || format === 'jpeg';
const isAutoBg = this.autoBackground && this.autoBackground.checked;
if (this.backgroundColorGroup) {
this.backgroundColorGroup.style.display = (needsBackground || isAutoBg) ? 'block' : 'none';
}
if (this.backgroundFillMode) {
const mode = this.backgroundFillMode.value;
if (this.bgColorControls) this.bgColorControls.style.display = (mode === 'color') ? 'flex' : 'none';
if (this.bgImageControls) this.bgImageControls.style.display = (mode === 'image') ? 'block' : 'none';
}
}
updateThemeIcon(isLight) {
if (this.themeIcon) {
this.themeIcon.textContent = isLight ? '☀️' : '🌙';
}
}
setupKeyboardShortcuts() {
// Toggle Shortcuts Panel
if (this.shortcutsBtn) {
this.shortcutsBtn.addEventListener('click', () => {
this.shortcutsPanel.classList.toggle('active');
});
}
document.addEventListener('keydown', (e) => {
const ctrl = e.ctrlKey || e.metaKey;
if (ctrl && e.key === 'u') {
e.preventDefault();
this.fileInput.click();
} else if (ctrl && e.key === 'Enter') {
e.preventDefault();
this.convertBtn.click();
} else if (ctrl && e.key === 'z' && !e.shiftKey) {
e.preventDefault();
this.clearAll();
} else if (ctrl && e.key === 'd') {
e.preventDefault();
if (this.convertedImages.length > 0) {
this.downloadAll();
}
} else if (ctrl && e.key === 'h') {
e.preventDefault();
this.toggleHistory();
} else if (e.key === 'Escape') {
this.closePresetModal();
this.historySection.style.display = 'none';
}
});
}
loadThemePreference() {
const savedTheme = localStorage.getItem('imageConverter_theme');
const prefersDark = window.matchMedia('(prefers-color-scheme: dark)').matches;
// If saved as light, or no save and user prefers light
if (savedTheme === 'light' || (!savedTheme && !prefersDark)) {
document.body.classList.add('light-theme');
this.updateThemeIcon(true);
} else {
document.body.classList.remove('light-theme');
this.updateThemeIcon(false);
}
// Listen for system theme changes if no manual preference is set
window.matchMedia('(prefers-color-scheme: dark)').addEventListener('change', (e) => {
if (!localStorage.getItem('imageConverter_theme')) {
const isLightNow = !e.matches;
document.body.classList.toggle('light-theme', isLightNow);
this.updateThemeIcon(isLightNow);
}
});
}
toggleTheme() {
document.body.classList.toggle('light-theme');
const isLight = document.body.classList.contains('light-theme');
this.updateThemeIcon(isLight);
localStorage.setItem('imageConverter_theme', isLight ? 'light' : 'dark');
}
loadUserPresets() {
try {
const saved = localStorage.getItem('imageConverter_userPresets');
return saved ? JSON.parse(saved) : {};
} catch {
return {};
}
}
saveUserPresets() {
try {
localStorage.setItem('imageConverter_userPresets', JSON.stringify(this.userPresets));
} catch (e) {
console.error('Failed to save presets:', e);
}
}
loadHistory() {
try {
const saved = localStorage.getItem('imageConverter_history');
return saved ? JSON.parse(saved) : [];
} catch {
return [];
}
}
saveHistory() {
try {
// Keep only last 10
const history = this.conversionHistory.slice(-10);
localStorage.setItem('imageConverter_history', JSON.stringify(history));
} catch (e) {
console.error('Failed to save history:', e);
}
}
selectPreset(preset) {
this.currentPreset = preset;
// Update button states
this.presetButtons.forEach(btn => {
btn.classList.toggle('active', btn.dataset.preset === preset);
});
// Show/hide custom size list section
if (preset === 'custom-list') {
if (this.customSizeListSection) this.customSizeListSection.style.display = 'block';
if (this.presetInfo) {
this.presetInfo.innerHTML = `
<strong>Custom Size List Mode</strong><br>
<small>💡 Add any sizes you want, then generate them all at once</small>
`;
}
} else {
if (this.customSizeListSection) this.customSizeListSection.style.display = 'none';
}
// Update preset info
const sizes = this.presetSizes[preset];
if (preset === 'none') {
if (this.presetInfo) this.presetInfo.textContent = 'Using custom dimensions or no resize';
if (this.resizeWidth) this.resizeWidth.disabled = false;
if (this.resizeHeight) this.resizeHeight.disabled = false;
if (this.resizeDimensions) this.resizeDimensions.style.display = 'block';
if (this.resizeHeightGroup) this.resizeHeightGroup.style.display = 'block';
} else if (preset === 'custom-list') {
// Already handled above
} else {
const sizesList = sizes.map(s => `${s.name || s.width + 'x' + s.height}`).join(', ');
const count = sizes.length;
if (this.presetInfo) {
this.presetInfo.innerHTML = `
<strong>${count} sizes will be generated:</strong><br>
${sizesList}<br>
<small>💡 Each uploaded image will generate ${count} resized versions automatically</small>
`;
}
if (this.resizeWidth) this.resizeWidth.disabled = true;
if (this.resizeHeight) this.resizeHeight.disabled = true;
if (this.resizeDimensions) this.resizeDimensions.style.display = 'none';
if (this.resizeHeightGroup) this.resizeHeightGroup.style.display = 'none';
// Auto-set resize mode to fit for presets
if (this.resizeMode.value === 'none') {
this.resizeMode.value = 'fit';
}
}
}
addCustomSize() {
const width = parseInt(this.newSizeWidth.value);
const height = parseInt(this.newSizeHeight.value);
const keepAspect = this.newSizeKeepAspect.checked;
if (!width && !height) {
this.showNotification('Please enter at least width or height', 'error');
return;
}
const newSize = {
width: width || null,
height: height || null,
keepAspect: keepAspect,
format: this.outputFormat.value,
quality: parseInt(this.quality.value),
backgroundColor: this.backgroundColor.value,
resizeMode: this.resizeMode.value || 'fit',
name: `${width || 'auto'}x${height || 'auto'}`
};
this.customSizesList.push(newSize);
this.updateCustomSizesListUI();
this.showNotification('Custom size added!', 'success');
// Clear inputs
this.newSizeWidth.value = '';
this.newSizeHeight.value = '';
this.newSizeKeepAspect.checked = false;
}
removeCustomSize(index) {
this.customSizesList.splice(index, 1);
this.updateCustomSizesListUI();
this.showNotification('Custom size removed!', 'info');
}
editCustomSize(index) {
const size = this.customSizesList[index];
this.editingSizeIndex = index;
this.editSizeWidth.value = size.width || '';
this.editSizeHeight.value = size.height || '';
this.editSizeFormat.value = size.format || 'png';
this.editSizeQuality.value = size.quality || 80;
this.editQualityValue.textContent = size.quality || 80;
this.editSizeKeepAspect.checked = size.keepAspect || false;
this.editSizeBackground.value = size.backgroundColor || '#ffffff';
this.editSizeResizeMode.value = size.resizeMode || 'fit';
this.editSizeModal.style.display = 'flex';
}
saveSizeEdit() {
if (this.editingSizeIndex === null) return;
const size = this.customSizesList[this.editingSizeIndex];
size.width = parseInt(this.editSizeWidth.value) || null;
size.height = parseInt(this.editSizeHeight.value) || null;
size.format = this.editSizeFormat.value;
size.quality = parseInt(this.editSizeQuality.value);
size.keepAspect = this.editSizeKeepAspect.checked;
size.backgroundColor = this.editSizeBackground.value;
size.resizeMode = this.editSizeResizeMode.value;
size.name = `${size.width || 'auto'}x${size.height || 'auto'}`;
this.updateCustomSizesListUI();
this.closeSizeEditModal();
this.showNotification('Custom size updated!', 'success');
}
closeSizeEditModal() {
this.editSizeModal.style.display = 'none';
this.editingSizeIndex = null;
// Watermark toggle
if (this.addWatermark) {
this.addWatermark.addEventListener('change', (e) => {
if (this.watermarkSettings) {
this.watermarkSettings.style.display = e.target.checked ? 'block' : 'none';
}
});
}
if (this.watermarkOpacity) {
this.watermarkOpacity.addEventListener('input', (e) => {
if (this.watermarkOpacityValue) this.watermarkOpacityValue.textContent = e.target.value;
});
}
// Filter value updates
if (this.filterBrightness) {
this.filterBrightness.addEventListener('input', (e) => {
if (this.brightnessValue) this.brightnessValue.textContent = e.target.value;
});
}
if (this.filterContrast) {
this.filterContrast.addEventListener('input', (e) => {
if (this.contrastValue) this.contrastValue.textContent = e.target.value;
});
}
if (this.filterSaturation) {
this.filterSaturation.addEventListener('input', (e) => {
if (this.saturationValue) this.saturationValue.textContent = e.target.value;
});
}
if (this.filterWarmth) {
this.filterWarmth.addEventListener('input', (e) => {
if (this.warmthValue) this.warmthValue.textContent = e.target.value;
});
}
if (this.filterSharpening) {
this.filterSharpening.addEventListener('input', (e) => {
if (this.sharpeningValue) this.sharpeningValue.textContent = e.target.value;
});
}
}
clearCustomSizesList() {
if (this.customSizesList.length === 0) return;
if (confirm(`Clear all ${this.customSizesList.length} custom sizes?`)) {
this.customSizesList = [];
this.updateCustomSizesListUI();
this.showNotification('Custom size list cleared!', 'info');
}
}
updateCustomSizesListUI() {
if (this.customSizesList.length === 0) {
this.customSizesListContainer.innerHTML = '<p class="empty-message">No custom sizes added yet. Click "+ Add Size" to start building your list.</p>';
return;
}
this.customSizesListContainer.innerHTML = this.customSizesList.map((size, index) => {
const width = size.width || 'Auto';
const height = size.height || 'Auto';
return `
<div class="custom-size-item">
<div class="size-item-info">
<div class="size-item-main">
<span class="size-item-dimensions">${width} × ${height}px</span>
${size.keepAspect ? '<span style="color: var(--text-secondary); font-size: 0.9rem;">(Aspect ratio)</span>' : ''}
</div>
<div class="size-item-details">
<span>Format: ${size.format.toUpperCase()}</span>
<span>Quality: ${size.quality}%</span>
<span>Mode: ${size.resizeMode}</span>
</div>
</div>
<div class="size-item-actions">
<button class="btn-icon" onclick="window.imageConverter.editCustomSize(${index})" title="Edit">✏️</button>
<button class="btn-icon danger" onclick="window.imageConverter.removeCustomSize(${index})" title="Remove">🗑️</button>
</div>
</div>
`;
}).join('');
}
saveSizeListAsPreset() {
if (this.customSizesList.length === 0) {
this.showNotification('Please add some custom sizes first', 'error');
return;
}
const name = prompt('Enter preset name:', 'My Custom Sizes');
if (!name || !name.trim()) {
this.showNotification('Preset name cannot be empty', 'error');
return;
}
const preset = {
name: name.trim(),
type: 'custom-size-list',
sizes: JSON.parse(JSON.stringify(this.customSizesList)),
timestamp: Date.now()
};
this.userPresets[name.trim()] = preset;
this.saveUserPresets();
this.updateUserPresetsUI();
this.showNotification(`Preset "${name.trim()}" saved! You can load it from "Your Custom Presets" section.`, 'success');
}
checkFormatSupport() {
// Check WebP support
const webpSupported = document.createElement('canvas').toDataURL('image/webp').indexOf('data:image/webp') === 0;
if (!webpSupported) {
const webpOption = this.outputFormat.querySelector('option[value="webp"]');
if (webpOption) {
webpOption.disabled = true;
webpOption.textContent += ' (not supported)';
}
}
}
handleDragOver(e) {
e.preventDefault();
this.uploadArea.classList.add('dragover');
}
handleDragLeave(e) {
e.preventDefault();
this.uploadArea.classList.remove('dragover');
}
handleDrop(e) {
e.preventDefault();
this.uploadArea.classList.remove('dragover');
const files = Array.from(e.dataTransfer.files).filter(file => file.type.startsWith('image/'));
this.handleFiles(files);
}
handlePaste(e) {
const items = e.clipboardData?.items;
if (!items) return;
const files = [];
for (let i = 0; i < items.length; i++) {
if (items[i].type.indexOf('image') !== -1) {
const blob = items[i].getAsFile();
if (blob) {
const file = new File([blob], `pasted_image_${Date.now()}_${i}.png`, { type: blob.type });
files.push(file);
}
}
}
if (files.length > 0) {
this.handleFiles(files);
}
}
async handleFiles(files) {
if (files.length === 0) return;
let hasValidImage = false;
for (const file of files) {
if (!file.type.match('image.*') && !file.name.endsWith('.svg')) {
this.showNotification(`Skipped non-image file: ${file.name}`, 'error');
continue;
}
try {
const imageData = await this.loadImage(file);
this.images.push(imageData);
hasValidImage = true;
} catch (error) {
console.error('Error loading image:', error);
this.showNotification(`Error loading ${file.name}: ${error.message}`, 'error');
}
}
if (hasValidImage) {
this.showNotification(`${files.length} image(s) loaded`, 'success');
}
this.updateUI();
}
loadImage(file) {
return new Promise((resolve, reject) => {
const reader = new FileReader();
reader.onload = (e) => {
const img = new Image();
img.onload = () => {
resolve({
file: file,
name: file.name,
originalSize: file.size,
width: img.width,
height: img.height,
image: img,
format: this.detectFormat(file.name, file.type),
hasTransparency: this.checkTransparency(img)
});
};
img.onerror = () => reject(new Error('Failed to load image'));
img.src = e.target.result;
};
reader.onerror = () => reject(new Error('Failed to read file'));
reader.readAsDataURL(file);
});
}
detectFormat(filename, mimeType) {
const ext = filename.split('.').pop().toLowerCase();
const formatMap = {
'png': 'png',
'jpg': 'jpg',
'jpeg': 'jpeg',
'webp': 'webp',
'bmp': 'bmp',
'gif': 'gif',
'tiff': 'tiff',
'svg': 'svg',
'avif': 'avif',
'heic': 'heic'
};
return formatMap[ext] || mimeType.split('/')[1] || 'unknown';
}
checkTransparency(img) {
try {
const canvas = document.createElement('canvas');
// Use a small scale for performance, but large enough to detect details
const size = Math.min(img.width, img.height, 100);
canvas.width = size;
canvas.height = size;
const ctx = canvas.getContext('2d');
ctx.drawImage(img, 0, 0, size, size);
const imageData = ctx.getImageData(0, 0, size, size).data;
for (let i = 3; i < imageData.length; i += 4) {