File size: 40,468 Bytes
453dce9
 
 
 
 
bb1105b
453dce9
bb1105b
 
453dce9
bb1105b
 
 
 
 
 
 
 
 
 
453dce9
bb1105b
 
 
453dce9
bb1105b
 
 
 
 
 
 
 
 
 
 
 
453dce9
 
 
 
 
 
bb1105b
 
453dce9
 
 
 
bb1105b
 
 
 
453dce9
 
bb1105b
 
 
 
453dce9
 
 
bb1105b
 
 
 
 
 
453dce9
bb1105b
 
453dce9
 
 
bb1105b
 
 
453dce9
bb1105b
 
453dce9
 
 
 
bb1105b
 
453dce9
bb1105b
453dce9
bb1105b
 
453dce9
 
 
 
 
 
bb1105b
 
 
 
 
 
 
 
 
 
 
 
453dce9
bb1105b
 
 
453dce9
 
 
bb1105b
 
 
 
 
 
 
 
453dce9
 
bb1105b
 
 
 
 
 
 
453dce9
 
 
bb1105b
 
 
 
 
 
 
 
453dce9
 
 
 
bb1105b
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
453dce9
 
 
 
bb1105b
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
453dce9
 
bb1105b
453dce9
bb1105b
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
453dce9
bb1105b
 
 
 
 
 
453dce9
bb1105b
 
 
 
 
 
 
 
 
 
 
 
 
 
 
453dce9
bb1105b
453dce9
bb1105b
 
 
 
 
 
 
 
 
 
 
 
 
453dce9
bb1105b
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
453dce9
bb1105b
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
453dce9
 
 
 
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
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>DeepNotes - Personal Knowledge Management</title>
    <script src="https://cdn.tailwindcss.com"></script>
    <script src="https://cdnjs.cloudflare.com/ajax/libs/jspdf/2.5.1/jspdf.umd.min.js"></script>
    <script src="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.4.0/js/all.min.js"></script>
    <style>
        .markdown h1 { @apply text-2xl font-bold my-4; }
        .markdown h2 { @apply text-xl font-semibold my-3; }
        .markdown h3 { @apply text-lg font-medium my-2; }
        .markdown p { @apply my-2; }
        .markdown ul { @apply list-disc pl-5 my-2; }
        .markdown ol { @apply list-decimal pl-5 my-2; }
        .markdown blockquote { @apply border-l-4 border-gray-300 pl-4 italic my-2; }
        .markdown pre { @apply bg-gray-100 p-2 rounded my-2; }
        .markdown code { @apply bg-gray-100 px-1 rounded text-sm; }
        .markdown a { @apply text-blue-600 hover:underline; }
        
        .note-link { @apply text-purple-600 hover:underline cursor-pointer; }
        .backlink { @apply bg-blue-50 p-2 rounded my-1; }
        .tag { @apply bg-gray-100 px-2 py-1 rounded-full text-xs inline-flex items-center mr-1; }
        
        .sidebar-item { @apply px-3 py-2 rounded hover:bg-gray-100 cursor-pointer flex items-center; }
        .sidebar-item.active { @apply bg-blue-50 text-blue-600; }
        
        .note-card { @apply border p-3 rounded mb-2 hover:bg-gray-50 cursor-pointer; }
        .note-card.active { @apply border-blue-300 bg-blue-50; }
        
        ::-webkit-scrollbar { width: 8px; height: 8px; }
        ::-webkit-scrollbar-track { @apply bg-gray-100; }
        ::-webkit-scrollbar-thumb { @apply bg-gray-300 rounded-full; }
        ::-webkit-scrollbar-thumb:hover { @apply bg-gray-400; }
        
        [contenteditable="true"]:focus { outline: none; }
    </style>
