-
Notifications
You must be signed in to change notification settings - Fork 2
Expand file tree
/
Copy pathapp.js
More file actions
13092 lines (11283 loc) · 520 KB
/
app.js
File metadata and controls
13092 lines (11283 loc) · 520 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
// Authentication token and current user
let authToken = '';
let currentUser = '';
let isAdmin = false;
const TRANSCRIPTION_PROVIDERS = ['openai', 'local', 'sensevoice'];
const POSTPROCESS_PROVIDERS = ['openai', 'google', 'openrouter', 'groq', 'lmstudio', 'ollama'];
let allowedTranscriptionProviders = [];
let allowedPostprocessProviders = [];
let defaultProviderConfig = {};
let multiUser = true;
const PROVIDER_LABELS = {
openai: 'OpenAI',
local: 'Local Whisper',
sensevoice: 'SenseVoice',
google: 'Google',
openrouter: 'OpenRouter',
groq: 'Groq',
lmstudio: 'LM Studio',
ollama: 'Ollama'
};
function safeSetInnerHTML(element, html) {
element.innerHTML = DOMPurify.sanitize(html);
}
function authFetch(url, options = {}) {
// Merge Authorization header with any provided headers
const mergedHeaders = { ...(options.headers || {}) };
if (authToken) {
mergedHeaders['Authorization'] = authToken;
}
return fetch(url, { ...options, headers: mergedHeaders });
}
// Example data and configuration
const ejemplosTranscripcion = [
"This is a dictated note about the web development project we are working on in the office.",
"Team meeting scheduled for tomorrow at 10:00 AM to review quarterly progress.",
"Ideas to improve user experience in the mobile application we are developing.",
"Pending tasks list: review code, update documentation, prepare client presentation.",
"Conference notes on artificial intelligence and its applications in modern web development.",
"Brainstorming new features to implement in the next version of the application."
];
const configuracionMejoras = {
clarity: {
nombre: "Improve Clarity",
descripcion: "Makes text clearer and more direct",
icono: "✨",
prompt: "Rewrite the following text in a clearer and more readable way. Remove any interjections or expressions typical of spoken language (mmm, ahhh, eh, um, etc.) and expressions of hesitation when speaking or thinking aloud. Respond ONLY with the improved text, without additional explanations:",
visible: true
},
formal: {
nombre: "Make Formal",
descripcion: "Converts text to a more formal tone",
icono: "🎩",
prompt: "Rewrite the following text in a formal tone. Remove any interjections or expressions typical of spoken language (mmm, ahhh, eh, um, etc.) and expressions of hesitation when speaking or thinking aloud. Respond ONLY with the rewritten text, without additional explanations:",
visible: false
},
casual: {
nombre: "Make Casual",
descripcion: "Converts text to a more casual tone",
icono: "😊",
prompt: "Rewrite the following text in a casual and friendly tone. Remove any interjections or expressions typical of spoken language (mmm, ahhh, eh, um, etc.) and expressions of hesitation when speaking or thinking aloud. Respond ONLY with the rewritten text, without additional explanations:",
visible: false
},
academic: {
nombre: "Academic",
descripcion: "Converts text to academic style",
icono: "🎓",
prompt: "Rewrite the following text in an academic style. Remove any interjections or expressions typical of spoken language (mmm, ahhh, eh, um, etc.) and expressions of hesitation when speaking or thinking aloud. Respond ONLY with the rewritten text, without additional explanations:",
visible: false
},
narrative: {
nombre: "Narrative",
descripcion: "Improves narrative texts and novel dialogues",
icono: "📖",
prompt: "Improve the following narrative text or novel dialogue, preserving the literary style and narrative voice. Enhance flow, description and literary quality while keeping the essence of the text. Respond ONLY with the improved text, without additional explanations:",
visible: false
},
academic_v2: {
nombre: "Academic v2",
descripcion: "Academic improvement with minimal changes, preserving author's words",
icono: "🎓",
prompt: "Improve the following academic text by making minimal changes to preserve the author's words. Use more precise wording when necessary, improve the structure and remove any interjections or expressions typical of spoken language (mmm, ahhh, eh, um, etc.) and expressions of hesitation when speaking or thinking aloud. Keep the original style and vocabulary as much as possible. Respond ONLY with the improved text, without additional explanations:",
visible: true
},
summarize: {
nombre: "Summarize",
descripcion: "Creates a concise summary of the text",
icono: "📝",
prompt: "Create a concise summary of the following text. Remove any interjections or expressions typical of spoken language (mmm, ahhh, eh, um, etc.) and expressions of hesitation when speaking or thinking aloud. Respond ONLY with the summary, without additional explanations:",
visible: false
},
expand: {
nombre: "Expand",
descripcion: "Adds more details and context",
icono: "✚",
prompt: "Expand the following text by adding more details and relevant context. Remove any interjections or expressions typical of spoken language (mmm, ahhh, eh, um, etc.) and expressions of hesitation when speaking or thinking aloud. Respond ONLY with the expanded text, without additional explanations:",
visible: true
},
remove_emoji: {
nombre: "Remove emoji",
descripcion: "Remove all emojis from the text",
icono: "🫠",
prompt: "Remove every single emoji from this text. You MUST NOT change nothing from the text, just remove the emojis. Respond ONLY with the improved text, without additional explanations:",
visible: false
},
diarization_fix: {
nombre: "Fix Speaker Tags",
descripcion: "Corrects speaker diarization tags",
icono: "👥",
prompt: "Correct the speaker diarization in this transcript. Some speaker tags may be incorrectly placed. You MUST NOT modify the text content, only adjust the position of the speaker tags or the text itself. Keep the tags in the format [SPEAKER X]. Respond ONLY with the fixed diarization text, without additional explanations:",
visible: true
},
translation: {
nombre: "Translation",
descripcion: "Translate text into another language",
icono: "🗣️",
prompt: "",
visible: false,
custom: true
},
tabularize: {
nombre: "Tabularize",
descripcion: "Convert text into a table",
icono: "\uD83D\uDCCB",
prompt: "",
visible: false,
custom: true
}
};
// Clase principal de la aplicación
class NotesApp {
constructor() {
this.notes = [];
this.folders = [];
this.folderStructure = [];
this.currentNote = null;
this.noteToDelete = null;
this.folderToMove = null;
this.currentViewMode = 'folder'; // 'folder' or 'list'
this.expandedFolders = new Set();
this.isRecording = false;
this.autoSaveTimeout = null;
this.autoSaveInterval = null;
this.saveInProgress = false;
this.pendingSave = false;
this.lastSaveHash = '';
this.searchTerm = '';
this.selectedText = '';
this.selectedRange = null;
this.insertionRange = null;
this.mediaRecorder = null;
this.audioChunks = [];
this.audioFileToDelete = null;
this.recordingStream = null;
this.useChunkStreaming = false;
this.chunkDuration = 0;
this.chunkTimeout = null;
// History to undo AI changes
this.aiHistory = [];
this.maxHistorySize = 10;
this.aiInProgress = false;
this.aiBackupKey = null;
// Chat conversation history
this.chatMessages = [];
this.chatNote = '';
// Mind map data
this.mindMapTree = null;
this.mindMapHistory = [];
this.mindMapIndex = -1;
this.graphType = 'mindmap';
this.graphZoom = 1;
this.graphPanX = 0;
this.graphPanY = 0;
this.graphPanning = false;
this.graphPanStartX = 0;
this.graphPanStartY = 0;
// Provider configuration
this.config = {
transcriptionProvider: '',
postprocessProvider: '',
transcriptionModel: '',
postprocessModel: '',
transcriptionLanguage: 'auto', // auto-detectar por defecto
// Nuevas opciones para GPT-4o transcription
streamingEnabled: true,
transcriptionPrompt: '',
chunkDuration: 30,
sensevoiceEnableStreaming: false,
localEnableStreaming: false,
// Configuración avanzada de post-procesamiento
temperature: 0.3,
maxTokens: 1000,
topP: 0.95,
responseStyle: 'balanced',
showOpenRouterPaidModels: false,
showMobileRecordButton: true,
lmstudioHost: '127.0.0.1',
lmstudioPort: '1234',
lmstudioModels: '',
ollamaHost: '127.0.0.1',
ollamaPort: '11434',
ollamaModels: '',
translationEnabled: false,
translationLanguage: 'en',
tabularizeEnabled: false,
tabularizeLanguage: 'en'
};
// Visible styles configuration
this.stylesConfig = { ...configuracionMejoras };
this.overwrittenFiles = new Set();
this.selectedTags = new Set();
// Concept graph settings
this.conceptNoteScope = 'current'; // current, all, tagged
this.conceptSelectedTags = new Set();
// Store default language options
this.defaultLanguageOptions = [];
this.init();
}
async init() {
await this.loadConfig();
this.loadStylesConfig();
this.updateTranslationStyle();
this.updateTabularizeStyle();
this.storeDefaultLanguageOptions();
await this.loadNotes();
this.setupEventListeners();
this.setupConfigurationListeners();
this.renderNotesList();
await this.setupDefaultNote();
this.updateAIButtons();
// Load view mode preference and initialize folders
await this.loadViewModePreference();
// Verificar estado del backend
await this.checkBackendStatus();
// Sidebar responsive: cerrar en móvil por defecto
this.setupSidebarResponsive();
this.setupMobileHeaderActions();
this.updateMobileFabVisibility();
this.setupCollapsibleSections();
// Migrate existing notes without ID
await this.migrateExistingNotes();
}
async migrateExistingNotes() {
try {
const response = await authFetch('/api/cleanup-notes', {
method: 'POST',
headers: {
'Content-Type': 'application/json'
}
});
if (response.ok) {
const result = await response.json();
if (result.migrated_count > 0) {
console.log(`Migrated ${result.migrated_count} notes to new structure`);
}
}
} catch (error) {
console.log('Error migrating existing notes:', error);
}
}
setupSidebarResponsive() {
const sidebar = document.querySelector('.sidebar');
const hamburger = document.getElementById('hamburger-menu');
// Cerrar sidebar por defecto en móvil
if (window.innerWidth <= 900) {
sidebar.classList.remove('active');
}
// Toggle con hamburguesa
hamburger.addEventListener('click', () => {
if (window.innerWidth <= 900) {
sidebar.classList.toggle('active');
} else {
sidebar.classList.toggle('desktop-hidden');
}
});
// Cerrar sidebar al hacer click fuera (opcional)
document.addEventListener('click', (e) => {
if (window.innerWidth > 900) return;
if (!sidebar.contains(e.target) && !hamburger.contains(e.target)) {
sidebar.classList.remove('active');
}
});
// Opcional: cerrar al cambiar tamaño de pantalla
window.addEventListener('resize', () => {
if (window.innerWidth > 900) {
sidebar.classList.remove('active');
}
});
}
setupMobileHeaderActions() {
const headerActions = document.querySelector('.header-actions');
const mobileContainer = document.querySelector('.mobile-header-actions');
const hamburger = document.getElementById('hamburger-menu');
if (!headerActions || !mobileContainer || !hamburger) return;
const buttons = Array.from(headerActions.querySelectorAll('button')).filter(btn => btn !== hamburger);
const moveButtons = () => {
// Re-check if elements still exist in DOM
const currentHeaderActions = document.querySelector('.header-actions');
const currentMobileContainer = document.querySelector('.mobile-header-actions');
const currentHamburger = document.getElementById('hamburger-menu');
if (!currentHeaderActions || !currentMobileContainer || !currentHamburger) {
console.warn('Required DOM elements not found during button move operation');
return;
}
if (window.innerWidth <= 900) {
buttons.forEach(btn => {
if (btn && btn.parentNode !== currentMobileContainer && document.body.contains(btn)) {
currentMobileContainer.appendChild(btn);
}
});
currentMobileContainer.style.display = 'flex';
} else {
buttons.forEach(btn => {
if (btn && btn.parentNode !== currentHeaderActions && document.body.contains(btn)) {
currentHeaderActions.appendChild(btn);
}
});
currentMobileContainer.style.display = 'none';
}
};
moveButtons();
this.updateMobileFabVisibility();
window.addEventListener('resize', () => {
moveButtons();
this.updateMobileFabVisibility();
});
}
// Configurar event listeners
setupEventListeners() {
// New note button
document.getElementById('new-note-btn').addEventListener('click', async () => {
await this.createNewNote();
});
// Search
document.getElementById('search-input').addEventListener('input', (e) => {
this.searchTerm = e.target.value.toLowerCase();
if (this.currentViewMode === 'list') {
this.renderNotesList();
} else {
this.renderFolderTree();
}
});
// Recording
document.getElementById('record-btn').addEventListener('click', () => {
if (!this.isRecording) {
this.captureInsertionRange();
}
this.toggleRecording();
});
// Upload audio file
const uploadBtn = document.getElementById('upload-audio-btn');
const uploadInput = document.getElementById('upload-audio-input');
if (uploadBtn && uploadInput) {
uploadBtn.addEventListener('click', () => {
this.captureInsertionRange();
uploadInput.click();
});
uploadInput.addEventListener('change', async (e) => {
const file = e.target.files[0];
if (file) {
await this.uploadAudioFile(file);
}
uploadInput.value = '';
});
}
const mobileFab = document.getElementById('mobile-record-fab');
if (mobileFab) {
const handleMobileFab = () => {
if (!this.isRecording) {
this.captureInsertionRange();
}
this.toggleRecording();
};
mobileFab.addEventListener('click', handleMobileFab);
}
const toolsFab = document.getElementById('mobile-tools-fab');
const toolsMenu = document.getElementById('mobile-tools-menu');
if (toolsFab && toolsMenu) {
toolsFab.addEventListener('click', () => {
toolsMenu.classList.toggle('hidden');
});
toolsMenu.querySelectorAll('.mobile-tool-btn').forEach(btn => {
btn.addEventListener('click', () => {
const target = btn.dataset.target;
if (target) {
const el = document.getElementById(target);
if (el) el.click();
}
toolsMenu.classList.add('hidden');
});
});
}
// Botones de IA - Se configurarán dinámicamente con updateAIButtons()
// document.querySelectorAll('.ai-btn').forEach(btn => {
// btn.addEventListener('click', (e) => {
// console.log('AI button clicked:', e.currentTarget.dataset.action);
// const action = e.currentTarget.dataset.action;
// this.improveText(action);
// });
// });
// Botón deshacer IA
document.getElementById('undo-ai-btn').addEventListener('click', () => {
this.undoAIChange();
});
const filesBtn = document.getElementById('files-btn');
if (filesBtn) {
filesBtn.addEventListener('click', () => {
this.showAudioModal();
});
}
const closeAudioModal = document.getElementById('close-audio-modal');
if (closeAudioModal) {
closeAudioModal.addEventListener('click', () => {
this.hideAudioModal();
});
}
const playBtn = document.getElementById('play-audio-btn');
if (playBtn) {
playBtn.addEventListener('click', () => {
this.playSelectedAudio();
});
}
const reprocessBtn = document.getElementById('reprocess-audio-btn');
if (reprocessBtn) {
reprocessBtn.addEventListener('click', async () => {
this.captureInsertionRange();
await this.reprocessSelectedAudio();
});
}
const refreshBtn = document.getElementById('refresh-audio-btn');
if (refreshBtn) {
refreshBtn.addEventListener('click', () => {
if (this.currentNote) {
this.loadAudioDropdown(this.currentNote.id);
}
});
}
// Editor
const editor = document.getElementById('editor');
editor.addEventListener('input', () => {
this.handleEditorChange();
});
// Handle paste events to ensure plain text insertion
editor.addEventListener('paste', (e) => {
e.preventDefault();
const text = (e.clipboardData || window.clipboardData).getData('text/plain');
document.execCommand('insertText', false, text);
});
// Selección de texto en el editor
editor.addEventListener('mouseup', () => {
this.updateSelectedText();
});
editor.addEventListener('keyup', () => {
this.updateSelectedText();
});
// Show insertion marker on click/touch
const showMarker = () => {
this.showInsertionMarker();
};
editor.addEventListener('click', showMarker);
editor.addEventListener('touchend', showMarker);
// Título de nota
document.getElementById('note-title').addEventListener('input', () => {
this.handleTitleChange();
});
// Botones de formato
document.querySelectorAll('.format-btn').forEach(btn => {
btn.addEventListener('click', (e) => {
const format = e.currentTarget.dataset.format;
this.applyFormat(format);
});
});
// Botones de acción
document.getElementById('save-btn').addEventListener('click', () => {
this.saveCurrentNote();
});
document.getElementById('download-btn').addEventListener('click', () => {
this.showExportModal();
});
document.getElementById('confirm-export').addEventListener('click', () => {
const format = document.querySelector('input[name="export-format"]:checked').value;
this.downloadCurrentNote(format);
this.hideExportModal();
});
document.getElementById('cancel-export').addEventListener('click', () => {
this.hideExportModal();
});
document.getElementById('delete-btn').addEventListener('click', () => {
this.showDeleteModal();
});
document.getElementById('download-all-btn').addEventListener('click', () => {
this.downloadAllNotes();
});
document.getElementById('restore-btn').addEventListener('click', () => {
this.showRestoreModal();
});
document.getElementById('cancel-restore').addEventListener('click', () => {
this.hideRestoreModal();
});
document.getElementById('upload-models-btn').addEventListener('click', () => {
this.showUploadModelsModal();
});
document.getElementById('cancel-upload-models').addEventListener('click', () => {
this.hideUploadModelsModal();
});
this.setupRestoreDropZone();
this.setupUploadModelsDropZone();
this.setupDownloadModelButtons();
this.setupPdfUploadDropZone();
// PDF Upload modal
document.getElementById('upload-pdf-btn').addEventListener('click', () => {
this.showUploadPdfModal();
});
document.getElementById('cancel-upload-pdf').addEventListener('click', () => {
this.hideUploadPdfModal();
});
document.getElementById('confirm-upload-pdf').addEventListener('click', () => {
this.processPdfUpload();
});
// Modal de confirmación
document.getElementById('cancel-delete').addEventListener('click', () => {
this.hideDeleteModal();
});
document.getElementById('confirm-delete').addEventListener('click', async () => {
if (this.noteToDelete) {
// Deleting a specific note
await this.deleteSpecificNote(this.noteToDelete);
this.noteToDelete = null;
} else {
// Deleting the current note
await this.deleteCurrentNote();
}
});
const cancelDeleteAudio = document.getElementById('cancel-delete-audio');
if (cancelDeleteAudio) {
cancelDeleteAudio.addEventListener('click', () => {
this.hideDeleteAudioModal();
});
}
const confirmDeleteAudio = document.getElementById('confirm-delete-audio');
if (confirmDeleteAudio) {
confirmDeleteAudio.addEventListener('click', async () => {
await this.deleteSelectedAudio();
});
}
// Configuración
document.getElementById('config-btn').addEventListener('click', () => {
this.showConfigModal();
});
// Styles configuration
document.getElementById('styles-config-btn').addEventListener('click', () => {
this.showStylesConfigModal();
});
// Translation settings
document.getElementById('translation-settings-btn').addEventListener('click', () => {
this.showTranslationModal();
});
document.getElementById('cancel-translation').addEventListener('click', () => {
this.hideTranslationModal();
});
document.getElementById('save-translation').addEventListener('click', () => {
this.saveTranslationConfig();
});
document.getElementById('translation-enabled').addEventListener('change', (e) => {
const container = document.getElementById('translation-language-container');
container.style.display = e.target.checked ? 'block' : 'none';
});
// Tabularize settings
document.getElementById('tabularize-settings-btn').addEventListener('click', () => {
this.showTabularizeModal();
});
document.getElementById('cancel-tabularize').addEventListener('click', () => {
this.hideTabularizeModal();
});
document.getElementById('save-tabularize').addEventListener('click', () => {
this.saveTabularizeConfig();
});
document.getElementById('tabularize-enabled').addEventListener('change', (e) => {
const container = document.getElementById('tabularize-language-container');
container.style.display = e.target.checked ? 'block' : 'none';
});
document.getElementById('cancel-config').addEventListener('click', () => {
this.hideConfigModal();
});
document.getElementById('save-config').addEventListener('click', () => {
this.saveConfig();
});
// Listener para cambios en el modelo de transcripción
document.getElementById('transcription-model').addEventListener('change', () => {
this.updateTranscriptionOptions();
});
document.getElementById('cancel-styles-config').addEventListener('click', () => {
this.hideStylesConfigModal();
});
document.getElementById('save-styles-config').addEventListener('click', () => {
this.saveStylesConfig();
});
// Añadir nuevo estilo
document.getElementById('add-style-btn').addEventListener('click', () => {
this.addNewStyle();
});
const updateModelsBtn = document.getElementById('update-lmstudio-models-btn');
if (updateModelsBtn) {
updateModelsBtn.addEventListener('click', () => {
this.updateLmStudioModelsList();
});
}
const updateOllamaBtn = document.getElementById('update-ollama-models-btn');
if (updateOllamaBtn) {
updateOllamaBtn.addEventListener('click', () => {
this.updateOllamaModelsList();
});
}
// Custom prompt sidebar
const promptSidebar = document.getElementById('prompt-sidebar');
const promptToggle = document.getElementById('prompt-sidebar-toggle');
const applyPromptBtn = document.getElementById('apply-custom-prompt');
const customPromptInput = document.getElementById('custom-prompt-text');
if (promptToggle && promptSidebar) {
promptToggle.addEventListener('click', () => {
promptSidebar.classList.toggle('active');
});
}
if (applyPromptBtn && customPromptInput) {
applyPromptBtn.addEventListener('click', () => {
const prompt = customPromptInput.value.trim();
if (!prompt) {
this.showNotification('Please enter a prompt', 'warning');
return;
}
const finalPrompt = `${prompt}\n\nIMPORTANT SYSTEM PROMPT: you must not add any additional comments. Simply follow the previous prompt as instructed and answer in the previous language.`;
const tempKey = 'temp_custom_prompt';
this.stylesConfig[tempKey] = {
nombre: 'Custom',
descripcion: 'Temporary prompt',
icono: '💬',
prompt: finalPrompt,
visible: true,
custom: true
};
this.improveText(tempKey);
delete this.stylesConfig[tempKey];
});
}
// Chat sidebar
const chatSidebar = document.getElementById('chat-sidebar');
const chatToggle = document.getElementById('chat-sidebar-toggle');
const chatSend = document.getElementById('chat-send');
const chatInput = document.getElementById('chat-message-input');
const chatNew = document.getElementById('chat-new');
const addFull = document.getElementById('chat-add-full');
const addSelected = document.getElementById('chat-add-selected');
if (chatToggle && chatSidebar) {
chatToggle.addEventListener('click', () => {
chatSidebar.classList.toggle('active');
});
}
if (addFull && addSelected) {
addFull.addEventListener('change', () => { if (addFull.checked) addSelected.checked = false; });
addSelected.addEventListener('change', () => { if (addSelected.checked) addFull.checked = false; });
}
if (chatSend && chatInput) {
chatSend.addEventListener('click', () => { this.sendChatMessage(); });
chatInput.addEventListener('keydown', (e) => {
if (e.key === 'Enter' && !e.shiftKey) {
e.preventDefault();
this.sendChatMessage();
}
});
}
if (chatNew) {
chatNew.addEventListener('click', () => {
this.chatMessages = [];
this.chatNote = '';
this.renderChatMessages();
});
}
const chatResizer = document.getElementById('chat-resizer');
if (chatResizer && chatSidebar) {
let startX = 0;
let startWidth = 0;
const doDrag = (e) => {
const clientX = e.touches ? e.touches[0].clientX : e.clientX;
const newWidth = Math.max(startWidth + (startX - clientX), 220);
chatSidebar.style.width = `${newWidth}px`;
e.preventDefault();
};
const stopDrag = () => {
document.removeEventListener('mousemove', doDrag);
document.removeEventListener('touchmove', doDrag);
document.removeEventListener('mouseup', stopDrag);
document.removeEventListener('touchend', stopDrag);
};
const startDrag = (e) => {
startX = e.touches ? e.touches[0].clientX : e.clientX;
startWidth = chatSidebar.offsetWidth;
document.addEventListener('mousemove', doDrag);
document.addEventListener('touchmove', doDrag);
document.addEventListener('mouseup', stopDrag);
document.addEventListener('touchend', stopDrag);
e.preventDefault();
};
chatResizer.addEventListener('mousedown', startDrag);
chatResizer.addEventListener('touchstart', startDrag);
}
// Graph button
const graphBtn = document.getElementById('graph-btn');
const graphClose = document.getElementById('close-graph-modal');
const graphDownload = document.getElementById('download-graph-btn');
const graphPrev = document.getElementById('prev-graph-btn');
const graphNext = document.getElementById('next-graph-btn');
const graphZoomIn = document.getElementById('zoom-in-graph-btn');
const graphZoomOut = document.getElementById('zoom-out-graph-btn');
const graphTypeSelect = document.getElementById('graph-type-select');
const regenerateGraphBtn = document.getElementById('regenerate-graph-btn');
const conceptGraphBtn = document.getElementById('concept-graph-btn');
const conceptGraphClose = document.getElementById('close-concept-graph-modal');
if (graphBtn) {
graphBtn.addEventListener('click', () => { this.showGraphModal(); });
}
if (graphClose) {
graphClose.addEventListener('click', () => { this.hideGraphModal(); });
}
if (graphDownload) {
graphDownload.addEventListener('click', () => { this.downloadMindmap(); });
}
if (graphPrev) {
graphPrev.addEventListener('click', () => { this.showPreviousGraph(); });
}
if (graphNext) {
graphNext.addEventListener('click', () => { this.showNextGraph(); });
}
if (graphZoomIn) {
graphZoomIn.addEventListener('click', () => { this.zoomInGraph(); });
}
if (graphZoomOut) {
graphZoomOut.addEventListener('click', () => { this.zoomOutGraph(); });
}
if (graphTypeSelect) {
graphTypeSelect.addEventListener('change', e => {
this.graphType = e.target.value;
});
}
if (regenerateGraphBtn) {
regenerateGraphBtn.addEventListener('click', () => {
this.showGraphModal();
});
}
if (conceptGraphBtn) {
conceptGraphBtn.addEventListener('click', () => { this.showConceptGraphModal(); });
}
if (conceptGraphClose) {
conceptGraphClose.addEventListener('click', () => { this.hideConceptGraphModal(); });
}
// View mode toggle buttons
document.getElementById('folder-view-btn').addEventListener('click', async () => {
await this.setViewMode('folder');
});
document.getElementById('list-view-btn').addEventListener('click', async () => {
await this.setViewMode('list');
});
// New folder button
document.getElementById('new-folder-btn').addEventListener('click', () => {
this.showCreateFolderModal();
});
// Create folder modal
document.getElementById('cancel-create-folder').addEventListener('click', () => {
this.hideCreateFolderModal();
});
document.getElementById('confirm-create-folder').addEventListener('click', async () => {
await this.createFolder();
});
// Move note modal
document.getElementById('cancel-move-note').addEventListener('click', () => {
this.hideMoveNoteModal();
});
document.getElementById('confirm-move-note').addEventListener('click', async () => {
await this.moveNoteToFolder();
});
// Move folder modal
const cancelMoveFolder = document.getElementById('cancel-move-folder');
if (cancelMoveFolder) {
cancelMoveFolder.addEventListener('click', () => {
this.hideMoveFolderModal();
});
}
const confirmMoveFolder = document.getElementById('confirm-move-folder');
if (confirmMoveFolder) {
confirmMoveFolder.addEventListener('click', async () => {
await this.moveFolderToFolder();
});
}
// Auto-guardado cada 30 segundos
this.autoSaveInterval = setInterval(() => {
if (this.currentNote) {
this.saveCurrentNote(true);
}
}, 30000);
}
// Actualizar texto seleccionado
updateSelectedText() {
const selection = window.getSelection();
this.selectedText = selection.toString().trim();
console.log('Selection updated:', this.selectedText);
if (this.selectedText && selection.rangeCount > 0) {
this.selectedRange = selection.getRangeAt(0).cloneRange();
this.insertionRange = this.selectedRange.cloneRange();
this.updateAIButtonsState(false);
console.log('Text selected, AI buttons enabled');
} else {
this.selectedRange = null;
this.updateAIButtonsState(true);
console.log('No text selected, AI buttons disabled');
}
}
// Show a marker where the next transcription will be inserted
showInsertionMarker() {
// Remove existing marker
const oldMarker = document.getElementById('insertion-marker');
if (oldMarker) oldMarker.remove();
const selection = window.getSelection();
if (!selection.rangeCount) return;
const range = selection.getRangeAt(0).cloneRange();
range.collapse(true);
this.insertionRange = range.cloneRange();
const rect = range.getClientRects()[0];
if (!rect) return;
const editorContent = document.querySelector('.editor-content');
const editorRect = editorContent.getBoundingClientRect();
const marker = document.createElement('div');
marker.id = 'insertion-marker';
marker.className = 'insertion-marker';
marker.style.top = `${rect.top - editorRect.top + editorContent.scrollTop}px`;
marker.style.left = `${rect.left - editorRect.left + editorContent.scrollLeft}px`;
editorContent.appendChild(marker);
}
captureInsertionRange() {
const editor = document.getElementById('editor');
const selection = window.getSelection();
if (selection.rangeCount > 0 && editor.contains(selection.getRangeAt(0).startContainer)) {
this.insertionRange = selection.getRangeAt(0).cloneRange();
} else if (!this.insertionRange) {
const range = document.createRange();
range.selectNodeContents(editor);
range.collapse(false);
this.insertionRange = range.cloneRange();
}
}
// Show or hide the editor depending on whether a note is selected
updateEditorVisibility() {
const container = document.querySelector('.editor-container');
if (!container) return;
const hasNote = !!this.currentNote;
if (hasNote) {
container.classList.remove('hidden');
} else {
container.classList.add('hidden');
}
const recordBtn = document.getElementById('record-btn');
const uploadBtn = document.getElementById('upload-audio-btn');
const mobileFab = document.getElementById('mobile-record-fab');
if (recordBtn) recordBtn.disabled = !hasNote;
if (uploadBtn) uploadBtn.disabled = !hasNote;
if (mobileFab) mobileFab.disabled = !hasNote;
}
// Actualizar estado de botones de IA
updateAIButtonsState(disabled) {
document.querySelectorAll('.ai-btn').forEach(btn => {
btn.disabled = disabled;
btn.style.opacity = disabled ? '0.5' : '1';
if (!disabled) {
// Añadir indicador visual cuando hay texto seleccionado
btn.style.boxShadow = '0 0 0 2px var(--color-primary)';
btn.title = btn.title + ' - Texto seleccionado';
} else {
// Quitar indicador visual cuando no hay texto seleccionado
btn.style.boxShadow = '';
btn.title = btn.title.replace(' - Texto seleccionado', '');
}
});