-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathscript.js
More file actions
753 lines (662 loc) · 24.8 KB
/
script.js
File metadata and controls
753 lines (662 loc) · 24.8 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
/* ═══════════════════════════════════════════════════════════
NOTA — Notes App Script
Features: CRUD, localStorage, search+highlight, tags,
pin, lock, markdown, dark mode, export/import, stats
═══════════════════════════════════════════════════════════ */
'use strict';
// ── State ─────────────────────────────────────────────────
let notes = []; // Master array of note objects
let activeNoteId = null; // Currently open note id (null = new)
let activeTag = 'all'; // Sidebar tag filter
let searchQuery = ''; // Live search string
let sortMode = 'date'; // 'date' | 'title' | 'priority'
let tagFilters = []; // Dropdown tag checkboxes
let isPreview = false; // Markdown preview toggle
let isListView = false; // Grid vs list
let pendingDeleteId = null;// Confirm dialog target
// ── Storage keys ──────────────────────────────────────────
const STORAGE_KEY = 'nota_notes_v1';
const THEME_KEY = 'nota_theme';
// ── Helpers ───────────────────────────────────────────────
const $ = id => document.getElementById(id);
const uid = () => Date.now().toString(36) + Math.random().toString(36).slice(2);
const now = () => new Date().toISOString();
/** Format ISO date string to readable short form */
function fmtDate(iso) {
const d = new Date(iso);
const today = new Date();
const diff = today - d;
if (diff < 60000) return 'just now';
if (diff < 3600000) return `${Math.floor(diff / 60000)}m ago`;
if (diff < 86400000) return `${Math.floor(diff / 3600000)}h ago`;
if (diff < 604800000) return `${Math.floor(diff / 86400000)}d ago`;
return d.toLocaleDateString('en', { month: 'short', day: 'numeric' });
}
/** Check if ISO date is today */
const isToday = iso => new Date(iso).toDateString() === new Date().toDateString();
/** Check if ISO date is within this week */
const isThisWeek = iso => (Date.now() - new Date(iso)) < 7 * 86400000;
// ── localStorage ──────────────────────────────────────────
function saveNotes() {
localStorage.setItem(STORAGE_KEY, JSON.stringify(notes));
}
function loadNotes() {
try {
notes = JSON.parse(localStorage.getItem(STORAGE_KEY)) || [];
} catch {
notes = [];
}
}
// ── Markdown Parser ───────────────────────────────────────
/**
* Very lightweight markdown → HTML converter.
* Supports: # headings, **bold**, *italic*, `code`, - lists
*/
function parseMarkdown(text) {
if (!text) return '';
// Escape HTML first
let html = text
.replace(/&/g, '&')
.replace(/</g, '<')
.replace(/>/g, '>');
// Headings (## H2, # H1)
html = html.replace(/^### (.+)$/gm, '<h3>$1</h3>');
html = html.replace(/^## (.+)$/gm, '<h2>$1</h2>');
html = html.replace(/^# (.+)$/gm, '<h1>$1</h1>');
// Bold & Italic
html = html.replace(/\*\*(.+?)\*\*/g, '<strong>$1</strong>');
html = html.replace(/\*(.+?)\*/g, '<em>$1</em>');
// Inline code
html = html.replace(/`(.+?)`/g, '<code>$1</code>');
// Unordered list items
html = html.replace(/^- (.+)$/gm, '<li>$1</li>');
html = html.replace(/(<li>.*<\/li>)/s, '<ul>$1</ul>');
// Paragraphs (blank line separation)
html = html
.split(/\n\n+/)
.map(block => {
block = block.trim();
if (!block) return '';
if (/^<(h[1-3]|ul|ol|li)/.test(block)) return block;
// Wrap lines without block tags in <p>
return `<p>${block.replace(/\n/g, '<br>')}</p>`;
})
.join('');
return html;
}
/** Strip markdown for plain text preview in cards */
function stripMarkdown(text) {
return text
.replace(/#{1,3} /g, '')
.replace(/\*\*(.+?)\*\*/g, '$1')
.replace(/\*(.+?)\*/g, '$1')
.replace(/`(.+?)`/g, '$1')
.replace(/^- /gm, '');
}
// ── Search Highlighting ───────────────────────────────────
/**
* Wrap matching substrings in <mark> tags.
* @param {string} text - plain text
* @param {string} query - search query
*/
function highlight(text, query) {
if (!query || !text) return escapeHtml(text || '');
const escaped = escapeHtml(text);
const regex = new RegExp(`(${escapeRegex(query)})`, 'gi');
return escaped.replace(regex, '<mark>$1</mark>');
}
function escapeHtml(s) {
return s.replace(/&/g,'&').replace(/</g,'<').replace(/>/g,'>');
}
function escapeRegex(s) {
return s.replace(/[.*+?^${}()|[\]\\]/g, '\\$&');
}
// ── Filter & Sort notes ───────────────────────────────────
function getFilteredNotes() {
let filtered = [...notes];
// Tag filter (sidebar)
if (activeTag !== 'all') {
filtered = filtered.filter(n => n.tag === activeTag);
}
// Dropdown tag multi-filter
if (tagFilters.length > 0) {
filtered = filtered.filter(n => tagFilters.includes(n.tag));
}
// Search
if (searchQuery) {
const q = searchQuery.toLowerCase();
filtered = filtered.filter(n =>
(n.title || '').toLowerCase().includes(q) ||
(n.content || '').toLowerCase().includes(q)
);
}
// Sort
filtered.sort((a, b) => {
if (sortMode === 'date') return new Date(b.updatedAt) - new Date(a.updatedAt);
if (sortMode === 'title') return (a.title || '').localeCompare(b.title || '');
if (sortMode === 'priority') {
if (a.pinned && !b.pinned) return -1;
if (!a.pinned && b.pinned) return 1;
return new Date(b.updatedAt) - new Date(a.updatedAt);
}
return 0;
});
// Always pin to top if sort isn't already priority
if (sortMode !== 'priority') {
filtered.sort((a, b) => (b.pinned ? 1 : 0) - (a.pinned ? 1 : 0));
}
return filtered;
}
// ── Render Notes Grid ─────────────────────────────────────
function renderNotes() {
const grid = $('notesGrid');
const empty = $('emptyState');
const filtered = getFilteredNotes();
$('notesCount').textContent = `${filtered.length} note${filtered.length !== 1 ? 's' : ''}`;
if (filtered.length === 0) {
grid.innerHTML = '';
empty.classList.remove('hidden');
return;
}
empty.classList.add('hidden');
grid.innerHTML = filtered.map(note => renderCard(note)).join('');
// Attach click handlers
grid.querySelectorAll('.note-card').forEach(card => {
card.addEventListener('click', () => openNote(card.dataset.id));
});
}
/** Build HTML for one note card */
function renderCard(note) {
const plainBody = stripMarkdown(note.content || '');
const titleHtml = highlight(note.title || 'Untitled', searchQuery);
const bodyHtml = highlight(plainBody.slice(0, 200), searchQuery);
const pinClass = note.pinned ? ' pinned' : '';
const lockClass = note.locked ? ' locked' : '';
const lockIcon = note.locked ? '<span class="card-lock-icon">🔒</span>' : '';
const tagAttr = note.tag ? `data-tag="${note.tag}"` : '';
const tagHtml = note.tag
? `<span class="card-tag" data-tag="${note.tag}">${note.tag}</span>`
: '';
return `
<div class="note-card${pinClass}${lockClass}" data-id="${note.id}" ${tagAttr}>
${tagHtml}
<div class="card-title">${titleHtml || 'Untitled'}</div>
<div class="card-body">${note.locked ? '🔒 Password protected' : (bodyHtml || '<em style="opacity:.4">No content</em>')}</div>
<div class="card-footer">
<span class="card-date">${fmtDate(note.updatedAt)}</span>
${lockIcon}
</div>
</div>`;
}
// ── Stats & Insights ──────────────────────────────────────
function updateStats() {
$('statTotal').textContent = notes.length;
$('statToday').textContent = notes.filter(n => isToday(n.createdAt)).length;
$('statPinned').textContent = notes.filter(n => n.pinned).length;
$('statLocked').textContent = notes.filter(n => n.locked).length;
// Top tag
const tagCounts = {};
notes.forEach(n => { if (n.tag) tagCounts[n.tag] = (tagCounts[n.tag] || 0) + 1; });
const topTag = Object.entries(tagCounts).sort((a,b) => b[1]-a[1])[0];
$('insightTopTag').textContent = topTag ? `${topTag[0]} (${topTag[1]})` : '—';
// Avg word count
const totalWords = notes.reduce((sum, n) => {
return sum + (n.content || '').split(/\s+/).filter(Boolean).length;
}, 0);
const avg = notes.length ? Math.round(totalWords / notes.length) : 0;
$('insightAvgLen').textContent = `${avg} words`;
// This week
$('insightWeek').textContent = `${notes.filter(n => isThisWeek(n.createdAt)).length} notes`;
}
// ── Open / Close Editor ───────────────────────────────────
function openNote(id) {
if (id) {
const note = notes.find(n => n.id === id);
if (!note) return;
// Handle locked notes
if (note.locked) {
const pwd = prompt('Enter password to unlock this note:');
if (pwd === null) return;
if (pwd !== note.password) {
showToast('Incorrect password', 'error');
return;
}
}
activeNoteId = id;
$('editorTitle').textContent = 'Edit Note';
$('noteTitle').value = note.title || '';
$('noteContent').value = note.content || '';
$('editorMeta').textContent =
`Created ${fmtDate(note.createdAt)} · Edited ${fmtDate(note.updatedAt)}`;
// Tags
document.querySelectorAll('.tag-btn').forEach(btn => {
btn.classList.toggle('active', btn.dataset.tag === note.tag);
});
// Pin / lock state reflected in buttons
syncEditorButtons(note);
$('deleteNoteBtn').classList.remove('hidden');
} else {
// New note
activeNoteId = null;
$('editorTitle').textContent = 'New Note';
$('noteTitle').value = '';
$('noteContent').value = '';
$('editorMeta').textContent = '';
document.querySelectorAll('.tag-btn').forEach(b => b.classList.remove('active'));
$('deleteNoteBtn').classList.add('hidden');
}
// Reset preview
isPreview = false;
$('noteContent').classList.remove('hidden');
$('notePreview').classList.add('hidden');
$('editorPreviewToggle').classList.remove('active');
// Show panel
$('editorPanel').classList.remove('hidden');
$('overlay').classList.remove('hidden');
$('noteTitle').focus();
}
function closeEditor() {
$('editorPanel').classList.add('hidden');
$('overlay').classList.add('hidden');
activeNoteId = null;
}
function syncEditorButtons(note) {
const pinBtn = $('editorPinToggle');
const lockBtn = $('editorLockToggle');
pinBtn.style.color = note.pinned ? 'var(--pin)' : '';
lockBtn.style.color = note.locked ? 'var(--locked)' : '';
}
// ── Save Note ─────────────────────────────────────────────
function saveNote() {
const title = $('noteTitle').value.trim();
const content = $('noteContent').value.trim();
const activeTagBtn = document.querySelector('.tag-btn.active');
const tag = activeTagBtn ? activeTagBtn.dataset.tag : null;
if (!title && !content) {
showToast('Add a title or content first', 'error');
return;
}
if (activeNoteId) {
// Update existing
const idx = notes.findIndex(n => n.id === activeNoteId);
if (idx !== -1) {
notes[idx] = { ...notes[idx], title, content, tag, updatedAt: now() };
}
showToast('Note updated ✓', 'success');
} else {
// Create new
const note = {
id: uid(),
title,
content,
tag,
pinned: false,
locked: false,
password: null,
createdAt: now(),
updatedAt: now()
};
notes.unshift(note);
activeNoteId = note.id;
$('editorTitle').textContent = 'Edit Note';
$('deleteNoteBtn').classList.remove('hidden');
showToast('Note created ✓', 'success');
}
saveNotes();
renderNotes();
updateStats();
}
// Auto-save on content changes (debounced 1.5s)
let autoSaveTimer = null;
function scheduleAutoSave() {
clearTimeout(autoSaveTimer);
autoSaveTimer = setTimeout(() => {
if ($('noteTitle').value || $('noteContent').value) saveNote();
}, 1500);
}
// ── Delete Note ───────────────────────────────────────────
function confirmDelete(id) {
pendingDeleteId = id;
$('dialogOverlay').classList.remove('hidden');
}
function executeDelete() {
notes = notes.filter(n => n.id !== pendingDeleteId);
saveNotes();
renderNotes();
updateStats();
closeEditor();
$('dialogOverlay').classList.add('hidden');
pendingDeleteId = null;
showToast('Note deleted');
}
// ── Pin / Lock ────────────────────────────────────────────
function togglePin() {
if (!activeNoteId) return;
const note = notes.find(n => n.id === activeNoteId);
if (!note) return;
note.pinned = !note.pinned;
note.updatedAt = now();
saveNotes();
renderNotes();
updateStats();
syncEditorButtons(note);
showToast(note.pinned ? 'Note pinned 📌' : 'Note unpinned', 'success');
}
function toggleLock() {
if (!activeNoteId) return;
const note = notes.find(n => n.id === activeNoteId);
if (!note) return;
if (note.locked) {
// Unlock — verify password first
const pwd = prompt('Enter password to unlock:');
if (pwd === null) return;
if (pwd !== note.password) {
showToast('Wrong password', 'error');
return;
}
note.locked = false;
note.password = null;
showToast('Note unlocked 🔓', 'success');
} else {
// Lock — set password
const pwd = prompt('Set a password for this note:');
if (!pwd) return;
note.locked = true;
note.password = pwd;
showToast('Note locked 🔒', 'success');
closeEditor();
}
note.updatedAt = now();
saveNotes();
renderNotes();
updateStats();
if (!note.locked) syncEditorButtons(note);
}
// ── Markdown Preview ──────────────────────────────────────
function togglePreview() {
isPreview = !isPreview;
const content = $('noteContent').value;
$('notePreview').innerHTML = parseMarkdown(content);
$('noteContent').classList.toggle('hidden', isPreview);
$('notePreview').classList.toggle('hidden', !isPreview);
$('editorPreviewToggle').style.color = isPreview ? 'var(--accent)' : '';
}
// ── Markdown Toolbar ──────────────────────────────────────
/**
* Insert markdown syntax around selected text or at cursor.
* @param {string} syntax - The wrapper chars (e.g. '**')
* @param {boolean} isPrefix - If true, prepend to line (for # and -)
*/
function insertMarkdown(syntax, isPrefix) {
const ta = $('noteContent');
const start = ta.selectionStart;
const end = ta.selectionEnd;
const val = ta.value;
const sel = val.slice(start, end);
let newVal, newCursorPos;
if (isPrefix) {
// Find start of line
const lineStart = val.lastIndexOf('\n', start - 1) + 1;
newVal = val.slice(0, lineStart) + syntax + val.slice(lineStart);
newCursorPos = start + syntax.length;
} else {
newVal = val.slice(0, start) + syntax + sel + syntax + val.slice(end);
newCursorPos = sel ? end + syntax.length * 2 : start + syntax.length;
}
ta.value = newVal;
ta.selectionStart = ta.selectionEnd = newCursorPos;
ta.focus();
scheduleAutoSave();
}
// ── Export / Import ───────────────────────────────────────
function exportNotes() {
const blob = new Blob([JSON.stringify(notes, null, 2)], { type: 'application/json' });
const a = document.createElement('a');
a.href = URL.createObjectURL(blob);
a.download = `nota-export-${new Date().toISOString().slice(0,10)}.json`;
a.click();
URL.revokeObjectURL(a.href);
showToast('Notes exported 📤', 'success');
}
function importNotes(file) {
const reader = new FileReader();
reader.onload = e => {
try {
const imported = JSON.parse(e.target.result);
if (!Array.isArray(imported)) throw new Error('Invalid format');
// Merge: avoid duplicate IDs
const existingIds = new Set(notes.map(n => n.id));
const newNotes = imported.filter(n => !existingIds.has(n.id));
notes = [...newNotes, ...notes];
saveNotes();
renderNotes();
updateStats();
showToast(`Imported ${newNotes.length} note(s) ✓`, 'success');
} catch {
showToast('Import failed — invalid file', 'error');
}
};
reader.readAsText(file);
}
// ── Toast ─────────────────────────────────────────────────
/**
* Show a short notification toast.
* @param {string} msg
* @param {'success'|'error'|''} type
*/
function showToast(msg, type = '') {
const wrap = $('toastWrap');
const toast = document.createElement('div');
toast.className = `toast ${type}`;
toast.textContent = msg;
wrap.appendChild(toast);
setTimeout(() => {
toast.style.animation = 'toastOut 0.25s ease forwards';
setTimeout(() => toast.remove(), 260);
}, 2500);
}
// ── Dark / Light Mode ─────────────────────────────────────
function initTheme() {
const saved = localStorage.getItem(THEME_KEY) || 'dark';
document.documentElement.setAttribute('data-theme', saved);
}
function toggleTheme() {
const current = document.documentElement.getAttribute('data-theme');
const next = current === 'dark' ? 'light' : 'dark';
document.documentElement.setAttribute('data-theme', next);
localStorage.setItem(THEME_KEY, next);
}
// ── Keyboard Shortcut (/ to focus search) ────────────────
document.addEventListener('keydown', e => {
const tag = document.activeElement.tagName;
if (e.key === '/' && tag !== 'INPUT' && tag !== 'TEXTAREA') {
e.preventDefault();
$('searchInput').focus();
}
if (e.key === 'Escape') {
if (!$('dialogOverlay').classList.contains('hidden')) {
$('dialogOverlay').classList.add('hidden');
} else {
closeEditor();
}
}
// Ctrl/Cmd+S to save
if ((e.ctrlKey || e.metaKey) && e.key === 's') {
e.preventDefault();
if (!$('editorPanel').classList.contains('hidden')) saveNote();
}
});
// ── Event Wiring ──────────────────────────────────────────
function initEvents() {
// New note FAB
$('newNoteBtn').addEventListener('click', () => openNote(null));
// Editor close
$('editorClose').addEventListener('click', closeEditor);
$('overlay').addEventListener('click', closeEditor);
// Save
$('saveNoteBtn').addEventListener('click', saveNote);
// Delete
$('deleteNoteBtn').addEventListener('click', () => {
if (activeNoteId) confirmDelete(activeNoteId);
});
// Confirm dialog
$('dialogConfirm').addEventListener('click', executeDelete);
$('dialogCancel').addEventListener('click', () => {
$('dialogOverlay').classList.add('hidden');
pendingDeleteId = null;
});
// Pin / Lock
$('editorPinToggle').addEventListener('click', togglePin);
$('editorLockToggle').addEventListener('click', toggleLock);
// Preview
$('editorPreviewToggle').addEventListener('click', togglePreview);
// Auto-save on typing
$('noteTitle').addEventListener('input', scheduleAutoSave);
$('noteContent').addEventListener('input', () => {
scheduleAutoSave();
if (isPreview) {
$('notePreview').innerHTML = parseMarkdown($('noteContent').value);
}
});
// Theme toggle
$('themeToggle').addEventListener('click', toggleTheme);
// Search
$('searchInput').addEventListener('input', e => {
searchQuery = e.target.value.trim();
renderNotes();
});
// Tag pills (sidebar)
document.querySelectorAll('.tag-pill').forEach(btn => {
btn.addEventListener('click', () => {
activeTag = btn.dataset.tag;
document.querySelectorAll('.tag-pill').forEach(b => b.classList.remove('active'));
btn.classList.add('active');
renderNotes();
});
});
// Tag buttons in editor
document.querySelectorAll('.tag-btn').forEach(btn => {
btn.addEventListener('click', () => {
const isActive = btn.classList.contains('active');
document.querySelectorAll('.tag-btn').forEach(b => b.classList.remove('active'));
if (!isActive) btn.classList.add('active');
scheduleAutoSave();
});
});
// Markdown toolbar
document.querySelectorAll('.md-btn').forEach(btn => {
btn.addEventListener('click', () => {
const md = btn.dataset.md;
const isPrefix = btn.dataset.prefix === 'true';
insertMarkdown(md, isPrefix);
});
});
// Sort dropdown
document.querySelectorAll('input[name="sort"]').forEach(radio => {
radio.addEventListener('change', e => {
sortMode = e.target.value;
renderNotes();
});
});
// Dropdown tag filters
document.querySelectorAll('.tag-filter').forEach(item => {
item.addEventListener('click', () => {
const tag = item.dataset.tag;
const idx = tagFilters.indexOf(tag);
if (idx === -1) {
tagFilters.push(tag);
item.classList.add('active');
} else {
tagFilters.splice(idx, 1);
item.classList.remove('active');
}
// Update filter count badge
const count = tagFilters.length;
$('filterCount').textContent = count;
$('filterCount').classList.toggle('hidden', count === 0);
renderNotes();
});
});
// Filter dropdown toggle
$('filterBtn').addEventListener('click', e => {
e.stopPropagation();
$('filterDropdown').classList.toggle('open');
});
document.addEventListener('click', () => {
$('filterDropdown').classList.remove('open');
});
$('filterDropdown').addEventListener('click', e => e.stopPropagation());
// Export
$('exportBtn').addEventListener('click', exportNotes);
// Import
$('importBtn').addEventListener('click', () => $('importFile').click());
$('importFile').addEventListener('change', e => {
const file = e.target.files[0];
if (file) importNotes(file);
e.target.value = ''; // Reset so same file can be re-imported
});
// View toggle
$('viewGrid').addEventListener('click', () => {
isListView = false;
$('notesGrid').classList.remove('list-view');
$('viewGrid').classList.add('active');
$('viewList').classList.remove('active');
});
$('viewList').addEventListener('click', () => {
isListView = true;
$('notesGrid').classList.add('list-view');
$('viewList').classList.add('active');
$('viewGrid').classList.remove('active');
});
}
// ── Seed Data (first run) ─────────────────────────────────
function seedIfEmpty() {
if (notes.length > 0) return;
notes = [
{
id: uid(),
title: 'Welcome to Nota ✦',
content: `# Welcome!\n\nThis is your **personal notes app**. Here\'s what you can do:\n\n- Create notes with rich *markdown* support\n- Pin important notes to the top\n- Lock sensitive notes with a password\n- Tag notes as Work, Study, Ideas, or Personal\n- Export & import your notes as JSON\n\nPress **/** to quickly focus search, or **Ctrl+S** to save.`,
tag: 'Ideas',
pinned: true,
locked: false,
password: null,
createdAt: now(),
updatedAt: now()
},
{
id: uid(),
title: 'Markdown cheatsheet',
content: `# Heading 1\n## Heading 2\n\n**Bold text** and *italic text*\n\n\`inline code\`\n\n- List item one\n- List item two\n- List item three`,
tag: 'Study',
pinned: false,
locked: false,
password: null,
createdAt: now(),
updatedAt: now()
},
{
id: uid(),
title: 'Q2 Goals',
content: 'Ship the redesign by end of April.\nReview team performance.\nSchedule offsite planning session.',
tag: 'Work',
pinned: false,
locked: false,
password: null,
createdAt: now(),
updatedAt: now()
}
];
saveNotes();
}
// ── Bootstrap ─────────────────────────────────────────────
function init() {
initTheme();
loadNotes();
seedIfEmpty();
initEvents();
renderNotes();
updateStats();
}
// Run on DOM ready
document.addEventListener('DOMContentLoaded', init);