-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathmain.js.backup
More file actions
4215 lines (4215 loc) · 171 KB
/
main.js.backup
File metadata and controls
4215 lines (4215 loc) · 171 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
// Serpentnote - Enhanced Version 3.0
console.log('%c🐍 Serpentnote v3.0 Enhanced', 'color: #34c759; font-size: 16px; font-weight: bold;');
console.log('Features: Keyboard shortcuts, Undo/Redo, Auto-save indicator, Image metadata, Channel export');
// Storage adapter that works with both browser localStorage and Electron file system
const isElectron = typeof window !== 'undefined' && window.electronAPI?.isElectron;
let electronDataPath = null;
// IndexedDB wrapper for browser mode (better than localStorage)
const DB_NAME = 'SerpentNote';
const DB_VERSION = 1;
const STORE_NAME = 'data';
let db = null;
async function initIndexedDB() {
if (isElectron)
return; // Only use IndexedDB in browser mode
return new Promise((resolve, reject) => {
const request = indexedDB.open(DB_NAME, DB_VERSION);
request.onerror = () => reject(request.error);
request.onsuccess = () => {
db = request.result;
resolve();
};
request.onupgradeneeded = (event) => {
const database = event.target.result;
if (!database.objectStoreNames.contains(STORE_NAME)) {
database.createObjectStore(STORE_NAME);
}
};
});
}
async function indexedDBSet(key, value) {
if (!db)
return;
return new Promise((resolve, reject) => {
const transaction = db.transaction([STORE_NAME], 'readwrite');
const store = transaction.objectStore(STORE_NAME);
const request = store.put(value, key);
request.onsuccess = () => resolve();
request.onerror = () => reject(request.error);
});
}
async function indexedDBGet(key) {
if (!db)
return null;
return new Promise((resolve, reject) => {
const transaction = db.transaction([STORE_NAME], 'readonly');
const store = transaction.objectStore(STORE_NAME);
const request = store.get(key);
request.onsuccess = () => resolve(request.result || null);
request.onerror = () => reject(request.error);
});
}
async function initElectronStorage() {
if (!isElectron)
return;
// Try to load saved data path from localStorage
const savedPath = localStorage.getItem('electronDataPath');
if (savedPath) {
electronDataPath = savedPath;
return;
}
// First time setup - ask user to select a folder
const result = await window.electronAPI.openDirectory();
if (result) {
electronDataPath = result;
localStorage.setItem('electronDataPath', result);
// Create serpentnote data directory
await window.electronAPI.mkdir(`${electronDataPath}/serpentnote-data`);
await window.electronAPI.mkdir(`${electronDataPath}/serpentnote-data/images`);
}
}
async function storageSet(key, value) {
if (isElectron && electronDataPath) {
// Electron mode: use file system
const filePath = `${electronDataPath}/serpentnote-data/${key}.json`;
await window.electronAPI.writeFile(filePath, value);
}
else if (db) {
// Browser mode with IndexedDB
await indexedDBSet(key, value);
}
else {
// Fallback to localStorage
localStorage.setItem(key, value);
}
}
async function storageGet(key) {
if (isElectron && electronDataPath) {
// Electron mode: use file system
const filePath = `${electronDataPath}/serpentnote-data/${key}.json`;
const result = await window.electronAPI.readFile(filePath);
return result.success ? result.data : null;
}
else if (db) {
// Browser mode with IndexedDB
return await indexedDBGet(key);
}
else {
// Fallback to localStorage
return localStorage.getItem(key);
}
}
async function saveImageToElectron(base64Data, filename) {
if (!isElectron || !electronDataPath)
return null;
try {
const imagePath = `${electronDataPath}/serpentnote-data/images/${filename}`;
await window.electronAPI.writeFile(imagePath, base64Data);
return imagePath;
}
catch (error) {
console.error('Failed to save image:', error);
return null;
}
}
async function deleteImageFromElectron(imagePath) {
if (!isElectron || !electronDataPath)
return false;
try {
const result = await window.electronAPI.unlink(imagePath);
return result.success;
}
catch (error) {
console.error('Failed to delete image:', error);
return false;
}
}
// Utility: Debounce function
function debounce(func, wait) {
let timeout = null;
return function (...args) {
if (timeout !== null) {
clearTimeout(timeout);
}
timeout = window.setTimeout(() => func(...args), wait);
};
}
// Utility: Throttle function for save operations
function throttle(func, limit) {
let inThrottle = false;
let lastArgs = null;
return function (...args) {
lastArgs = args;
if (!inThrottle) {
func(...args);
inThrottle = true;
lastArgs = null;
setTimeout(() => {
inThrottle = false;
// If there were additional calls during throttle, execute with latest args
if (lastArgs !== null) {
func(...lastArgs);
lastArgs = null;
}
}, limit);
}
};
}
// Utility: Check localStorage quota
function checkStorageQuota() {
let used = 0;
for (const key in localStorage) {
if (localStorage.hasOwnProperty(key)) {
used += localStorage[key].length + key.length;
}
}
// Most browsers allocate 5-10MB for localStorage
const available = 10 * 1024 * 1024; // 10MB estimate
const percentage = (used / available) * 100;
return { used, available, percentage };
}
// Utility: Show storage warning
function showStorageWarning(percentage) {
if (percentage > 80 && percentage < 95) {
showToast(`⚠️ Storage ${percentage.toFixed(0)}% full. Consider exporting and clearing old data.`, 'warning', 5000);
}
}
// Toast notification system
function showToast(message, type = 'info', duration = 3000) {
const toast = document.createElement('div');
toast.className = `toast toast-${type}`;
toast.textContent = message;
// Icon based on type
const icon = {
success: '✓',
error: '✕',
warning: '⚠',
info: 'ℹ'
}[type];
toast.innerHTML = `<span class="toast-icon">${icon}</span><span class="toast-message">${message}</span>`;
document.body.appendChild(toast);
// Trigger animation
requestAnimationFrame(() => {
toast.classList.add('toast-show');
});
// Auto remove
setTimeout(() => {
toast.classList.remove('toast-show');
setTimeout(() => {
if (document.body.contains(toast)) {
document.body.removeChild(toast);
}
}, 300);
}, duration);
}
const undoStack = [];
const MAX_UNDO_STACK = 10;
function addUndoAction(action) {
undoStack.push(action);
if (undoStack.length > MAX_UNDO_STACK) {
undoStack.shift();
}
showUndoToast();
}
function undo() {
const action = undoStack.pop();
if (!action)
return;
if (action.type === 'delete-channel') {
const channel = action.data;
state.channels.push(channel);
saveToStorage();
renderChannelsList();
renderFilterTags();
selectChannel(channel.id);
const message = document.createElement('div');
message.textContent = `✓ Channel "${channel.name}" restored`;
message.style.position = 'fixed';
message.style.top = '20px';
message.style.left = '50%';
message.style.transform = 'translateX(-50%)';
message.style.background = '#34c759';
message.style.color = 'white';
message.style.padding = '12px 24px';
message.style.borderRadius = '8px';
message.style.fontWeight = '600';
message.style.zIndex = '3001';
message.style.boxShadow = '0 4px 12px rgba(0,0,0,0.3)';
document.body.appendChild(message);
setTimeout(() => document.body.removeChild(message), 3000);
}
else if (action.type === 'delete-image') {
const { channelId, imageUrl, index } = action.data;
const channel = state.channels.find(c => c.id === channelId);
if (channel) {
channel.images.splice(index, 0, imageUrl);
saveToStorage();
renderGallery(channel);
renderChannelsList();
const message = document.createElement('div');
message.textContent = '✓ Image restored';
message.style.position = 'fixed';
message.style.top = '20px';
message.style.left = '50%';
message.style.transform = 'translateX(-50%)';
message.style.background = '#34c759';
message.style.color = 'white';
message.style.padding = '12px 24px';
message.style.borderRadius = '8px';
message.style.fontWeight = '600';
message.style.zIndex = '3001';
message.style.boxShadow = '0 4px 12px rgba(0,0,0,0.3)';
document.body.appendChild(message);
setTimeout(() => document.body.removeChild(message), 3000);
}
}
else if (action.type === 'delete-tag') {
const { tagName, affectedChannels } = action.data;
state.tags.push(tagName);
affectedChannels.forEach((channelData) => {
const channel = state.channels.find(c => c.id === channelData.id);
if (channel) {
channel.tags = channelData.tags;
}
});
saveToStorage();
renderExistingTags();
renderFilterTags();
renderChannelsList();
const message = document.createElement('div');
message.textContent = `✓ Tag "${tagName}" restored`;
message.style.position = 'fixed';
message.style.top = '20px';
message.style.left = '50%';
message.style.transform = 'translateX(-50%)';
message.style.background = '#34c759';
message.style.color = 'white';
message.style.padding = '12px 24px';
message.style.borderRadius = '8px';
message.style.fontWeight = '600';
message.style.zIndex = '3001';
message.style.boxShadow = '0 4px 12px rgba(0,0,0,0.3)';
document.body.appendChild(message);
setTimeout(() => document.body.removeChild(message), 3000);
}
}
function showUndoToast() {
// Remove existing toast if any
const existingToast = document.getElementById('undoToast');
if (existingToast) {
document.body.removeChild(existingToast);
}
const toast = document.createElement('div');
toast.id = 'undoToast';
toast.innerHTML = `
<span>Deleted</span>
<button id="undoBtn">Undo</button>
`;
toast.style.position = 'fixed';
toast.style.bottom = '20px';
toast.style.left = '50%';
toast.style.transform = 'translateX(-50%)';
toast.style.background = '#2c2c2e';
toast.style.color = 'white';
toast.style.padding = '12px 16px';
toast.style.borderRadius = '8px';
toast.style.fontWeight = '500';
toast.style.zIndex = '3001';
toast.style.boxShadow = '0 4px 12px rgba(0,0,0,0.3)';
toast.style.display = 'flex';
toast.style.gap = '16px';
toast.style.alignItems = 'center';
const undoBtn = toast.querySelector('#undoBtn');
undoBtn.style.background = '#0a84ff';
undoBtn.style.color = 'white';
undoBtn.style.border = 'none';
undoBtn.style.padding = '6px 12px';
undoBtn.style.borderRadius = '6px';
undoBtn.style.cursor = 'pointer';
undoBtn.style.fontWeight = '600';
undoBtn.style.fontSize = '14px';
undoBtn.addEventListener('click', () => {
undo();
document.body.removeChild(toast);
});
document.body.appendChild(toast);
// Auto-remove after 5 seconds
setTimeout(() => {
if (document.body.contains(toast)) {
document.body.removeChild(toast);
}
}, 5000);
}
// State management
let state = {
channels: [],
tags: [],
activeChannelId: null,
activeFilter: 'all',
activeFilters: [],
theme: 'oled-black',
language: 'en',
searchQuery: '',
currentTagPage: 0,
tagsPerPage: 15
};
let autocompleteSelectedIndex = -1;
let autocompleteItems = [];
let customDanbooruTags = [];
// Local storage keys
const STORAGE_KEYS = {
CHANNELS: 'serpentsBook_channels',
TAGS: 'serpentsBook_tags',
THEME: 'serpentsBook_theme',
LANGUAGE: 'serpentsBook_language',
DANBOORU_TAGS: 'serpentsBook_danbooruTags'
};
// Language translations
const translations = {
en: {
name: 'English',
appTitle: 'Serpentnote',
settings: 'Settings',
newChannel: 'New Channel',
manageTags: 'Manage Tags',
filterByTags: 'Filter by Tags',
allChannels: 'All Channels',
channels: 'Channels',
gallery: 'Gallery',
uploadImage: 'Upload Image',
noImages: 'No images yet. Double-click or drag & drop to upload!',
prompt: 'Prompt',
copy: 'Copy',
edit: 'Edit',
delete: 'Delete',
cancel: 'Cancel',
save: 'Save',
channelName: 'Channel Name',
tags: 'Tags',
addTag: 'Add tag...',
createNewTag: 'Create New Tag',
add: 'Add',
theme: 'Theme',
colorTheme: 'Color Theme',
themeDescription: 'Choose your preferred visual theme',
light: 'Light',
oledBlack: 'OLED Black',
language: 'Language',
uiLanguage: 'UI Language',
languageDescription: 'Choose your preferred interface language',
manageDanbooruTags: 'Manage Danbooru Tags',
dataManagement: 'Data Management',
exportData: 'Export All Data',
exportDescription: 'Download all channels, prompts, tags, and images as a JSON file',
exportBtn: 'Export',
importData: 'Import Data',
importDescription: 'Import previously exported data (replaces current data)',
importBtn: 'Import',
clearData: 'Clear All Data',
clearDescription: 'Permanently delete all channels, prompts, tags, and images',
clearBtn: 'Clear All',
dataStatistics: 'Data & Statistics',
totalChannels: 'Total Channels',
totalChannelsDescription: 'Number of channels in your library',
totalTags: 'Total Tags',
totalTagsDescription: 'Filter tags for organizing channels',
customDanbooruTags: 'Custom Danbooru Tags',
customDanbooruTagsDescription: 'Custom tags added to autocomplete',
confirmDeleteChannel: 'Are you sure you want to delete this channel?',
confirmClearData: 'Are you sure you want to clear all data? This cannot be undone.',
confirmDeleteTag: 'Are you sure you want to delete this tag?',
yes: 'Yes',
no: 'No',
copiedPrompt: 'Prompt copied to clipboard!',
copiedFailed: 'Failed to copy prompt'
},
es: {
name: 'Español',
appTitle: 'Serpentnote',
settings: 'Configuración',
newChannel: 'Nuevo Canal',
manageTags: 'Administrar Etiquetas',
filterByTags: 'Filtrar por Etiquetas',
allChannels: 'Todos los Canales',
channels: 'Canales',
gallery: 'Galería',
uploadImage: 'Subir Imagen',
noImages: '¡Aún no hay imágenes. Sube tu primera imagen generada por IA!',
prompt: 'Prompt',
copy: 'Copiar',
edit: 'Editar',
delete: 'Eliminar',
cancel: 'Cancelar',
save: 'Guardar',
channelName: 'Nombre del Canal',
tags: 'Etiquetas',
addTag: 'Agregar etiqueta...',
createNewTag: 'Crear Nueva Etiqueta',
add: 'Agregar',
theme: 'Tema',
colorTheme: 'Tema de Color',
themeDescription: 'Elige tu tema visual preferido',
light: 'Claro',
oledBlack: 'Negro OLED',
language: 'Idioma',
uiLanguage: 'Idioma de la Interfaz',
languageDescription: 'Elige tu idioma de interfaz preferido',
dataManagement: 'Gestión de Datos',
exportData: 'Exportar Todos los Datos',
exportDescription: 'Descarga todos los canales, prompts, etiquetas e imágenes como archivo JSON',
exportBtn: 'Exportar Datos',
importData: 'Importar Datos',
importDescription: 'Sube un archivo JSON exportado previamente para restaurar tus datos',
importBtn: 'Importar Datos',
clearData: 'Borrar Todos los Datos',
clearDescription: 'Eliminar permanentemente todos los canales, prompts, etiquetas e imágenes',
clearBtn: 'Borrar Datos',
statistics: 'Estadísticas',
totalChannels: 'Total de Canales',
totalChannelsDescription: 'Número de canales en tu biblioteca',
totalTags: 'Total de Etiquetas',
totalTagsDescription: 'Etiquetas de filtro para organizar canales',
customDanbooruTags: 'Etiquetas Danbooru Personalizadas',
customDanbooruTagsDescription: 'Etiquetas personalizadas agregadas al autocompletado',
confirmDeleteChannel: '¿Estás seguro de que quieres eliminar este canal?',
confirmClearData: '¿Estás seguro de que quieres borrar todos los datos? Esto no se puede deshacer.',
confirmDeleteTag: '¿Estás seguro de que quieres eliminar esta etiqueta?',
yes: 'Sí',
no: 'No',
copiedPrompt: '¡Prompt copiado al portapapeles!',
copiedFailed: 'Error al copiar el prompt'
},
fr: {
name: 'Français',
appTitle: 'Serpentnote',
settings: 'Paramètres',
newChannel: 'Nouveau Canal',
manageTags: 'Gérer les Étiquettes',
filterByTags: 'Filtrer par Étiquettes',
allChannels: 'Tous les Canaux',
channels: 'Canaux',
gallery: 'Galerie',
uploadImage: 'Télécharger une Image',
noImages: 'Pas encore d\'images. Téléchargez votre première image générée par IA!',
prompt: 'Prompt',
copy: 'Copier',
edit: 'Modifier',
delete: 'Supprimer',
cancel: 'Annuler',
save: 'Enregistrer',
channelName: 'Nom du Canal',
tags: 'Étiquettes',
addTag: 'Ajouter une étiquette...',
createNewTag: 'Créer une Nouvelle Étiquette',
add: 'Ajouter',
theme: 'Thème',
colorTheme: 'Thème de Couleur',
themeDescription: 'Choisissez votre thème visuel préféré',
light: 'Clair',
oledBlack: 'Noir OLED',
language: 'Langue',
uiLanguage: 'Langue de l\'Interface',
languageDescription: 'Choisissez votre langue d\'interface préférée',
dataManagement: 'Gestion des Données',
exportData: 'Exporter Toutes les Données',
exportDescription: 'Téléchargez tous les canaux, prompts, étiquettes et images en fichier JSON',
exportBtn: 'Exporter les Données',
importData: 'Importer des Données',
importDescription: 'Téléchargez un fichier JSON précédemment exporté pour restaurer vos données',
importBtn: 'Importer des Données',
clearData: 'Effacer Toutes les Données',
clearDescription: 'Supprimer définitivement tous les canaux, prompts, étiquettes et images',
clearBtn: 'Effacer les Données',
statistics: 'Statistiques',
totalChannels: 'Total de Canaux',
totalChannelsDescription: 'Nombre de canaux dans votre bibliothèque',
totalTags: 'Total d\'Étiquettes',
totalTagsDescription: 'Étiquettes de filtre pour organiser les canaux',
customDanbooruTags: 'Étiquettes Danbooru Personnalisées',
customDanbooruTagsDescription: 'Étiquettes personnalisées ajoutées à l\'autocomplétion',
confirmDeleteChannel: 'Êtes-vous sûr de vouloir supprimer ce canal?',
confirmClearData: 'Êtes-vous sûr de vouloir effacer toutes les données? Cette action ne peut pas être annulée.',
confirmDeleteTag: 'Êtes-vous sûr de vouloir supprimer cette étiquette?',
yes: 'Oui',
no: 'Non',
copiedPrompt: 'Prompt copié dans le presse-papiers!',
copiedFailed: 'Échec de la copie du prompt'
},
zh: {
name: '中文',
appTitle: 'Serpentnote',
settings: '设置',
newChannel: '新建频道',
manageTags: '管理标签',
filterByTags: '按标签筛选',
allChannels: '所有频道',
channels: '频道',
gallery: '画廊',
uploadImage: '上传图片',
noImages: '还没有图片。上传您的第一张AI生成的图片!',
prompt: '提示词',
copy: '复制',
edit: '编辑',
delete: '删除',
cancel: '取消',
save: '保存',
channelName: '频道名称',
tags: '标签',
addTag: '添加标签...',
createNewTag: '创建新标签',
add: '添加',
theme: '主题',
colorTheme: '颜色主题',
themeDescription: '选择您喜欢的视觉主题',
light: '亮色',
oledBlack: 'OLED黑',
language: '语言',
uiLanguage: '界面语言',
languageDescription: '选择您喜欢的界面语言',
dataManagement: '数据管理',
exportData: '导出所有数据',
exportDescription: '将所有频道、提示词、标签和图片下载为JSON文件',
exportBtn: '导出数据',
importData: '导入数据',
importDescription: '上传之前导出的JSON文件以恢复您的数据',
importBtn: '导入数据',
clearData: '清除所有数据',
clearDescription: '永久删除所有频道、提示词、标签和图片',
clearBtn: '清除数据',
statistics: '统计',
totalChannels: '总频道数',
totalChannelsDescription: '您的库中的频道数量',
totalTags: '总标签数',
totalTagsDescription: '用于组织频道的筛选标签',
customDanbooruTags: '自定义Danbooru标签',
customDanbooruTagsDescription: '添加到自动完成的自定义标签',
confirmDeleteChannel: '确定要删除此频道吗?',
confirmClearData: '确定要清除所有数据吗?此操作无法撤消。',
confirmDeleteTag: '确定要删除此标签吗?',
yes: '是',
no: '否',
copiedPrompt: '提示词已复制到剪贴板!',
copiedFailed: '复制提示词失败'
},
ja: {
name: '日本語',
appTitle: 'Serpentnote',
settings: '設定',
newChannel: '新しいチャンネル',
manageTags: 'タグを管理',
filterByTags: 'タグでフィルター',
allChannels: 'すべてのチャンネル',
channels: 'チャンネル',
gallery: 'ギャラリー',
uploadImage: '画像をアップロード',
noImages: 'まだ画像がありません。最初のAI生成画像をアップロードしてください!',
prompt: 'プロンプト',
copy: 'コピー',
edit: '編集',
delete: '削除',
cancel: 'キャンセル',
save: '保存',
channelName: 'チャンネル名',
tags: 'タグ',
addTag: 'タグを追加...',
createNewTag: '新しいタグを作成',
add: '追加',
theme: 'テーマ',
colorTheme: 'カラーテーマ',
themeDescription: 'お好みのビジュアルテーマを選択',
light: 'ライト',
oledBlack: 'OLEDブラック',
language: '言語',
uiLanguage: 'インターフェース言語',
languageDescription: 'お好みのインターフェース言語を選択',
dataManagement: 'データ管理',
exportData: 'すべてのデータをエクスポート',
exportDescription: 'すべてのチャンネル、プロンプト、タグ、画像をJSONファイルとしてダウンロード',
exportBtn: 'データをエクスポート',
importData: 'データをインポート',
importDescription: '以前にエクスポートしたJSONファイルをアップロードしてデータを復元',
importBtn: 'データをインポート',
clearData: 'すべてのデータをクリア',
clearDescription: 'すべてのチャンネル、プロンプト、タグ、画像を完全に削除',
clearBtn: 'データをクリア',
statistics: '統計',
totalChannels: '総チャンネル数',
totalChannelsDescription: 'ライブラリ内のチャンネル数',
totalTags: '総タグ数',
totalTagsDescription: 'チャンネルを整理するためのフィルタータグ',
customDanbooruTags: 'カスタムDanbooruタグ',
customDanbooruTagsDescription: 'オートコンプリートに追加されたカスタムタグ',
confirmDeleteChannel: 'このチャンネルを削除してもよろしいですか?',
confirmClearData: 'すべてのデータをクリアしてもよろしいですか?この操作は元に戻せません。',
confirmDeleteTag: 'このタグを削除してもよろしいですか?',
yes: 'はい',
no: 'いいえ',
copiedPrompt: 'プロンプトをクリップボードにコピーしました!',
copiedFailed: 'プロンプトのコピーに失敗しました'
},
ar: {
name: 'العربية',
appTitle: 'Serpentnote',
settings: 'الإعدادات',
newChannel: 'قناة جديدة',
manageTags: 'إدارة العلامات',
filterByTags: 'تصفية حسب العلامات',
allChannels: 'جميع القنوات',
channels: 'القنوات',
gallery: 'المعرض',
uploadImage: 'تحميل صورة',
noImages: 'لا توجد صور بعد. قم بتحميل أول صورة تم إنشاؤها بواسطة الذكاء الاصطناعي!',
prompt: 'الموجه',
copy: 'نسخ',
edit: 'تعديل',
delete: 'حذف',
cancel: 'إلغاء',
save: 'حفظ',
channelName: 'اسم القناة',
tags: 'العلامات',
addTag: 'إضافة علامة...',
createNewTag: 'إنشاء علامة جديدة',
add: 'إضافة',
theme: 'المظهر',
colorTheme: 'نظام الألوان',
themeDescription: 'اختر المظهر المرئي المفضل لديك',
light: 'فاتح',
oledBlack: 'أسود OLED',
language: 'اللغة',
uiLanguage: 'لغة الواجهة',
languageDescription: 'اختر لغة الواجهة المفضلة لديك',
dataManagement: 'إدارة البيانات',
exportData: 'تصدير جميع البيانات',
exportDescription: 'تنزيل جميع القنوات والموجهات والعلامات والصور كملف JSON',
exportBtn: 'تصدير البيانات',
importData: 'استيراد البيانات',
importDescription: 'قم بتحميل ملف JSON تم تصديره مسبقًا لاستعادة بياناتك',
importBtn: 'استيراد البيانات',
clearData: 'مسح جميع البيانات',
clearDescription: 'حذف جميع القنوات والموجهات والعلامات والصور بشكل دائم',
clearBtn: 'مسح البيانات',
statistics: 'الإحصائيات',
totalChannels: 'إجمالي القنوات',
totalChannelsDescription: 'عدد القنوات في مكتبتك',
totalTags: 'إجمالي العلامات',
totalTagsDescription: 'علامات الفلترة لتنظيم القنوات',
customDanbooruTags: 'علامات Danbooru المخصصة',
customDanbooruTagsDescription: 'علامات مخصصة مضافة إلى الإكمال التلقائي',
confirmDeleteChannel: 'هل أنت متأكد أنك تريد حذف هذه القناة؟',
confirmClearData: 'هل أنت متأكد أنك تريد مسح جميع البيانات؟ لا يمكن التراجع عن هذا الإجراء.',
confirmDeleteTag: 'هل أنت متأكد أنك تريد حذف هذه العلامة؟',
yes: 'نعم',
no: 'لا',
copiedPrompt: 'تم نسخ الموجه إلى الحافظة!',
copiedFailed: 'فشل نسخ الموجه'
}
};
// Custom confirm dialog
let confirmResolve = null;
function t(key) {
const lang = state.language || 'en';
return translations[lang]?.[key] || translations['en'][key] || key;
}
function updateUILanguage() {
// Update app title
const appTitle = document.querySelector('.app-title');
if (appTitle)
appTitle.textContent = t('appTitle');
// Update sidebar
const filterByTagsTitle = document.querySelector('.sidebar-section-title');
if (filterByTagsTitle)
filterByTagsTitle.textContent = t('filterByTags');
const allChannelsBtn = document.querySelector('[data-filter="all"]');
if (allChannelsBtn)
allChannelsBtn.textContent = t('allChannels');
const channelsTitle = document.querySelectorAll('.sidebar-section-title')[1];
if (channelsTitle)
channelsTitle.textContent = t('channels');
const newChannelBtn = document.getElementById('newChannelBtn');
if (newChannelBtn)
newChannelBtn.textContent = t('newChannel');
const manageTagsBtn = document.getElementById('manageTagsBtn');
if (manageTagsBtn)
manageTagsBtn.textContent = t('manageTags');
// Update main content section titles
const galleryTitle = document.querySelector('.gallery-section .section-header h3');
if (galleryTitle)
galleryTitle.textContent = t('gallery');
const uploadBtn = document.getElementById('uploadImageBtn');
if (uploadBtn) {
const btnText = uploadBtn.childNodes[1];
if (btnText)
btnText.textContent = ' ' + t('uploadImage');
}
const promptTitle = document.querySelector('.prompt-section .section-header h3');
if (promptTitle)
promptTitle.textContent = t('prompt');
const copyPromptBtn = document.getElementById('copyPromptBtn');
if (copyPromptBtn)
copyPromptBtn.textContent = '📋';
const editPromptBtn = document.getElementById('editPromptBtn');
if (editPromptBtn)
editPromptBtn.textContent = '✏️';
const copyNegativePromptBtn = document.getElementById('copyNegativePromptBtn');
if (copyNegativePromptBtn)
copyNegativePromptBtn.textContent = '📋';
const editNegativePromptBtn = document.getElementById('editNegativePromptBtn');
if (editNegativePromptBtn)
editNegativePromptBtn.textContent = '✏️';
// Update channel modal
const channelModalTitle = document.querySelector('#channelModal .modal-header h2');
if (channelModalTitle)
channelModalTitle.textContent = t('newChannel');
const channelNameLabel = document.querySelector('label[for="channelNameInput"]');
if (channelNameLabel)
channelNameLabel.textContent = t('channelName');
const tagsLabel = document.querySelector('label[for="tagInput"]');
if (tagsLabel)
tagsLabel.textContent = t('tags');
const tagInput = document.getElementById('tagInput');
if (tagInput)
tagInput.placeholder = t('addTag');
const promptLabel = document.querySelector('label[for="promptInput"]');
if (promptLabel)
promptLabel.textContent = t('prompt');
const cancelChannelBtn = document.getElementById('cancelChannelBtn');
if (cancelChannelBtn)
cancelChannelBtn.textContent = t('cancel');
const saveChannelBtn = document.getElementById('saveChannelBtn');
if (saveChannelBtn)
saveChannelBtn.textContent = t('save');
// Update tags modal
const tagsModalTitle = document.querySelector('#tagsModal .modal-header h2');
if (tagsModalTitle)
tagsModalTitle.textContent = t('manageTags');
const createTagLabel = document.querySelector('label[for="newTagInput"]');
if (createTagLabel)
createTagLabel.textContent = t('createNewTag');
const addTagBtn = document.getElementById('addTagBtn');
if (addTagBtn)
addTagBtn.textContent = t('add');
// Update settings modal
const settingsTitle = document.querySelector('#settingsModal .modal-header h2');
if (settingsTitle)
settingsTitle.textContent = t('settings');
const themeSection = document.querySelectorAll('.settings-section-title')[0];
if (themeSection)
themeSection.textContent = t('theme');
const colorThemeLabel = document.querySelectorAll('.settings-item label')[0];
if (colorThemeLabel)
colorThemeLabel.textContent = t('colorTheme');
const themeDesc = document.querySelectorAll('.settings-description')[0];
if (themeDesc)
themeDesc.textContent = t('themeDescription');
const lightSpan = document.querySelector('[data-theme="light"] span');
if (lightSpan)
lightSpan.textContent = t('light');
const oledBlackSpan = document.querySelector('[data-theme="oled-black"] span');
if (oledBlackSpan)
oledBlackSpan.textContent = t('oledBlack');
const languageSection = document.querySelectorAll('.settings-section-title')[1];
if (languageSection)
languageSection.textContent = t('language');
const uiLanguageLabel = document.querySelectorAll('.settings-item label')[1];
if (uiLanguageLabel)
uiLanguageLabel.textContent = t('uiLanguage');
const languageDesc = document.querySelectorAll('.settings-description')[1];
if (languageDesc)
languageDesc.textContent = t('languageDescription');
const danbooruTagsSection = document.querySelectorAll('.settings-section-title')[2];
if (danbooruTagsSection)
danbooruTagsSection.textContent = t('manageDanbooruTags');
// Data & Statistics section labels (indices updated after adding Custom Danbooru Tags)
const totalChannelsLabel = document.querySelectorAll('.settings-item label')[2];
if (totalChannelsLabel)
totalChannelsLabel.textContent = t('totalChannels');
const totalChannelsDesc = document.querySelectorAll('.settings-description')[2];
if (totalChannelsDesc)
totalChannelsDesc.textContent = t('totalChannelsDescription');
const totalTagsLabel = document.querySelectorAll('.settings-item label')[3];
if (totalTagsLabel)
totalTagsLabel.textContent = t('totalTags');
const totalTagsDesc = document.querySelectorAll('.settings-description')[3];
if (totalTagsDesc)
totalTagsDesc.textContent = t('totalTagsDescription');
const customDanbooruLabel = document.querySelectorAll('.settings-item label')[4];
if (customDanbooruLabel)
customDanbooruLabel.textContent = t('customDanbooruTags');
const customDanbooruDesc = document.querySelectorAll('.settings-description')[4];
if (customDanbooruDesc)
customDanbooruDesc.textContent = t('customDanbooruTagsDescription');
const exportDataLabel = document.querySelectorAll('.settings-item label')[5];
if (exportDataLabel)
exportDataLabel.textContent = t('exportData');
const exportDesc = document.querySelectorAll('.settings-description')[5];
if (exportDesc)
exportDesc.textContent = t('exportDescription');
const exportBtn = document.getElementById('exportDataBtn');
if (exportBtn)
exportBtn.textContent = t('exportBtn');
const importDataLabel = document.querySelectorAll('.settings-item label')[6];
if (importDataLabel)
importDataLabel.textContent = t('importData');
const importDesc = document.querySelectorAll('.settings-description')[6];
if (importDesc)
importDesc.textContent = t('importDescription');
const importBtn = document.getElementById('importDataBtn');
if (importBtn)
importBtn.textContent = t('importBtn');
const clearDataLabel = document.querySelectorAll('.settings-item label')[7];
if (clearDataLabel)
clearDataLabel.textContent = t('clearData');
const clearDesc = document.querySelectorAll('.settings-description')[7];
if (clearDesc)
clearDesc.textContent = t('clearDescription');
const clearBtn = document.getElementById('clearDataBtn');
if (clearBtn)
clearBtn.textContent = t('clearBtn');
const dataStatsSection = document.querySelectorAll('.settings-section-title')[3];
if (dataStatsSection)
dataStatsSection.textContent = t('dataStatistics');
// Update confirm modal
const confirmYes = document.getElementById('confirmYes');
if (confirmYes)
confirmYes.textContent = t('yes');
const confirmNo = document.getElementById('confirmNo');
if (confirmNo)
confirmNo.textContent = t('no');
// Update empty state if visible
const galleryEmpty = document.querySelector('.gallery-empty p');
if (galleryEmpty)
galleryEmpty.textContent = t('noImages');
// Re-parse emojis after text changes
parseEmojis();
}
function customConfirm(message) {
return new Promise((resolve) => {
confirmResolve = resolve;
const modal = document.getElementById('confirmModal');
const messageEl = document.getElementById('confirmMessage');
messageEl.textContent = message;
modal.classList.add('active');
});
}
function closeConfirmModal(result) {
const modal = document.getElementById('confirmModal');
modal.classList.remove('active');
if (confirmResolve) {
confirmResolve(result);
confirmResolve = null;
}
}
// Helper function to convert text with emojis to Twemoji HTML BEFORE DOM insertion
function convertToTwemoji(text) {
// Return plain text if twemoji is not loaded
if (typeof twemoji === 'undefined')
return text;
// Create a temporary element to parse the text
const temp = document.createElement('div');
temp.textContent = text;
// Parse with Twemoji - use base parameter instead of callback
twemoji.parse(temp, {
folder: 'svg',
ext: '.svg',
base: 'https://cdn.jsdelivr.net/gh/twitter/[email protected]/assets/'
});
// Add explicit dimensions to prevent layout shift
// Don't use lazy loading for tags - they're always visible
const emojiImages = temp.querySelectorAll('img.emoji');
emojiImages.forEach(img => {
const imgEl = img;
// Add explicit dimensions
imgEl.setAttribute('width', '16');
imgEl.setAttribute('height', '16');
imgEl.style.width = '1em';
imgEl.style.height = '1em';
});
return temp.innerHTML;
}
// Initialize app
async function init() {
// Initialize storage based on environment
if (isElectron) {
await initElectronStorage();
}
else {
// Initialize IndexedDB for browser mode
try {
await initIndexedDB();
console.log('✅ IndexedDB initialized successfully');
}
catch (error) {
console.warn('⚠️ IndexedDB initialization failed, falling back to localStorage:', error);
}
}
await loadFromStorage();
// Initialize tag search worker AFTER loading custom tags from storage
initTagWorker();
applyTheme(state.theme);
applyLanguage(state.language);
// Initialize emoji observer BEFORE rendering
initEmojiObserver();
renderChannelsList();
renderFilterTags();
setupEventListeners();
if (state.channels.length === 0) {
showEmptyState();
}
else {
// Select first channel
selectChannel(state.channels[0].id);
}
// Parse emojis to Apple style using Twemoji
parseEmojis();
}
// Lazy load emojis - only load when visible
let emojiObserver = null;
const loadedEmojis = new Set();
// Initialize the emoji observer
function initEmojiObserver() {
if (!emojiObserver) {
emojiObserver = new IntersectionObserver((entries) => {
entries.forEach(entry => {
const img = entry.target;
if (entry.isIntersecting) {
// Load emoji when it becomes visible
const dataSrc = img.getAttribute('data-src');
if (dataSrc && !img.src) {
img.src = dataSrc;
loadedEmojis.add(dataSrc);
}
}
else {
// Unload emoji when it's no longer visible (optional - saves memory)
if (img.src && !img.getAttribute('data-keep')) {
img.removeAttribute('src');
}
}
});
}, {
rootMargin: '50px', // Load slightly before entering viewport
threshold: 0.01
});
}
}
function parseEmojis() {
if (typeof twemoji === 'undefined')
return;
// Ensure observer is initialized
initEmojiObserver();
// Parse emojis but don't load images immediately