-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathscript.js
More file actions
1014 lines (869 loc) · 31 KB
/
Copy pathscript.js
File metadata and controls
1014 lines (869 loc) · 31 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
/**
* WordLite - A minimal word processor
* No frameworks, no dependencies, just vanilla JavaScript
*/
// Main application state
const wordlite = {
currentDocument: {
id: Date.now().toString(),
title: 'Untitled Document',
content: '',
lastSaved: null
},
documents: [],
saveTimeout: null,
isZenMode: false,
isThemeDark: false,
commandPaletteOpen: false,
commands: [
{ id: 'save', name: 'Save Document', shortcut: 'Ctrl+S', action: () => wordlite.saveDocument() },
{ id: 'new', name: 'New Document', shortcut: 'Ctrl+N', action: () => wordlite.createNewDocument() },
{ id: 'zen', name: 'Toggle Zen Mode', shortcut: 'Ctrl+E', action: () => wordlite.toggleZenMode() },
{ id: 'theme', name: 'Toggle Dark Theme', shortcut: 'Ctrl+Shift+D', action: () => wordlite.toggleTheme() },
{ id: 'export-pdf', name: 'Export as PDF', shortcut: '', action: () => wordlite.exportAsPDF() },
{ id: 'export-md', name: 'Export as Markdown', shortcut: '', action: () => wordlite.exportAsMarkdown() },
{ id: 'export-wdoc', name: 'Export as WDOC', shortcut: '', action: () => wordlite.exportAsWDOC() }
]
};
// DOM Elements
const editor = document.getElementById('editor');
const documentTitle = document.getElementById('documentTitle');
const formatToolbar = document.getElementById('formatToolbar');
const documentList = document.getElementById('documentList');
const wordCount = document.getElementById('wordCount');
const saveStatus = document.getElementById('saveStatus');
const sidebar = document.getElementById('sidebar');
const menuToggle = document.getElementById('menuToggle');
const commandPalette = document.getElementById('commandPalette');
const commandInput = document.getElementById('commandInput');
const commandList = document.getElementById('commandList');
/**
* Initialize the application
*/
function initApp() {
// Load documents from localStorage
loadDocumentsFromStorage();
// Initialize document, update UI
updateEditorContent();
updateWordCount();
populateDocumentList();
// Setup event listeners
setupEventListeners();
// Register service worker for offline support
registerServiceWorker();
// Start autosave
startAutoSave();
// Apply saved theme preference
applyThemePreference();
}
/**
* Set up all event listeners
*/
function setupEventListeners() {
// Editor events
editor.addEventListener('input', handleEditorInput);
editor.addEventListener('mouseup', handleTextSelection);
editor.addEventListener('keyup', handleTextSelection);
// Document title events
documentTitle.addEventListener('change', handleTitleChange);
// Toolbar button events
document.getElementById('btn-bold').addEventListener('click', () => formatText('bold'));
document.getElementById('btn-italic').addEventListener('click', () => formatText('italic'));
document.getElementById('btn-underline').addEventListener('click', () => formatText('underline'));
document.getElementById('btn-heading').addEventListener('click', () => formatText('h1'));
document.getElementById('btn-quote').addEventListener('click', () => formatText('quote'));
document.getElementById('btn-code').addEventListener('click', () => formatText('code'));
document.getElementById('btn-theme').addEventListener('click', toggleTheme);
document.getElementById('btn-zen').addEventListener('click', toggleZenMode);
document.getElementById('exitZenBtn').addEventListener('click', toggleZenMode);
document.getElementById('btn-save').addEventListener('click', saveDocument);
// Export options
document.getElementById('export-pdf').addEventListener('click', exportAsPDF);
document.getElementById('export-docx').addEventListener('click', exportAsDocx);
document.getElementById('export-md').addEventListener('click', exportAsMarkdown);
document.getElementById('export-wdoc').addEventListener('click', exportAsWDOC);
// Floating toolbar format buttons
const formatButtons = formatToolbar.querySelectorAll('button');
formatButtons.forEach(button => {
button.addEventListener('click', () => {
formatText(button.getAttribute('data-format'));
});
});
// Sidebar toggle for mobile
menuToggle.addEventListener('click', () => {
sidebar.classList.toggle('open');
});
// Set up font selection event listeners
document.querySelectorAll('[data-font]').forEach(item => {
item.addEventListener('click', (e) => {
e.preventDefault();
const font = e.target.getAttribute('data-font');
document.execCommand('fontName', false, font);
});
});
// Set up font size selection event listeners
document.querySelectorAll('[data-size]').forEach(item => {
item.addEventListener('click', (e) => {
e.preventDefault();
const size = e.target.getAttribute('data-size');
document.execCommand('fontSize', false, size);
});
});
document.getElementById('btn-paste').addEventListener('click', handlePaste);
function handlePaste() {
// Focus editor
editor.focus();
// Use execCommand for paste
if (document.execCommand('paste')) {
// Success using execCommand
return;
}
// Fallback using Clipboard API
try {
navigator.clipboard.readText().then(text => {
// Insert at cursor position
document.execCommand('insertText', false, text);
});
} catch (err) {
console.error('Failed to read clipboard:', err);
alert('Please use Ctrl+V to paste content');
}
}
// Add event listener for import button
document.getElementById('importDoc').addEventListener('click', () => {
document.getElementById('fileInput').click();
});
// Add event listener for file input change
document.getElementById('fileInput').addEventListener('change', handleFileSelect);
function handleFileSelect(event) {
const file = event.target.files[0];
if (!file) return;
const fileName = file.name;
const fileExtension = fileName.split('.').pop().toLowerCase();
if (fileExtension === 'wdoc') {
// Handle WDOC files
const reader = new FileReader();
reader.onload = function(e) {
try {
const wdoc = JSON.parse(e.target.result);
// Create new document
wordlite.currentDocument = {
id: Date.now().toString(),
title: wdoc.title || 'Imported Document',
content: wdoc.content || '',
lastSaved: null
};
// Update UI
updateEditorContent();
updateWordCount();
saveDocument();
} catch (error) {
console.error('Error parsing WDOC file:', error);
alert('Invalid WDOC file format');
}
};
reader.readAsText(file);
} else if (fileExtension === 'docx' || fileExtension === 'doc') {
// For DOCX files, we'd need mammoth.js library
// This is a simplified placeholder
alert('To import Word files (.docx), please add the mammoth.js library.\n\nBasic steps to add support:\n1. Add mammoth.js to lib folder\n2. Use it to convert docx to HTML');
// Guide users what to do
console.log('To implement Word import:');
console.log('1. Add mammoth.js: npm install mammoth');
console.log('2. Use mammoth.extractRawText() to convert docx to text');
console.log('3. Insert the text into the editor');
}
// Reset file input
event.target.value = '';
}
// New document button
document.getElementById('newDoc').addEventListener('click', createNewDocument);
// Document click handler (to hide floating toolbar)
document.addEventListener('click', (e) => {
if (!editor.contains(e.target) && !formatToolbar.contains(e.target)) {
formatToolbar.style.display = 'none';
}
// Close command palette if clicking outside
if (!commandPalette.contains(e.target) && commandPalette.style.display === 'block') {
commandPalette.style.display = 'none';
wordlite.commandPaletteOpen = false;
}
});
// Keyboard shortcuts
document.addEventListener('keydown', handleKeyboardShortcuts);
// Command palette input
commandInput.addEventListener('input', filterCommands);
commandInput.addEventListener('keydown', navigateCommandsList);
}
// Add event listeners for table functionality
document.getElementById('btn-table').addEventListener('click', showTableDialog);
document.getElementById('insertTableCancel').addEventListener('click', hideTableDialog);
document.getElementById('insertTableConfirm').addEventListener('click', insertTable);
// Show table dialog
function showTableDialog() {
document.getElementById('tableDialog').style.display = 'flex';
}
// Hide table dialog
function hideTableDialog() {
document.getElementById('tableDialog').style.display = 'none';
}
// Insert table into editor
function insertTable() {
const rows = parseInt(document.getElementById('tableRows').value);
const cols = parseInt(document.getElementById('tableCols').value);
if (isNaN(rows) || isNaN(cols) || rows < 1 || cols < 1) {
alert('Please enter valid numbers for rows and columns');
return;
}
// Create table HTML
let tableHtml = '<table border="1" style="border-collapse: collapse; width: 100%;">';
// Add header row
tableHtml += '<thead><tr>';
for (let i = 0; i < cols; i++) {
tableHtml += '<th style="border: 1px solid #ccc; padding: 8px;">Header ' + (i+1) + '</th>';
}
tableHtml += '</tr></thead>';
// Add body rows
tableHtml += '<tbody>';
for (let i = 0; i < rows - 1; i++) {
tableHtml += '<tr>';
for (let j = 0; j < cols; j++) {
tableHtml += '<td style="border: 1px solid #ccc; padding: 8px;">Cell ' + (i+1) + '-' + (j+1) + '</td>';
}
tableHtml += '</tr>';
}
tableHtml += '</tbody></table><p></p>';
// Insert at cursor position
document.execCommand('insertHTML', false, tableHtml);
// Hide dialog
hideTableDialog();
}
/**
* Handle keyboard shortcuts
*/
function handleKeyboardShortcuts(e) {
// Command palette
if (e.ctrlKey && e.key === 'k') {
e.preventDefault();
toggleCommandPalette();
return;
}
// Command palette is open - handle Escape to close
if (wordlite.commandPaletteOpen) {
if (e.key === 'Escape') {
commandPalette.style.display = 'none';
wordlite.commandPaletteOpen = false;
return;
}
return; // Don't process other shortcuts when command palette is open
}
// Format shortcuts
if (e.ctrlKey && !e.shiftKey && !e.altKey) {
switch (e.key.toLowerCase()) {
case 'b':
e.preventDefault();
formatText('bold');
break;
case 'i':
e.preventDefault();
formatText('italic');
break;
case 'u':
e.preventDefault();
formatText('underline');
break;
case 's':
e.preventDefault();
saveDocument();
break;
case 'e':
e.preventDefault();
toggleZenMode();
break;
}
}
// Toggle dark theme
if (e.ctrlKey && e.shiftKey && e.key.toLowerCase() === 'd') {
e.preventDefault();
toggleTheme();
}
}
/**
* Toggle the command palette
*/
function toggleCommandPalette() {
wordlite.commandPaletteOpen = !wordlite.commandPaletteOpen;
if (wordlite.commandPaletteOpen) {
// Populate and show command palette
populateCommandList();
commandPalette.style.display = 'block';
commandInput.value = '';
commandInput.focus();
} else {
commandPalette.style.display = 'none';
}
}
/**
* Populate the command list
*/
function populateCommandList(filter = '') {
commandList.innerHTML = '';
const filteredCommands = wordlite.commands.filter(cmd =>
cmd.name.toLowerCase().includes(filter.toLowerCase())
);
filteredCommands.forEach(cmd => {
const item = document.createElement('div');
item.className = 'command-item';
item.innerHTML = `
<span>${cmd.name}</span>
<span class="shortcut">${cmd.shortcut}</span>
`;
item.addEventListener('click', () => {
cmd.action();
commandPalette.style.display = 'none';
wordlite.commandPaletteOpen = false;
});
commandList.appendChild(item);
});
}
/**
* Filter commands based on input
*/
function filterCommands() {
populateCommandList(commandInput.value);
}
/**
* Navigate command list with arrow keys
*/
function navigateCommandsList(e) {
if (e.key === 'ArrowDown' || e.key === 'ArrowUp') {
e.preventDefault();
const items = commandList.querySelectorAll('.command-item');
if (items.length === 0) return;
// Find currently focused item
const focusedItem = commandList.querySelector('.command-item:focus');
let index = -1;
if (focusedItem) {
// Get index of currently focused item
Array.from(items).forEach((item, i) => {
if (item === focusedItem) index = i;
});
}
// Calculate new index
if (e.key === 'ArrowDown') {
index = (index + 1) % items.length;
} else {
index = (index - 1 + items.length) % items.length;
}
// Focus the new item
items[index].focus();
} else if (e.key === 'Enter') {
e.preventDefault();
// Execute focused command
const focusedItem = commandList.querySelector('.command-item:focus');
if (focusedItem) {
focusedItem.click();
} else {
// Execute first command if nothing is focused
const firstItem = commandList.querySelector('.command-item');
if (firstItem) firstItem.click();
}
}
}
/**
* Toggle Zen Mode
*/
function toggleZenMode() {
wordlite.isZenMode = !wordlite.isZenMode;
document.querySelector('.app').classList.toggle('zen-mode', wordlite.isZenMode);
// If entering zen mode, focus editor
if (wordlite.isZenMode) {
editor.focus();
}
}
/**
* Toggle between light and dark theme
*/
function toggleTheme() {
wordlite.isThemeDark = !wordlite.isThemeDark;
document.documentElement.setAttribute('data-theme', wordlite.isThemeDark ? 'dark' : 'light');
localStorage.setItem('wordlite-theme', wordlite.isThemeDark ? 'dark' : 'light');
}
/**
* Apply saved theme preference
*/
function applyThemePreference() {
const savedTheme = localStorage.getItem('wordlite-theme');
if (savedTheme) {
wordlite.isThemeDark = savedTheme === 'dark';
document.documentElement.setAttribute('data-theme', savedTheme);
} else {
// Check for system preference
if (window.matchMedia && window.matchMedia('(prefers-color-scheme: dark)').matches) {
wordlite.isThemeDark = true;
document.documentElement.setAttribute('data-theme', 'dark');
}
}
}
/**
* Handle text selection and show/position the formatting toolbar
*/
function handleTextSelection() {
const selection = window.getSelection();
if (selection.rangeCount === 0) return;
const range = selection.getRangeAt(0);
// Only show the toolbar if text is selected within the editor
if (selection.toString().trim() === '' || !editor.contains(range.commonAncestorContainer)) {
formatToolbar.style.display = 'none';
return;
}
// Get position for the toolbar
const rect = range.getBoundingClientRect();
const editorRect = editor.getBoundingClientRect();
// Position toolbar above the selection
formatToolbar.style.top = `${rect.top - formatToolbar.offsetHeight - 10 + window.scrollY}px`;
formatToolbar.style.left = `${(rect.left + rect.right) / 2 - formatToolbar.offsetWidth / 2 + window.scrollX}px`;
formatToolbar.style.display = 'block';
// Update active states for formatting buttons
updateFormatButtonStates();
}
/**
* Update the active states of formatting buttons based on current selection
*/
function updateFormatButtonStates() {
const buttons = formatToolbar.querySelectorAll('button');
buttons.forEach(button => {
const format = button.getAttribute('data-format');
button.classList.toggle('active', document.queryCommandState(format));
});
}
/**
* Apply formatting to selected text
*/
function formatText(format) {
// Save selection
const selection = window.getSelection();
const range = selection.getRangeAt(0);
// Focus the editor
editor.focus();
// Apply formatting based on command
switch (format) {
case 'bold':
document.execCommand('bold', false, null);
break;
case 'italic':
document.execCommand('italic', false, null);
break;
case 'underline':
document.execCommand('underline', false, null);
break;
case 'h1':
document.execCommand('formatBlock', false, '<h1>');
break;
case 'h2':
document.execCommand('formatBlock', false, '<h2>');
break;
case 'quote':
document.execCommand('formatBlock', false, '<blockquote>');
break;
case 'code':
// Check if we're in a pre block already
const parentPre = getClosestElement(range.commonAncestorContainer, 'PRE');
if (parentPre) {
// Remove pre block
const textContent = parentPre.textContent;
const textNode = document.createTextNode(textContent);
parentPre.parentNode.replaceChild(textNode, parentPre);
} else {
// Check if we're wrapping inline or block
if (selection.toString().includes('\n')) {
// Block code
const pre = document.createElement('pre');
const code = document.createElement('code');
code.textContent = selection.toString();
pre.appendChild(code);
// Replace selection with code block
range.deleteContents();
range.insertNode(pre);
} else {
// Inline code
const code = document.createElement('code');
code.textContent = selection.toString();
// Replace selection with code element
range.deleteContents();
range.insertNode(code);
}
}
break;
}
// Update format button states
updateFormatButtonStates();
// Update word count
updateWordCount();
// Schedule autosave
scheduleAutoSave();
}
/**
* Get closest parent element matching the tag name
*/
function getClosestElement(node, tagName) {
while (node) {
if (node.nodeType === 1 && node.tagName === tagName) {
return node;
}
node = node.parentNode;
}
return null;
}
/**
* Handle editor input event
*/
function handleEditorInput() {
updateWordCount();
scheduleAutoSave();
}
/**
* Update the word count in the status bar
*/
function updateWordCount() {
const text = editor.innerText || '';
const count = text.trim() ? text.trim().split(/\s+/).length : 0;
wordCount.textContent = `Words: ${count}`;
}
/**
* Handle document title change
*/
function handleTitleChange() {
wordlite.currentDocument.title = documentTitle.value || 'Untitled Document';
scheduleAutoSave();
}
/**
* Schedule auto-save with debounce
*/
function scheduleAutoSave() {
// Clear any existing timeout
if (wordlite.saveTimeout) {
clearTimeout(wordlite.saveTimeout);
}
// Show saving indicator
saveStatus.textContent = 'Saving...';
saveStatus.classList.add('saving');
// Set new timeout
wordlite.saveTimeout = setTimeout(() => {
saveDocument();
}, 5000); // 5 seconds delay
}
/**
* Start auto-save interval
*/
function startAutoSave() {
// Initial save
saveDocument();
// Set up interval for backup saves (every 30 seconds)
setInterval(() => {
if (wordlite.saveTimeout) {
// If there's a pending save, do it now
clearTimeout(wordlite.saveTimeout);
wordlite.saveTimeout = null;
saveDocument();
}
}, 30000);
}
/**
* Save the current document
*/
function saveDocument() {
// Get current content from editor
wordlite.currentDocument.content = editor.innerHTML;
wordlite.currentDocument.lastSaved = new Date().toISOString();
// Find if this document already exists in our list
const index = wordlite.documents.findIndex(doc => doc.id === wordlite.currentDocument.id);
if (index !== -1) {
// Update existing document
wordlite.documents[index] = {...wordlite.currentDocument};
} else {
// Add new document
wordlite.documents.push({...wordlite.currentDocument});
}
// Save to localStorage
saveDocumentsToStorage();
// Update UI
populateDocumentList();
updateSaveStatus();
}
/**
* Update save status indicator
*/
function updateSaveStatus() {
saveStatus.textContent = 'Saved';
saveStatus.classList.remove('saving');
if (wordlite.currentDocument.lastSaved) {
const date = new Date(wordlite.currentDocument.lastSaved);
const timeStr = date.toLocaleTimeString([], { hour: '2-digit', minute: '2-digit' });
saveStatus.textContent = `Saved at ${timeStr}`;
}
}
/**
* Create a new document
*/
function createNewDocument() {
// Save the current one first
saveDocument();
// Create new document
wordlite.currentDocument = {
id: Date.now().toString(),
title: 'Untitled Document',
content: '<h1>New Document</h1><p>Start writing here...</p>',
lastSaved: null
};
// Update UI
documentTitle.value = wordlite.currentDocument.title;
updateEditorContent();
updateWordCount();
// Focus editor
editor.focus();
}
/**
* Update editor with current document content
*/
function updateEditorContent() {
editor.innerHTML = wordlite.currentDocument.content;
documentTitle.value = wordlite.currentDocument.title;
}
/**
* Populate document list in sidebar
*/
function populateDocumentList() {
documentList.innerHTML = '';
// Sort documents by last modified date
const sortedDocs = [...wordlite.documents].sort((a, b) => {
return new Date(b.lastSaved) - new Date(a.lastSaved);
});
sortedDocs.forEach(doc => {
const item = document.createElement('div');
item.className = 'document-item';
if (doc.id === wordlite.currentDocument.id) {
item.classList.add('active');
}
// Create title element
const title = document.createElement('div');
title.className = 'document-title';
title.textContent = doc.title;
// Create date element if available
const date = document.createElement('div');
date.className = 'document-date';
if (doc.lastSaved) {
const lastSaved = new Date(doc.lastSaved);
date.textContent = lastSaved.toLocaleDateString();
}
// Add elements to item
item.appendChild(title);
item.appendChild(date);
// Add click event
item.addEventListener('click', () => loadDocument(doc.id));
// Add to list
documentList.appendChild(item);
});
}
/**
* Load a document by ID
*/
function loadDocument(id) {
// Save current first
saveDocument();
// Find document
const doc = wordlite.documents.find(d => d.id === id);
if (!doc) return;
// Set as current
wordlite.currentDocument = {...doc};
// Update UI
updateEditorContent();
updateWordCount();
populateDocumentList();
// Close sidebar on mobile
if (window.innerWidth <= 768) {
sidebar.classList.remove('open');
}
}
/**
* Save documents to localStorage
*/
function saveDocumentsToStorage() {
try {
localStorage.setItem('wordlite-documents', JSON.stringify(wordlite.documents));
} catch (error) {
console.error('Error saving to localStorage:', error);
// If localStorage fails, try using IndexedDB
saveToIndexedDB();
}
}
/**
* Load documents from localStorage
*/
function loadDocumentsFromStorage() {
try {
const storedDocs = localStorage.getItem('wordlite-documents');
if (storedDocs) {
wordlite.documents = JSON.parse(storedDocs);
// Set current document to most recently saved
if (wordlite.documents.length > 0) {
const mostRecent = [...wordlite.documents].sort((a, b) => {
return new Date(b.lastSaved) - new Date(a.lastSaved);
})[0];
wordlite.currentDocument = {...mostRecent};
}
}
} catch (error) {
console.error('Error loading from localStorage:', error);
// Try loading from IndexedDB
loadFromIndexedDB();
}
}
/**
* Save to IndexedDB (fallback for large documents)
*/
function saveToIndexedDB() {
// Basic IndexedDB implementation - expand as needed
const request = indexedDB.open('WordLiteDB', 1);
request.onupgradeneeded = (event) => {
const db = event.target.result;
if (!db.objectStoreNames.contains('documents')) {
db.createObjectStore('documents', { keyPath: 'id' });
}
};
request.onsuccess = (event) => {
const db = event.target.result;
const transaction = db.transaction(['documents'], 'readwrite');
const store = transaction.objectStore('documents');
// Save each document individually
wordlite.documents.forEach(doc => {
store.put(doc);
});
transaction.oncomplete = () => {
console.log('All documents saved to IndexedDB');
};
};
}
/**
* Load from IndexedDB
*/
function loadFromIndexedDB() {
const request = indexedDB.open('WordLiteDB', 1);
request.onsuccess = (event) => {
const db = event.target.result;
const transaction = db.transaction(['documents'], 'readonly');
const store = transaction.objectStore('documents');
const getAllRequest = store.getAll();
getAllRequest.onsuccess = () => {
if (getAllRequest.result.length > 0) {
wordlite.documents = getAllRequest.result;
// Set current document to most recently saved
const mostRecent = [...wordlite.documents].sort((a, b) => {
return new Date(b.lastSaved) - new Date(a.lastSaved);
})[0];
wordlite.currentDocument = {...mostRecent};
updateEditorContent();
updateWordCount();
populateDocumentList();
}
};
};
}
/**
* Export as PDF
* Note: Would typically use html2pdf.js library
*/
function exportAsPDF() {
alert('PDF export requires the html2pdf.js library. Please include it or download as WDOC instead.');
// Commented code for when html2pdf is available:
/*
if (typeof html2pdf === 'undefined') {
alert('PDF export requires the html2pdf.js library.');
return;
}
const content = document.createElement('div');
content.innerHTML = wordlite.currentDocument.content;
const options = {
margin: 10,
filename: `${wordlite.currentDocument.title}.pdf`,
image: { type: 'jpeg', quality: 0.98 },
html2canvas: { scale: 2 },
jsPDF: { unit: 'mm', format: 'a4', orientation: 'portrait' }
};
html2pdf().from(content).set(options).save();
*/
}
function exportAsDocx() {
// Access docx library from window.docx
const { Document, Paragraph, TextRun, Packer } = window.docx;
// Create new document
const doc = new Document();
// Simple conversion of HTML to paragraphs
// This is basic - more complex conversion would require parsing HTML
const content = editor.innerText;
const paragraphs = content.split('\n').filter(p => p.trim() !== '');
paragraphs.forEach(p => {
doc.addParagraph(new Paragraph({
children: [new TextRun(p)]
}));
});
// Generate and download
Packer.toBlob(doc).then(blob => {
saveAs(blob, `${wordlite.currentDocument.title}.docx`);
});
}
/**
* Export as Markdown
* Note: Would typically use Showdown.js library
*/
function exportAsMarkdown() {
alert('Markdown export requires the Showdown.js library. Please include it or download as WDOC instead.');
// Commented code for when Showdown is available:
/*
if (typeof showdown === 'undefined') {
alert('Markdown export requires the Showdown.js library.');
return;
}
const converter = new showdown.Converter();
const html = wordlite.currentDocument.content;
const markdown = converter.makeMarkdown(html);
downloadFile(`${wordlite.currentDocument.title}.md`, markdown);
*/
}
/**
* Export as WDOC (custom JSON format)
*/
function exportAsWDOC() {
const wdoc = JSON.stringify({
title: wordlite.currentDocument.title,
content: wordlite.currentDocument.content,
created: wordlite.currentDocument.id,
lastModified: new Date().toISOString(),
format: 'wdoc-1.0'
}, null, 2);
downloadFile(`${wordlite.currentDocument.title}.wdoc`, wdoc);
}
/**
* Helper to download a file
*/
function downloadFile(filename, text) {
const element = document.createElement('a');
element.setAttribute('href', 'data:text/plain;charset=utf-8,' + encodeURIComponent(text));
element.setAttribute('download', filename);
element.style.display = 'none';
document.body.appendChild(element);
element.click();
document.body.removeChild(element);
}