</head>
<body class="bg-gray-50 font-sans flex h-screen overflow-hidden">
    <!-- Sidebar -->
    <div class="w-64 bg-white border-r flex flex-col h-full">
        <div class="p-4 border-b">
            <h1 class="text-xl font-bold flex items-center">
                <i class="fas fa-brain mr-2 text-blue-500"></i> DeepNotes
            </h1>
        </div>
        
        <div class="flex-1 overflow-y-auto">
            <div class="p-3 border-b">
                <button id="newNoteBtn" class="w-full bg-blue-600 text-white py-2 rounded flex items-center justify-center">
                    <i class="fas fa-plus mr-2"></i> New Note
                </button>
            </div>
            
            <div class="p-3">
                <div class="relative">
                    <input type="text" id="searchNotes" placeholder="Search notes..." class="w-full pl-8 pr-3 py-2 border rounded text-sm">
                    <i class="fas fa-search absolute left-3 top-3 text-gray-400"></i>
                </div>
            </div>
            
            <div class="p-3">
                <div class="flex items-center justify-between mb-2">
                    <h3 class="font-medium">Subjects</h3>
                    <button id="newSubjectBtn" class="text-gray-500 hover:text-gray-700">
                        <i class="fas fa-plus"></i>
                    </button>
                </div>
                <div id="subjectList" class="space-y-1">
                    <!-- Subjects will be added here dynamically -->
                </div>
            </div>
            
            <div class="p-3 border-t">
                <div class="flex items-center justify-between mb-2">
                    <h3 class="font-medium">Tags</h3>
                </div>
                <div id="tagList" class="flex flex-wrap gap-1">
                    <!-- Tags will be added here dynamically -->
                </div>
            </div>
        </div>
        
        <div class="p-3 border-t text-sm text-gray-500">
            <div class="flex justify-between mb-1">
                <span>Storage</span>
                <span id="storageUsage">0% used</span>
            </div>
            <div class="w-full bg-gray-200 rounded-full h-1">
                <div id="storageBar" class="bg-blue-500 h-1 rounded-full" style="width: 0%"></div>
            </div>
        </div>
    </div>
    
    <!-- Main Content -->
    <div class="flex-1 flex flex-col h-full overflow-hidden">
        <!-- Note List -->
        <div class="w-72 border-r bg-white overflow-y-auto">
            <div class="p-3 border-b flex justify-between items-center">
                <h3 id="currentSubject" class="font-medium">All Notes</h3>
                <div class="flex space-x-1">
                    <button id="sortNotes" class="text-gray-500 hover:text-gray-700">
                        <i class="fas fa-sort-alpha-down"></i>
                    </button>
                    <button id="filterNotes" class="text-gray-500 hover:text-gray-700">
                        <i class="fas fa-filter"></i>
                    </button>
                </div>
            </div>
            
            <div id="noteList" class="divide-y">
                <!-- Notes will be added here dynamically -->
            </div>
        </div>
        
        <!-- Note Editor -->
        <div class="flex-1 flex flex-col overflow-hidden bg-white">
            <div class="border-b p-3 flex justify-between items-center">
                <div>
                    <input id="noteTitle" type="text" placeholder="Note title" class="text-xl font-bold w-full focus:outline-none">
                    <div id="noteMeta" class="text-xs text-gray-500 mt-1">
                        <span id="noteCreated">Created: -</span>
                        <span id="noteUpdated" class="ml-3">Updated: -</span>
                    </div>
                </div>
                <div class="flex space-x-2">
                    <button id="exportPdfBtn" class="px-3 py-1 bg-gray-100 rounded text-sm hover:bg-gray-200">
                        <i class="fas fa-file-pdf mr-1"></i> PDF
                    </button>
                    <button id="deleteNoteBtn" class="px-3 py-1 bg-red-50 text-red-600 rounded text-sm hover:bg-red-100">
                        <i class="fas fa-trash mr-1"></i> Delete
                    </button>
                </div>
            </div>
            
            <div class="p-3 border-b">
                <div class="flex flex-wrap items-center gap-2">
                    <select id="noteSubject" class="border rounded px-2 py-1 text-sm">
                        <option value="">No subject</option>
                        <!-- Subjects will be added here dynamically -->
                    </select>
                    <div id="noteTags" class="flex flex-wrap gap-1">
                        <input type="text" id="newTagInput" placeholder="Add tag" class="border rounded-full px-2 py-1 text-sm w-24">
                    </div>
                </div>
            </div>
            
            <div id="editorToolbar" class="border-b p-2 flex flex-wrap gap-1">
                <button data-cmd="h1" class="w-8 h-8 flex items-center justify-center hover:bg-gray-100 rounded">
                    <i class="fas fa-heading"></i>1
                </button>
                <button data-cmd="h2" class="w-8 h-8 flex items-center justify-center hover:bg-gray-100 rounded">
                    <i class="fas fa-heading"></i>2
                </button>
                <button data-cmd="h3" class="w-8 h-8 flex items-center justify-center hover:bg-gray-100 rounded">
                    <i class="fas fa-heading"></i>3
                </button>
                <div class="w-px h-6 bg-gray-300 mx-1"></div>
                <button data-cmd="bold" class="w-8 h-8 flex items-center justify-center hover:bg-gray-100 rounded">
                    <i class="fas fa-bold"></i>
                </button>
                <button data-cmd="italic" class="w-8 h-8 flex items-center justify-center hover:bg-gray-100 rounded">
                    <i class="fas fa-italic"></i>
                </button>
                <div class="w-px h-6 bg-gray-300 mx-1"></div>
                <button data-cmd="insertunorderedlist" class="w-8 h-8 flex items-center justify-center hover:bg-gray-100 rounded">
                    <i class="fas fa-list-ul"></i>
                </button>
                <button data-cmd="insertorderedlist" class="w-8 h-8 flex items-center justify-center hover:bg-gray-100 rounded">
                    <i class="fas fa-list-ol"></i>
                </button>
                <div class="w-px h-6 bg-gray-300 mx-1"></div>
                <button data-cmd="createlink" class="w-8 h-8 flex items-center justify-center hover:bg-gray-100 rounded">
                    <i class="fas fa-link"></i>
                </button>
                <button data-cmd="quote" class="w-8 h-8 flex items-center justify-center hover:bg-gray-100 rounded">
                    <i class="fas fa-quote-right"></i>
                </button>
                <button data-cmd="code" class="w-8 h-8 flex items-center justify-center hover:bg-gray-100 rounded">
                    <i class="fas fa-code"></i>
                </button>
            </div>
            
            <div id="editorContent" class="flex-1 overflow-y-auto p-4 markdown" contenteditable="true" data-placeholder="Start writing your note here..."></div>
            
            <div id="backlinksPanel" class="border-t p-3 hidden">
                <h3 class="font-medium mb-2">Linked References</h3>
                <div id="backlinksList">
                    <!-- Backlinks will be added here dynamically -->
                </div>
            </div>
        </div>
    </div>
    
    <!-- Modals -->
    <div id="newSubjectModal" class="fixed inset-0 bg-black bg-opacity-50 flex items-center justify-center hidden">
        <div class="bg-white rounded-lg p-4 w-96">
            <h3 class="font-bold text-lg mb-3">Create New Subject</h3>
            <input type="text" id="newSubjectInput" placeholder="Subject name" class="w-full border rounded px-3 py-2 mb-3">
            <div class="flex justify-end space-x-2">
                <button id="cancelNewSubject" class="px-4 py-2 bg-gray-100 rounded hover:bg-gray-200">Cancel</button>
                <button id="confirmNewSubject" class="px-4 py-2 bg-blue-600 text-white rounded hover:bg-blue-700">Create</button>
            </div>
        </div>
    </div>
    
    <div id="linkNoteModal" class="fixed inset-0 bg-black bg-opacity-50 flex items-center justify-center hidden">
        <div class="bg-white rounded-lg p-4 w-96 max-h-[80vh] overflow-hidden flex flex-col">
            <h3 class="font-bold text-lg mb-3">Link to Note</h3>
            <input type="text" id="searchLinkNote" placeholder="Search notes..." class="w-full border rounded px-3 py-2 mb-3">
            <div id="linkNoteResults" class="flex-1 overflow-y-auto">
                <!-- Note search results will be added here dynamically -->
            </div>
            <div class="flex justify-end space-x-2 mt-3">
                <button id="cancelLinkNote" class="px-4 py-2 bg-gray-100 rounded hover:bg-gray-200">Cancel</button>
            </div>
        </div>
    </div>

    <script>
        // Initialize the app
        document.addEventListener('DOMContentLoaded', function() {
            const { jsPDF } = window.jspdf;
            
            // App state
            let state = {
                notes: JSON.parse(localStorage.getItem('deepnotes-notes')) || [],
                subjects: JSON.parse(localStorage.getItem('deepnotes-subjects')) || ['General', 'Work', 'Personal'],
                tags: JSON.parse(localStorage.getItem('deepnotes-tags')) || ['important', 'todo', 'reference'],
                currentNoteId: null,
                currentSubject: null,
                sortBy: 'updated',
                sortDirection: 'desc'
            };
            
            // DOM elements
            const elements = {
                // Sidebar
                subjectList: document.getElementById('subjectList'),
                tagList: document.getElementById('tagList'),
                newSubjectBtn: document.getElementById('newSubjectBtn'),
                newNoteBtn: document.getElementById('newNoteBtn'),
                searchNotes: document.getElementById('searchNotes'),
                storageUsage: document.getElementById('storageUsage'),
                storageBar: document.getElementById('storageBar'),
                
                // Note list
                noteList: document.getElementById('noteList'),
                currentSubject: document.getElementById('currentSubject'),
                sortNotes: document.getElementById('sortNotes'),
                filterNotes: document.getElementById('filterNotes'),
                
                // Editor
                noteTitle: document.getElementById('noteTitle'),
                noteCreated: document.getElementById('noteCreated'),
                noteUpdated: document.getElementById('noteUpdated'),
                noteSubject: document.getElementById('noteSubject'),
                noteTags: document.getElementById('noteTags'),
                newTagInput: document.getElementById('newTagInput'),
                editorContent: document.getElementById('editorContent'),
                editorToolbar: document.getElementById('editorToolbar'),
                backlinksPanel: document.getElementById('backlinksPanel'),
                backlinksList: document.getElementById('backlinksList'),
                exportPdfBtn: document.getElementById('exportPdfBtn'),
                deleteNoteBtn: document.getElementById('deleteNoteBtn'),
                
                // Modals
                newSubjectModal: document.getElementById('newSubjectModal'),
                newSubjectInput: document.getElementById('newSubjectInput'),
                cancelNewSubject: document.getElementById('cancelNewSubject'),
                confirmNewSubject: document.getElementById('confirmNewSubject'),
                linkNoteModal: document.getElementById('linkNoteModal'),
                searchLinkNote: document.getElementById('searchLinkNote'),
                linkNoteResults: document.getElementById('linkNoteResults'),
                cancelLinkNote: document.getElementById('cancelLinkNote')
            };
            
            // Initialize the app
            function init() {
                renderSubjects();
                renderTags();
                renderNoteList();
                updateStorageUsage();
                
                // Set up event listeners
                setupEventListeners();
                
                // Create a default note if none exist
                if (state.notes.length === 0) {
                    createNewNote();
                } else {
                    // Load the most recent note
                    loadNote(state.notes[0].id);
                }
            }
            
            // Set up event listeners
            function setupEventListeners() {
                // Sidebar
                elements.newSubjectBtn.addEventListener('click', showNewSubjectModal);
                elements.newNoteBtn.addEventListener('click', createNewNote);
                elements.searchNotes.addEventListener('input', debounce(renderNoteList, 300));
                
                // Note list
                elements.sortNotes.addEventListener('click', toggleSort);
                
                // Editor
                elements.noteTitle.addEventListener('input', saveNote);
                elements.editorContent.addEventListener('input', debounce(saveNote, 500));
                elements.noteSubject.addEventListener('change', saveNote);
                elements.newTagInput.addEventListener('keydown', handleTagInput);
                
                // Toolbar buttons
                elements.editorToolbar.querySelectorAll('button').forEach(btn => {
                    btn.addEventListener('click', function() {
                        const cmd = this.getAttribute('data-cmd');
                        if (cmd === 'quote') {
                            insertTextAtCursor('\n> ');
                        } else if (cmd === 'code') {
                            insertTextAtCursor('`code`');
                        } else {
                            document.execCommand(cmd, false, null);
                        }
                        elements.editorContent.focus();
                    });
                });
                
                // Modals
                elements.cancelNewSubject.addEventListener('click', hideNewSubjectModal);
                elements.confirmNewSubject.addEventListener('click', addNewSubject);
                elements.newSubjectInput.addEventListener('keydown', function(e) {
                    if (e.key === 'Enter') addNewSubject();
                });
                
                elements.cancelLinkNote.addEventListener('click', hideLinkNoteModal);
                elements.searchLinkNote.addEventListener('input', debounce(searchNotesForLinking, 300));
                
                // Other buttons
                elements.exportPdfBtn.addEventListener('click', exportToPdf);
                elements.deleteNoteBtn.addEventListener('click', deleteCurrentNote);
                
                // Handle clicks on note links
                document.addEventListener('click', function(e) {
                    if (e.target.classList.contains('note-link')) {
                        e.preventDefault();
                        const noteId = e.target.getAttribute('data-note-id');
                        if (noteId) loadNote(noteId);
                    }
                });
            }
            
            // Render subjects in sidebar
            function renderSubjects() {
                elements.subjectList.innerHTML = '';
                
                // All notes item
                const allNotesItem = document.createElement('div');
                allNotesItem.className = `sidebar-item ${!state.currentSubject ? 'active' : ''}`;
                allNotesItem.innerHTML = `<i class="fas fa-sticky-note mr-2"></i> All Notes`;
                allNotesItem.addEventListener('click', () => {
                    state.currentSubject = null;
                    renderNoteList();
                    document.querySelectorAll('.sidebar-item').forEach(el => el.classList.remove('active'));
                    allNotesItem.classList.add('active');
                });
                elements.subjectList.appendChild(allNotesItem);
                
                // Subject items
                state.subjects.forEach(subject => {
                    const item = document.createElement('div');
                    item.className = `sidebar-item ${state.currentSubject === subject ? 'active' : ''}`;
                    item.innerHTML = `<i class="fas fa-folder mr-2"></i> ${subject}`;
                    item.addEventListener('click', () => {
                        state.currentSubject = subject;
                        renderNoteList();
                        document.querySelectorAll('.sidebar-item').forEach(el => el.classList.remove('active'));
                        item.classList.add('active');
                    });
                    elements.subjectList.appendChild(item);
                });
                
                // Also render in subject dropdown
                elements.noteSubject.innerHTML = '<option value="">No subject</option>';
                state.subjects.forEach(subject => {
                    const option = document.createElement('option');
                    option.value = subject;
                    option.textContent = subject;
                    elements.noteSubject.appendChild(option);
                });
            }
            
            // Render tags in sidebar
            function renderTags() {
                elements.tagList.innerHTML = '';
                state.tags.forEach(tag => {
                    const tagEl = document.createElement('div');
                    tagEl.className = 'tag cursor-pointer hover:bg-gray-200';
                    tagEl.innerHTML = `<i class="fas fa-tag mr-1"></i> ${tag}`;
                    tagEl.addEventListener('click', () => {
                        // Filter notes by this tag
                        state.currentSubject = null;
                        renderNoteList(tag);
                        document.querySelectorAll('.sidebar-item').forEach(el => el.classList.remove('active'));
                    });
                    elements.tagList.appendChild(tagEl);
                });
            }
            
            // Render note list
            function renderNoteList(filterTag = null) {
                elements.noteList.innerHTML = '';
                
                // Update current subject display
                elements.currentSubject.textContent = state.currentSubject || 'All Notes';
                if (filterTag) {
                    elements.currentSubject.textContent = `Tag: ${filterTag}`;
                }
                
                // Filter notes
                let filteredNotes = [...state.notes];
                
                if (state.currentSubject) {
                    filteredNotes = filteredNotes.filter(note => note.subject === state.currentSubject);
                }
                
                if (filterTag) {
                    filteredNotes = filteredNotes.filter(note => note.tags.includes(filterTag));
                }
                
                // Search filter
                const searchTerm = elements.searchNotes.value.toLowerCase();
                if (searchTerm) {
                    filteredNotes = filteredNotes.filter(note => 
                        note.title.toLowerCase().includes(searchTerm) || 
                        note.content.toLowerCase().includes(searchTerm)
                    );
                }
                
                // Sort notes
                filteredNotes.sort((a, b) => {
                    if (state.sortBy === 'title') {
                        return a.title.localeCompare(b.title) * (state.sortDirection === 'asc' ? 1 : -1);
                    } else {
                        const dateA = new Date(state.sortBy === 'created' ? a.createdAt : a.updatedAt);
                        const dateB = new Date(state.sortBy === 'created' ? b.createdAt : b.updatedAt);
                        return (dateB - dateA) * (state.sortDirection === 'asc' ? -1 : 1);
                    }
                });
                
                // Display notes
                if (filteredNotes.length === 0) {
                    elements.noteList.innerHTML = '<div class="p-4 text-gray-500 text-center">No notes found</div>';
                    return;
                }
                
                filteredNotes.forEach(note => {
                    const noteCard = document.createElement('div');
                    noteCard.className = `note-card ${note.id === state.currentNoteId ? 'active' : ''}`;
                    noteCard.innerHTML = `
                        <h4 class="font-medium truncate">${note.title || 'Untitled Note'}</h4>
                        <p class="text-xs text-gray-500">${formatDate(note.updatedAt)}</p>
                        <div class="text-sm text-gray-600 truncate mt-1">${getNoteExcerpt(note.content)}</div>
                        ${note.tags.length > 0 ? `
                            <div class="mt-2 flex flex-wrap gap-1">
                                ${note.tags.map(tag => `<span class="tag">${tag}</span>`).join('')}
                            </div>
                        ` : ''}
                    `;
                    noteCard.addEventListener('click', () => loadNote(note.id));
                    elements.noteList.appendChild(noteCard);
                });
            }
            
            // Get note excerpt for preview
            function getNoteExcerpt(content) {
                const plainText = content.replace(/<[^>]*>/g, ' ').replace(/\s+/g, ' ').trim();
                return plainText.substring(0, 100) + (plainText.length > 100 ? '...' : '');
            }
            
            // Format date for display
            function formatDate(dateString) {
                const date = new Date(dateString);
                return date.toLocaleDateString() + ' ' + date.toLocaleTimeString([], {hour: '2-digit', minute:'2-digit'});
            }
            
            // Create a new note
            function createNewNote() {
                const newNote = {
                    id: generateId(),
                    title: 'Untitled Note',
                    content: '',
                    subject: '',
                    tags: [],
                    createdAt: new Date().toISOString(),
                    updatedAt: new Date().toISOString(),
                    linkedNotes: []
                };
                
                state.notes.unshift(newNote);
                saveState();
                renderNoteList();
                loadNote(newNote.id);
            }
            
            // Load a note into the editor
            function loadNote(noteId) {
                const note = state.notes.find(n => n.id === noteId);
                if (!note) return;
                
                state.currentNoteId = noteId;
                
                // Update UI
                elements.noteTitle.value = note.title;
                elements.editorContent.innerHTML = note.content || '';
                elements.noteSubject.value = note.subject || '';
                
                // Update dates
                elements.noteCreated.textContent = `Created: ${formatDate(note.createdAt)}`;
                elements.noteUpdated.textContent = `Updated: ${formatDate(note.updatedAt)}`;
                
                // Update tags
                elements.noteTags.innerHTML = '';
                note.tags.forEach(tag => {
                    const tagEl = document.createElement('span');
                    tagEl.className = 'tag';
                    tagEl.innerHTML = `${tag} <i class="fas fa-times ml-1 cursor-pointer" data-tag="${tag}"></i>`;
                    tagEl.querySelector('i').addEventListener('click', (e) => {
                        e.stopPropagation();
                        removeTagFromNote(tag);
                    });
                    elements.noteTags.appendChild(tagEl);
                });
                elements.noteTags.appendChild(elements.newTagInput);
                
                // Update backlinks
                updateBacklinks(noteId);
                
                // Highlight active note in list
                document.querySelectorAll('.note-card').forEach(el => {
                    el.classList.toggle('active', el.getAttribute('data-note-id') === noteId);
                });
                
                // Re-render note list to update active state
                renderNoteList();
            }
            
            // Save the current note
            function saveNote() {
                if (!state.currentNoteId) return;
                
                const noteIndex = state.notes.findIndex(n => n.id === state.currentNoteId);
                if (noteIndex === -1) return;
                
                const note = state.notes[noteIndex];
                note.title = elements.noteTitle.value;
                note.content = elements.editorContent.innerHTML;
                note.subject = elements.noteSubject.value;
                note.updatedAt = new Date().toISOString();
                
                // Update note in state
                state.notes[noteIndex] = note;
                saveState();
                
                // Update UI
                elements.noteUpdated.textContent = `Updated: ${formatDate(note.updatedAt)}`;
                
                // Update backlinks for all notes that might reference this one
                updateAllBacklinks();
                
                // Re-render note list to show updated title/date
                renderNoteList();
            }
            
            // Delete the current note
            function deleteCurrentNote() {
                if (!state.currentNoteId) return;
                
                if (!confirm('Are you sure you want to delete this note?')) return;
                
                // Remove note from state
                state.notes = state.notes.filter(n => n.id !== state.currentNoteId);
                saveState();
                
                // Load another note if available
                if (state.notes.length > 0) {
                    loadNote(state.notes[0].id);
                } else {
                    // Create a new note if none left
                    createNewNote();
                }
                
                renderNoteList();
            }
            
            // Handle tag input
            function handleTagInput(e) {
                if (e.key === 'Enter' && e.target.value.trim()) {
                    const tag = e.target.value.trim();
                    addTagToNote(tag);
                    e.target.value = '';
                }
            }
            
            // Add a tag to the current note
            function addTagToNote(tag) {
                if (!state.currentNoteId) return;
                
                const noteIndex = state.notes.findIndex(n => n.id === state.currentNoteId);
                if (noteIndex === -1) return;
                
                // Add to note tags if not already present
                if (!state.notes[noteIndex].tags.includes(tag)) {
                    state.notes[noteIndex].tags.push(tag);
                    saveState();
                    
                    // Add to global tags if not present
                    if (!state.tags.includes(tag)) {
                        state.tags.push(tag);
                        saveState();
                        renderTags();
                    }
                    
                    // Update UI
                    loadNote(state.currentNoteId);
                }
            }
            
            // Remove a tag from the current note
            function removeTagFromNote(tag) {
                if (!state.currentNoteId) return;
                
                const noteIndex = state.notes.findIndex(n => n.id === state.currentNoteId);
                if (noteIndex === -1) return;
                
                state.notes[noteIndex].tags = state.notes[noteIndex].tags.filter(t => t !== tag);
                saveState();
                
                // Update UI
                loadNote(state.currentNoteId);
            }
            
            // Show new subject modal
            function showNewSubjectModal() {
                elements.newSubjectInput.value = '';
                elements.newSubjectModal.classList.remove('hidden');
                elements.newSubjectInput.focus();
            }
            
            // Hide new subject modal
            function hideNewSubjectModal() {
                elements.newSubjectModal.classList.add('hidden');
            }
            
            // Add a new subject
            function addNewSubject() {
                const subject = elements.newSubjectInput.value.trim();
                if (subject && !state.subjects.includes(subject)) {
                    state.subjects.push(subject);
                    saveState();
                    renderSubjects();
                    hideNewSubjectModal();
                }
            }
            
            // Toggle sort order
            function toggleSort() {
                if (state.sortBy === 'updated') {
                    state.sortBy = 'title';
                    state.sortDirection = 'asc';
                } else if (state.sortBy === 'title' && state.sortDirection === 'asc') {
                    state.sortBy = 'title';
                    state.sortDirection = 'desc';
                } else {
                    state.sortBy = 'updated';
                    state.sortDirection = 'desc';
                }
                
                renderNoteList();
            }
            
            // Update backlinks for the current note
            function updateBacklinks(noteId) {
                const backlinks = state.notes.filter(note => 
                    note.id !== noteId && 
                    note.content.includes(`data-note-id="${noteId}"`)
                );
                
                if (backlinks.length > 0) {
                    elements.backlinksPanel.classList.remove('hidden');
                    elements.backlinksList.innerHTML = '';
                    
                    backlinks.forEach(note => {
                        const backlink = document.createElement('div');
                        backlink.className = 'backlink';
                        backlink.innerHTML = `
                            <a href="#" class="font-medium note-link" data-note-id="${note.id}">${note.title || 'Untitled Note'}</a>
                            <p class="text-sm text-gray-600 mt-1">${getNoteExcerpt(note.content)}</p>
                        `;
                        elements.backlinksList.appendChild(backlink);
                    });
                } else {
                    elements.backlinksPanel.classList.add('hidden');
                }
            }
            
            // Update backlinks for all notes
            function updateAllBacklinks() {
                state.notes.forEach(note => {
                    if (note.id === state.currentNoteId) {
                        updateBacklinks(note.id);
                    }
                });
            }
            
            // Show link note modal
            function showLinkNoteModal() {
                elements.searchLinkNote.value = '';
                elements.linkNoteResults.innerHTML = '';
                elements.linkNoteModal.classList.remove('hidden');
                elements.searchLinkNote.focus();
            }
            
            // Hide link note modal
            function hideLinkNoteModal() {
                elements.linkNoteModal.classList.add('hidden');
            }
            
            // Search notes for linking
            function searchNotesForLinking() {
                const query = elements.searchLinkNote.value.toLowerCase();
                elements.linkNoteResults.innerHTML = '';
                
                const filteredNotes = state.notes.filter(note => 
                    note.id !== state.currentNoteId && 
                    (note.title.toLowerCase().includes(query) || note.content.toLowerCase().includes(query))
                );
                
                if (filteredNotes.length === 0) {
                    elements.linkNoteResults.innerHTML = '<div class="p-4 text-gray-500 text-center">No notes found</div>';
                    return;
                }
                
                filteredNotes.forEach(note => {
                    const result = document.createElement('div');
                    result.className = 'p-3 border-b hover:bg-gray-50 cursor-pointer';
                    result.innerHTML = `
                        <h4 class="font-medium">${note.title || 'Untitled Note'}</h4>
                        <p class="text-sm text-gray-600 mt-1">${getNoteExcerpt(note.content)}</p>
                    `;
                    result.addEventListener('click', () => {
                        insertTextAtCursor(`[[${note.title}]]`);
                        hideLinkNoteModal();
                    });
                    elements.linkNoteResults.appendChild(result);
                });
            }
            
            // Insert text at cursor position
            function insertTextAtCursor(text) {
                const selection = window.getSelection();
                if (selection.rangeCount > 0) {
                    const range = selection.getRangeAt(0);
                    range.deleteContents();
                    range.insertNode(document.createTextNode(text));
                    
                    // Move cursor to end of inserted text
                    range.setStartAfter(range.endContainer);
                    range.collapse(true);
                    selection.removeAllRanges();
                    selection.addRange(range);
                }
                
                elements.editorContent.focus();
            }
            
            // Export current note to PDF
            function exportToPdf() {
                if (!state.currentNoteId) return;
                
                const note = state.notes.find(n => n.id === state.currentNoteId);
                if (!note) return;
                
                const doc = new jsPDF();
                
                // Add title
                doc.setFontSize(20);
                doc.text(note.title || 'Untitled Note', 15, 15);
                
                // Add metadata
                doc.setFontSize(10);
                doc.setTextColor(100);
                doc.text(`Created: ${formatDate(note.createdAt)}`, 15, 25);
                doc.text(`Updated: ${formatDate(note.updatedAt)}`, 15, 30);
                
                if (note.subject) {
                    doc.text(`Subject: ${note.subject}`, 15, 35);
                }
                
                if (note.tags.length > 0) {
                    doc.text(`Tags: ${note.tags.join(', ')}`, 15, 40);
                }
                
                // Add content
                const content = note.content.replace(/<[^>]*>/g, ' ');
                const lines = doc.splitTextToSize(content, 180);
                
                doc.setFontSize(12);
                doc.setTextColor(0);
                doc.text(lines, 15, 50);
                
                // Save the PDF
                doc.save(`${note.title || 'note'}.pdf`);
            }
            
            // Update storage usage display
            function updateStorageUsage() {
                const dataSize = JSON.stringify(state).length;
                const percentUsed = Math.min(100, Math.round(dataSize / 5000 * 100)); // 5KB max for demo
                
                elements.storageUsage.textContent = `${percentUsed}% used`;
                elements.storageBar.style.width = `${percentUsed}%`;
            }
            
            // Save app state to localStorage
            function saveState() {
                localStorage.setItem('deepnotes-notes', JSON.stringify(state.notes));
                localStorage.setItem('deepnotes-subjects', JSON.stringify(state.subjects));
                localStorage.setItem('deepnotes-tags', JSON.stringify(state.tags));
                updateStorageUsage();
            }
            
            // Generate a random ID
            function generateId() {
                return Math.random().toString(36).substring(2, 15);
            }
            
            // Debounce function
            function debounce(func, wait) {
                let timeout;
                return function() {
                    const context = this, args = arguments;
                    clearTimeout(timeout);
                    timeout = setTimeout(() => func.apply(context, args), wait);
                };
            }
            
            // Initialize the app
            init();
        });
    </script>
<p style="border-radius: 8px; text-align: center; font-size: 12px; color: #fff; margin-top: 16px;position: fixed; left: 8px; bottom: 8px; z-index: 10; background: rgba(0, 0, 0, 0.8); padding: 4px 8px;">Made with <img src="https://enzostvs-deepsite.hf.space/logo.svg" alt="DeepSite Logo" style="width: 16px; height: 16px; vertical-align: middle;display:inline-block;margin-right:3px;filter:brightness(0) invert(1);"><a href="https://enzostvs-deepsite.hf.space" style="color: #fff;text-decoration: underline;" target="_blank" >DeepSite</a> - 🧬 <a href="https://enzostvs-deepsite.hf.space?remix=LVCprt/mynotes-1" style="color: #fff;text-decoration: underline;" target="_blank" >Remix</a></p></body>
</html>