-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathscript.js
More file actions
840 lines (728 loc) · 27.3 KB
/
script.js
File metadata and controls
840 lines (728 loc) · 27.3 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
/* ===================================
NotepadX JavaScript
Handles all app functionality
=================================== */
// ===== DOM ELEMENTS =====
// Get references to HTML elements we'll be working with
const notepad = document.getElementById('notepad');
const saveBtn = document.getElementById('saveBtn');
const clearBtn = document.getElementById('clearBtn');
const statusMessage = document.getElementById('statusMessage');
const wordCountEl = document.getElementById('wordCount');
const searchInput = document.getElementById('searchInput');
const prevMatchBtn = document.getElementById('prevMatch');
const nextMatchBtn = document.getElementById('nextMatch');
const fontSizeSlider = document.getElementById('fontSize');
const fontSizeValue = document.getElementById('fontSizeValue');
const fontFamilySelect = document.getElementById('fontFamily');
const lineNumbers = document.getElementById('lineNumbers');
const quoteText = document.getElementById('quoteText');
const quoteAuthor = document.getElementById('quoteAuthor');
const newQuoteBtn = document.getElementById('newQuoteBtn');
// Export elements
const exportBtn = document.getElementById('exportBtn');
const exportMenu = document.getElementById('exportMenu');
const exportOptions = document.querySelectorAll('.export-option');
// Gist modal elements
const gistModal = document.getElementById('gistModal');
const closeGistModal = document.getElementById('closeGistModal');
const cancelGist = document.getElementById('cancelGist');
const createGist = document.getElementById('createGist');
const gistToken = document.getElementById('gistToken');
const gistFilename = document.getElementById('gistFilename');
const gistDescription = document.getElementById('gistDescription');
const gistPublic = document.getElementById('gistPublic');
const clearToken = document.getElementById('clearToken');
const tokenStatus = document.getElementById('tokenStatus');
const toggleTokenVisibility = document.getElementById('toggleTokenVisibility');
let lastSearch = '';
let lastIndex = -1;
// ===== CONSTANTS =====
// Key used to store notes in localStorage
const STORAGE_KEY = 'notepadx_content';
const FONT_SIZE_KEY = 'notepadx_font_size';
const FONT_FAMILY_KEY = 'notepadx_font_family';
// ===== QUOTES COLLECTION =====
const quotes = [
{ text: "The only way to do great work is to love what you do.", author: "Steve Jobs" },
{ text: "Innovation distinguishes between a leader and a follower.", author: "Steve Jobs" },
{ text: "The best time to plant a tree was 20 years ago. The second best time is now.", author: "Chinese Proverb" },
{ text: "Your time is limited, don't waste it living someone else's life.", author: "Steve Jobs" },
{ text: "Write what should not be forgotten.", author: "Isabel Allende" },
{ text: "Start writing, no matter what. The water does not flow until the faucet is turned on.", author: "Louis L'Amour" },
{ text: "You can make anything by writing.", author: "C.S. Lewis" },
{ text: "There is no greater agony than bearing an untold story inside you.", author: "Maya Angelou" },
{ text: "If you want to be a writer, you must do two things above all others: read a lot and write a lot.", author: "Stephen King" },
{ text: "The scariest moment is always just before you start.", author: "Stephen King" },
{ text: "You don't start out writing good stuff. You start out writing crap and thinking it's good stuff, and then gradually you get better at it.", author: "Octavia E. Butler" },
{ text: "The first draft is just you telling yourself the story.", author: "Terry Pratchett" },
{ text: "Ideas are like rabbits. You get a couple and learn how to handle them, and pretty soon you have a dozen.", author: "John Steinbeck" },
{ text: "Don't tell me the moon is shining; show me the glint of light on broken glass.", author: "Anton Chekhov" },
{ text: "The most valuable of all talents is that of never using two words when one will do.", author: "Thomas Jefferson" },
{ text: "Every secret of a writer's soul, every experience of their life, every quality of their mind, is written large in their works.", author: "Virginia Woolf" },
{ text: "Creativity is intelligence having fun.", author: "Albert Einstein" },
{ text: "The purpose of life is not to be happy. It is to be useful, to be honorable, to be compassionate.", author: "Ralph Waldo Emerson" },
{ text: "Success is not final, failure is not fatal: it is the courage to continue that counts.", author: "Winston Churchill" },
{ text: "Believe you can and you're halfway there.", author: "Theodore Roosevelt" }
];
// ===== INITIALIZATION =====
// This function runs when the page loads
function init() {
console.log('NotepadX initializing...');
// Load any previously saved notes from localStorage
loadNote();
// Set up event listeners for buttons
saveBtn.addEventListener('click', saveNote);
clearBtn.addEventListener('click', clearNote);
// Update word count and line numbers as the user types
const updateContent = () => {
updateWordCount();
updateLineNumbers();
};
notepad.addEventListener('input', updateContent);
notepad.addEventListener('keyup', updateContent);
notepad.addEventListener('change', updateContent);
notepad.addEventListener('paste', updateContent);
// Sync line numbers scrolling with textarea
notepad.addEventListener('scroll', syncScroll);
// Initialize line numbers
updateLineNumbers();
// Wire up search controls if present
if (searchInput) {
searchInput.addEventListener('keydown', (e) => {
if (e.key === 'Enter') {
e.preventDefault();
findNext();
}
});
}
if (nextMatchBtn) nextMatchBtn.addEventListener('click', findNext);
if (prevMatchBtn) prevMatchBtn.addEventListener('click', findPrev);
// Font size control (number input)
if (fontSizeSlider) {
const savedSize = loadFontSize();
applyFontSize(savedSize);
updateFontSizeUI(savedSize);
const onSizeChange = (e) => {
const raw = e.target.value;
const parsed = parseInt(raw, 10);
const size = Number.isFinite(parsed) ? parsed : savedSize;
const clamped = clamp(size, 10, 48);
applyFontSize(clamped);
updateFontSizeUI(clamped);
saveFontSize(clamped);
};
fontSizeSlider.addEventListener('input', onSizeChange);
fontSizeSlider.addEventListener('change', onSizeChange);
}
// Font family control
if (fontFamilySelect) {
const savedFont = loadFontFamily();
applyFontFamily(savedFont);
fontFamilySelect.value = savedFont;
fontFamilySelect.addEventListener('change', (e) => {
const font = e.target.value;
applyFontFamily(font);
saveFontFamily(font);
});
}
// Font family control
if (fontFamilySelect) {
const savedFont = loadFontFamily();
applyFontFamily(savedFont);
fontFamilySelect.value = savedFont;
fontFamilySelect.addEventListener('change', (e) => {
const font = e.target.value;
applyFontFamily(font);
saveFontFamily(font);
});
}
// Quote generator
if (newQuoteBtn) {
console.log('Setting up quote generator...');
newQuoteBtn.addEventListener('click', displayRandomQuote);
displayRandomQuote(); // Show initial quote
} else {
console.error('newQuoteBtn not found!');
}
// Export dropdown functionality
if (exportBtn && exportMenu) {
console.log('Setting up export menu...');
exportBtn.addEventListener('click', toggleExportMenu);
// Close dropdown when clicking outside
document.addEventListener('click', (e) => {
if (!exportBtn.contains(e.target) && !exportMenu.contains(e.target)) {
exportMenu.classList.remove('show');
exportBtn.setAttribute('aria-expanded', 'false');
}
});
// Handle export option clicks
exportOptions.forEach(option => {
option.addEventListener('click', (e) => {
const format = e.target.closest('.export-option').dataset.format;
console.log('Export format selected:', format);
handleExport(format);
exportMenu.classList.remove('show');
exportBtn.setAttribute('aria-expanded', 'false');
});
});
} else {
console.error('exportBtn or exportMenu not found!', {exportBtn, exportMenu});
}
// Gist modal functionality
if (closeGistModal) closeGistModal.addEventListener('click', closeModal);
if (cancelGist) cancelGist.addEventListener('click', closeModal);
if (createGist) createGist.addEventListener('click', createGitHubGist);
if (clearToken) clearToken.addEventListener('click', clearSavedToken);
if (toggleTokenVisibility) toggleTokenVisibility.addEventListener('click', toggleTokenDisplay);
// Close modal when clicking outside
if (gistModal) {
gistModal.addEventListener('click', (e) => {
if (e.target === gistModal) closeModal();
});
}
// Auto-save feature: save notes every 5 seconds if there's content
setInterval(autoSave, 5000);
console.log('NotepadX initialization complete!');
}
// ===== LOAD FUNCTION =====
/**
* Load saved notes from localStorage when the app starts
*/
function loadNote() {
try {
// Try to get saved content from localStorage
const savedContent = localStorage.getItem(STORAGE_KEY);
// If there's saved content, display it in the textarea
if (savedContent) {
notepad.value = savedContent;
showStatus('Previous notes loaded successfully');
updateWordCount();
updateLineNumbers();
}
} catch (error) {
// Handle any errors (e.g., localStorage not available)
showStatus('Could not load previous notes.', true);
console.error('Load error:', error);
}
}
// ===== FONT SIZE HELPERS =====
function applyFontSize(size) {
if (!notepad) return;
const clamped = clamp(size, 10, 48);
notepad.style.fontSize = `${clamped}px`;
// Apply same font size to line numbers
if (lineNumbers) lineNumbers.style.fontSize = `${clamped}px`;
}
function updateFontSizeUI(size) {
if (fontSizeSlider) fontSizeSlider.value = String(size);
if (fontSizeValue) fontSizeValue.textContent = `${size}px`;
}
function saveFontSize(size) {
try { localStorage.setItem(FONT_SIZE_KEY, String(size)); } catch {}
}
function loadFontSize() {
try {
const stored = localStorage.getItem(FONT_SIZE_KEY);
const parsed = stored ? parseInt(stored, 10) : 16;
if (Number.isFinite(parsed)) return clamp(parsed, 10, 48);
return 16;
} catch { return 16; }
}
function clamp(n, min, max) { return Math.min(max, Math.max(min, n)); }
// ===== FONT FAMILY HELPERS =====
function applyFontFamily(font) {
if (!notepad) return;
notepad.style.fontFamily = font;
// Apply same font family to line numbers
if (lineNumbers) lineNumbers.style.fontFamily = font;
}
function saveFontFamily(font) {
try { localStorage.setItem(FONT_FAMILY_KEY, font); } catch {}
}
function loadFontFamily() {
try {
const stored = localStorage.getItem(FONT_FAMILY_KEY);
return stored || 'Arial, sans-serif';
} catch { return 'Arial, sans-serif'; }
}
// ===== FONT FAMILY HELPERS =====
function applyFontFamily(font) {
if (!notepad) return;
notepad.style.fontFamily = font;
}
function saveFontFamily(font) {
try { localStorage.setItem(FONT_FAMILY_KEY, font); } catch {}
}
function loadFontFamily() {
try {
const stored = localStorage.getItem(FONT_FAMILY_KEY);
return stored || 'Arial, sans-serif';
} catch { return 'Arial, sans-serif'; }
}
// ===== SAVE FUNCTION =====
/**
* Save the current notes to localStorage
*/
function saveNote() {
try {
// Get the current text from the textarea
const content = notepad.value;
// Save it to localStorage
localStorage.setItem(STORAGE_KEY, content);
// Show success message
showStatus('Notes saved successfully');
updateWordCount();
} catch (error) {
// Handle any errors (e.g., storage quota exceeded)
showStatus('Failed to save notes. Please try again.', true);
console.error('Save error:', error);
}
}
// ===== AUTO-SAVE FUNCTION =====
/**
* Automatically save notes in the background
* This runs every 5 seconds
*/
function autoSave() {
const content = notepad.value;
// Only auto-save if there's content
if (content.trim().length > 0) {
try {
localStorage.setItem(STORAGE_KEY, content);
// Silent save - no status message to avoid disrupting user
// keep word count up-to-date on auto-save too
updateWordCount();
} catch (error) {
console.error('Auto-save error:', error);
}
}
}
// ===== CLEAR FUNCTION =====
/**
* Clear all text from the notepad
* Asks for confirmation before clearing
*/
function clearNote() {
// Ask user to confirm before clearing
const confirmClear = confirm('Are you sure you want to clear all notes? This cannot be undone.');
if (confirmClear) {
// Clear the textarea
notepad.value = '';
// Remove saved content from localStorage
localStorage.removeItem(STORAGE_KEY);
// Show confirmation message
showStatus('Notes cleared successfully');
// Focus back on textarea
notepad.focus();
updateWordCount();
}
}
// ===== DOWNLOAD FUNCTION =====
/**
* Download the current notes as a .txt file
*/
function downloadNote() {
// Get the current text content
const content = notepad.value;
// Check if there's content to download
if (content.trim().length === 0) {
showStatus('Nothing to download! Please write something first.', true);
return;
}
try {
// Create a Blob (binary large object) with the text content
const blob = new Blob([content], { type: 'text/plain' });
// Create a temporary download link
const url = URL.createObjectURL(blob);
const link = document.createElement('a');
// Set download filename with current date
const date = new Date().toISOString().slice(0, 10);
link.download = `notepadx_${date}.txt`;
// Set the URL and trigger download
link.href = url;
link.click();
// Clean up: remove the temporary URL
URL.revokeObjectURL(url);
// Show success message
showStatus('Notes downloaded successfully');
updateWordCount();
} catch (error) {
// Handle any errors
showStatus('Failed to download notes. Please try again.', true);
console.error('Download error:', error);
}
}
// ===== WORD COUNT FUNCTION =====
/**
* Update the word count display based on textarea content
*/
function updateWordCount() {
if (!wordCountEl) return;
const text = notepad.value.trim();
if (text.length === 0) {
wordCountEl.textContent = 'Words: 0';
return;
}
// Split by whitespace sequences to count words
const words = text.split(/\s+/).filter(Boolean);
wordCountEl.textContent = `Words: ${words.length}`;
}
// ===== SIMPLE SEARCH =====
/**
* Find next occurrence of search term and select it in the textarea
*/
function findNext() {
if (!searchInput) return;
const term = searchInput.value;
if (!term) return;
const content = notepad.value;
let startPos = 0;
if (lastSearch === term && lastIndex >= 0) {
startPos = lastIndex + 1; // search after previous match
}
const idx = content.toLowerCase().indexOf(term.toLowerCase(), startPos);
if (idx >= 0) {
notepad.focus();
notepad.setSelectionRange(idx, idx + term.length);
lastSearch = term;
lastIndex = idx;
showStatus(`Found at ${idx}`);
} else {
// wrap around search
const wrapIdx = content.toLowerCase().indexOf(term.toLowerCase(), 0);
if (wrapIdx >= 0) {
notepad.focus();
notepad.setSelectionRange(wrapIdx, wrapIdx + term.length);
lastSearch = term;
lastIndex = wrapIdx;
showStatus('Wrapped to first match');
} else {
showStatus('No matches found', true);
lastIndex = -1;
}
}
}
/**
* Find previous occurrence of search term and select it in the textarea
*/
function findPrev() {
if (!searchInput) return;
const term = searchInput.value;
if (!term) return;
const content = notepad.value;
let endPos = content.length;
if (lastSearch === term && lastIndex > 0) {
endPos = lastIndex - 1; // search before previous match
}
const idx = content.toLowerCase().lastIndexOf(term.toLowerCase(), endPos);
if (idx >= 0) {
notepad.focus();
notepad.setSelectionRange(idx, idx + term.length);
lastSearch = term;
lastIndex = idx;
showStatus(`Found at ${idx}`);
} else {
showStatus('No previous matches', true);
lastIndex = -1;
}
}
// ===== LINE NUMBERS =====
/**
* Update line numbers based on textarea content
*/
function updateLineNumbers() {
if (!lineNumbers || !notepad) return;
const text = notepad.value;
const lines = text.split('\n').length;
// Generate line numbers
let lineNumbersHtml = '';
for (let i = 1; i <= lines; i++) {
lineNumbersHtml += i + '\n';
}
lineNumbers.textContent = lineNumbersHtml;
}
/**
* Sync line numbers scrolling with textarea
*/
function syncScroll() {
if (!lineNumbers || !notepad) return;
lineNumbers.scrollTop = notepad.scrollTop;
}
// ===== QUOTE GENERATOR =====
/**
* Display a random motivational or literary quote
*/
function displayRandomQuote() {
if (!quoteText || !quoteAuthor || quotes.length === 0) return;
// Get a random quote from the array
const randomIndex = Math.floor(Math.random() * quotes.length);
const quote = quotes[randomIndex];
// Display the quote with a fade effect
quoteText.style.opacity = '0';
quoteAuthor.style.opacity = '0';
setTimeout(() => {
quoteText.textContent = `"${quote.text}"`;
quoteAuthor.textContent = `${quote.author}`;
quoteText.style.opacity = '1';
quoteAuthor.style.opacity = '1';
}, 200);
}
// ===== EXPORT FUNCTIONALITY =====
/**
* Toggle export dropdown menu
*/
function toggleExportMenu(e) {
e.stopPropagation();
const isOpen = exportMenu.classList.toggle('show');
exportBtn.setAttribute('aria-expanded', isOpen);
}
/**
* Handle export based on selected format
*/
function handleExport(format) {
const content = notepad.value;
if (!content.trim()) {
showStatus('Nothing to export! Please write some notes first.', true);
return;
}
switch(format) {
case 'txt':
exportAsTxt(content);
break;
case 'md':
exportAsMarkdown(content);
break;
case 'pdf':
exportAsPdf(content);
break;
case 'gist':
openGistModal();
break;
default:
showStatus('Unknown export format', true);
}
}
/**
* Export as plain text file
*/
function exportAsTxt(content) {
try {
const blob = new Blob([content], { type: 'text/plain' });
const url = URL.createObjectURL(blob);
const link = document.createElement('a');
link.href = url;
link.download = `notes_${Date.now()}.txt`;
document.body.appendChild(link);
link.click();
document.body.removeChild(link);
URL.revokeObjectURL(url);
showStatus('Notes exported as TXT successfully!');
} catch (error) {
showStatus('Failed to export as TXT', true);
console.error('TXT export error:', error);
}
}
/**
* Export as Markdown file
*/
function exportAsMarkdown(content) {
try {
// Add markdown metadata
const timestamp = new Date().toLocaleString();
const markdown = `# Notes from NotepadX\n\n**Date:** ${timestamp}\n\n---\n\n${content}`;
const blob = new Blob([markdown], { type: 'text/markdown' });
const url = URL.createObjectURL(blob);
const link = document.createElement('a');
link.href = url;
link.download = `notes_${Date.now()}.md`;
document.body.appendChild(link);
link.click();
document.body.removeChild(link);
URL.revokeObjectURL(url);
showStatus('Notes exported as Markdown successfully!');
} catch (error) {
showStatus('Failed to export as Markdown', true);
console.error('Markdown export error:', error);
}
}
/**
* Export as PDF file
*/
function exportAsPdf(content) {
try {
// Check if jsPDF is loaded
if (typeof window.jspdf === 'undefined') {
showStatus('PDF library not loaded. Please refresh the page.', true);
return;
}
const { jsPDF } = window.jspdf;
const doc = new jsPDF();
// Add title
doc.setFontSize(16);
doc.text('Notes from NotepadX', 20, 20);
// Add timestamp
doc.setFontSize(10);
doc.text(`Date: ${new Date().toLocaleString()}`, 20, 30);
// Add content
doc.setFontSize(12);
const lines = doc.splitTextToSize(content, 170);
doc.text(lines, 20, 40);
// Save PDF
doc.save(`notes_${Date.now()}.pdf`);
showStatus('Notes exported as PDF successfully!');
} catch (error) {
showStatus('Failed to export as PDF', true);
console.error('PDF export error:', error);
}
}
/**
* Open GitHub Gist modal
*/
function openGistModal() {
if (gistModal) {
gistModal.classList.add('show');
gistModal.setAttribute('aria-hidden', 'false');
// Load saved token if exists and show status
const savedToken = localStorage.getItem('github_token');
if (savedToken && gistToken) {
gistToken.value = savedToken;
if (tokenStatus) {
tokenStatus.style.display = 'flex';
}
} else {
if (tokenStatus) {
tokenStatus.style.display = 'none';
}
}
}
}
/**
* Close GitHub Gist modal
*/
function closeModal() {
if (gistModal) {
gistModal.classList.remove('show');
gistModal.setAttribute('aria-hidden', 'true');
}
}
/**
* Create GitHub Gist
*/
async function createGitHubGist() {
const token = gistToken.value.trim();
const filename = gistFilename.value.trim() || 'notes.md';
const description = gistDescription.value.trim() || 'Notes from NotepadX';
const isPublic = gistPublic.checked;
const content = notepad.value;
if (!token) {
showStatus('Please enter your GitHub token', true);
return;
}
if (!content.trim()) {
showStatus('Nothing to share! Please write some notes first.', true);
return;
}
try {
showStatus('Creating Gist...');
const response = await fetch('https://api.github.com/gists', {
method: 'POST',
headers: {
'Authorization': `token ${token}`,
'Content-Type': 'application/json',
},
body: JSON.stringify({
description: description,
public: isPublic,
files: {
[filename]: {
content: content
}
}
})
});
if (!response.ok) {
throw new Error(`GitHub API error: ${response.status}`);
}
const data = await response.json();
// Save token for future use
localStorage.setItem('github_token', token);
// Close modal
closeModal();
// Show success with link
showStatus('Gist created successfully!');
// Open gist in new tab
window.open(data.html_url, '_blank');
} catch (error) {
showStatus('Failed to create Gist. Check your token and try again.', true);
console.error('Gist creation error:', error);
}
}
/**
* Clear saved GitHub token
*/
function clearSavedToken() {
if (confirm('Are you sure you want to clear your saved GitHub token?')) {
localStorage.removeItem('github_token');
if (gistToken) {
gistToken.value = '';
}
if (tokenStatus) {
tokenStatus.style.display = 'none';
}
showStatus('GitHub token cleared successfully');
}
}
/**
* Toggle token visibility (show/hide password)
*/
function toggleTokenDisplay() {
if (!gistToken) return;
if (gistToken.type === 'password') {
gistToken.type = 'text';
if (toggleTokenVisibility) {
toggleTokenVisibility.textContent = '🙈';
toggleTokenVisibility.title = 'Hide token';
}
} else {
gistToken.type = 'password';
if (toggleTokenVisibility) {
toggleTokenVisibility.textContent = '👁️';
toggleTokenVisibility.title = 'Show token';
}
}
}
// ===== STATUS MESSAGE FUNCTION =====
/**
* Display status messages to the user
* @param {string} message - The message to display
* @param {boolean} isError - Whether this is an error message
*/
function showStatus(message, isError = false) {
// Set the message text
statusMessage.textContent = message;
// Apply appropriate styling
statusMessage.className = 'status-message show';
if (isError) {
statusMessage.classList.add('error');
}
// Hide the message after 3 seconds
setTimeout(() => {
statusMessage.className = 'status-message';
statusMessage.textContent = '';
}, 3000);
}
// ===== KEYBOARD SHORTCUTS =====
/**
* Handle keyboard shortcuts for common actions
*/
document.addEventListener('keydown', (event) => {
// Ctrl+S or Cmd+S to save (prevent default browser save dialog)
if ((event.ctrlKey || event.metaKey) && event.key === 's') {
event.preventDefault();
saveNote();
}
});
// ===== START THE APP =====
// Initialize the app when the DOM is fully loaded
document.addEventListener('DOMContentLoaded', init);