-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathformAutoSave.js
More file actions
821 lines (718 loc) · 35.5 KB
/
Copy pathformAutoSave.js
File metadata and controls
821 lines (718 loc) · 35.5 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
/**
* FormAutoSave - Automatic Form Data Persistence
*
* A JavaScript library for automatically saving and restoring form data
* using browser localStorage/sessionStorage.
*
* This script uses HTML5 Dialog with Bootstrap 3 styling (no jQuery dependency)
*
* Date: April 22, 2026
*
* @author David Herman
* @website https://github.com/daveherman71/FormAutoSave
* @version 1.0.0
* @license MIT
*/
class FormAutoSave {
VERSION = '1.0.0';
// Private fields with # prefix
#forms;
#debounceTimers;
#saveIndicators;
#storage;
constructor(options = {}) {
// Set default options
this.formSelector = options.hasOwnProperty('formSelector') ? options.formSelector : '.form-autosave';
this.statusSelector = options.hasOwnProperty('statusSelector') ? options.statusSelector : null;
this.storagePrefix = options.hasOwnProperty('storagePrefix') ? options.storagePrefix : 'form_autosave_';
this.excludeAttribute = options.hasOwnProperty('excludeAttribute') ? options.excludeAttribute : 'data-no-autosave';
this.debounceDelay = options.hasOwnProperty('debounceDelay') ? options.debounceDelay : 500;
this.maxAge = options.hasOwnProperty('maxAge') ? options.maxAge : 7 * 24 * 60 * 60 * 1000; // 7 days default
this.useSessionStorage = options.hasOwnProperty('useSessionStorage') ? options.useSessionStorage === true : false;
this.useSilentMode = options.hasOwnProperty('useSilentMode') ? options.useSilentMode === true : false;
this.showNotifications = options.hasOwnProperty('showNotifications') ? options.showNotifications === true : true;
this.onSave = options.hasOwnProperty('onSAve') ? options.onSave : null;
this.onRestore = options.hasOwnProperty('onRestore') ? options.onRestore : null;
this.onClear = options.hasOwnProperty('onClear') ? options.onClear : null;
// Define internal state
this.#forms = new Map();
this.#debounceTimers = new Map();
this.#saveIndicators = new Map();
this.#storage = this.useSessionStorage ? sessionStorage : localStorage;
// Initialize the module
this.#init();
}
#init() {
// Wait for DOM to be ready before setting up forms
if (document.readyState === 'loading') {
document.addEventListener('DOMContentLoaded', () => this.#setupForms());
} else {
this.#setupForms();
}
// Clean up expired data on init
this.#cleanupExpiredData();
// Inject CSS for dialogs
this.#injectStyles();
}
#setupForms() {
const forms = document.querySelectorAll(`form${this.formSelector}`);
forms.forEach(form => {
// Skip forms that don't have an identifier
const formId = this.getFormIdentifier(form);
if (!formId) return;
// Store the form reference
this.#forms.set(formId, form);
this.#checkForSavedData(form, formId);
this.#attachEventListeners(form, formId);
if (this.showNotifications) {
this.#addSaveIndicator(form, formId);
}
});
}
#getEditableFields(form) {
const fields = form.querySelectorAll('input, textarea, select');
return Array.from(fields).filter(field => {
// Exclude fields based on type and custom attribute
if (field.hasAttribute(this.excludeAttribute)) return false;
// Exclude non-editable types
const excludedTypes = ['submit', 'button', 'reset', 'file'];
if (field.type && excludedTypes.includes(field.type)) return false;
// Exclude password fields for security reasons
if (field.type === 'password') return false;
return true;
});
}
#attachEventListeners(form, formId) {
// Add input/change listeners to all editable fields
const fields = this.#getEditableFields(form);
fields.forEach(field => {
['input', 'change'].forEach(eventType => {
field.addEventListener(eventType, () => {
this.#debouncedSave(formId);
this.#updateStatus(formId, 'saving');
});
});
});
// Add submit handler to clear saved data on successful submission
form.addEventListener('submit', (e) => {
setTimeout(() => {
this.#clearFormData(formId);
}, 100);
});
// Add reset button handler
form.addEventListener('reset', () => {
this.#clearFormData(formId);
});
}
#checkForSavedData(form, formId) {
// Check if there's saved data for this form
const storageKey = this.storagePrefix + formId;
const saved = this.#storage.getItem(storageKey);
if (saved) {
try {
// Get the stored data to check the timestamp and metadata
const { timestamp, metadata } = JSON.parse(saved);
const saveDate = new Date(timestamp);
// Check if expired
if (new Date() - saveDate > this.maxAge) {
this.#clearFormData(formId);
return;
}
// If silent mode is enabled, restore immediately without prompting
if (this.useSilentMode) {
this.#loadFormData(form, formId);
} else {
this.#showRestorePrompt(form, formId, saveDate, metadata);
}
} catch (e) {
console.error('Failed to check saved data:', e);
this.#clearFormData(formId);
}
}
}
#cleanupExpiredData() {
const now = new Date();
const keys = Object.keys(this.#storage);
keys.forEach(key => {
if (!key.startsWith(this.storagePrefix)) return;
try {
// Get the stored data to check the timestamp
const data = this.#storage.getItem(key);
const { timestamp } = JSON.parse(data);
const saveDate = new Date(timestamp);
// If the data is older than maxAge, remove it
if (now - saveDate > this.maxAge) {
this.#storage.removeItem(key);
console.log(`Cleaned up expired data: ${key}`);
}
} catch (e) {
// Invalid data, remove it
this.#storage.removeItem(key);
}
});
}
#getFormData(form) {
const fields = this.#getEditableFields(form);
const data = {};
const metadata = {
fieldTypes: {},
fieldCount: 0
};
fields.forEach(field => {
// Use name or id as the key, but skip if neither exists
const name = field.name || field.id;
if (!name) return;
// Track field types in metadata
metadata.fieldCount++;
metadata.fieldTypes[name] = field.type;
// Get the value based on field type
if (field.type === 'checkbox') {
data[name] = field.checked;
} else if (field.type === 'radio') {
if (field.checked) {
data[name] = field.value;
}
} else if (field.tagName === 'SELECT' && field.multiple) {
data[name] = Array.from(field.selectedOptions).map(opt => opt.value);
} else {
data[name] = field.value;
}
});
return { data, metadata };
}
#clearFormData(formId) {
// Remove saved data from storage
const storageKey = this.storagePrefix + formId;
this.#storage.removeItem(storageKey);
// Callback if it exists
if (this.onClear) {
this.onClear(formId);
}
}
#debouncedSave(formId) {
// Clear existing timer if it exists
if (this.#debounceTimers.has(formId)) {
clearTimeout(this.#debounceTimers.get(formId));
}
// Set new timer
const timer = setTimeout(() => {
this.#saveFormData(formId);
this.#debounceTimers.delete(formId);
}, this.debounceDelay);
// Store timer reference
this.#debounceTimers.set(formId, timer);
}
async #saveFormData(formId) {
// Get the form reference
const form = this.#forms.get(formId);
if (!form) return;
// Get form data and metadata
const { data, metadata } = this.#getFormData(form);
// Create a structured object to store, including metadata and timestamp
const storageKey = this.storagePrefix + formId;
const saveData = {
data: data,
metadata: metadata,
timestamp: new Date().toISOString(),
url: window.location.href,
version: this.VERSION
};
try {
// Save data as JSON string in storage
const dataToStore = JSON.stringify(saveData);
this.#storage.setItem(storageKey, dataToStore);
this.#updateStatus(formId, 'saved');
// Callback if it exists
if (this.onSave) {
this.onSave(formId, data);
}
} catch (e) {
console.error('Failed to save form data:', e);
this.#updateStatus(formId, 'error');
}
}
#loadFormData(form, formId) {
// Get the saved data from storage
const storageKey = this.storagePrefix + formId;
const saved = this.#storage.getItem(storageKey);
if (saved) {
try {
// Get the stored data to check the data, timestamp and metadata
const { data, timestamp, metadata } = JSON.parse(saved);
const saveDate = new Date(timestamp);
// Check if expired
if (new Date() - saveDate > this.maxAge) {
this.#clearFormData(formId);
return null;
}
// Populate form fields with the saved data
const fields = this.#getEditableFields(form);
fields.forEach(field => {
// Use name or id as the key, but skip if neither exists
const name = field.name || field.id;
if (!name || !(name in data)) return;
// Set the value based on field type
if (field.type === 'checkbox') {
field.checked = data[name];
} else if (field.type === 'radio') {
if (field.value === data[name]) {
field.checked = true;
}
} else if (field.tagName === 'SELECT' && field.multiple) {
Array.from(field.options).forEach(opt => {
opt.selected = data[name].includes(opt.value);
});
} else {
field.value = data[name];
}
// Trigger change event for any dependent fields
field.dispatchEvent(new Event('change', { bubbles: true }));
});
// Callback if it exists
if (this.onRestore) {
this.onRestore(formId, data);
}
return { timestamp, metadata };
} catch (e) {
console.error('Failed to load form data:', e);
return null;
}
}
}
#injectStyles() {
// Avoid injecting styles multiple times
if (document.getElementById('autosave-dialog-styles')) return;
const styles = document.createElement('style');
styles.id = 'autosave-dialog-styles';
styles.textContent = `
.autosave-dialog {
--alert-compare-bg: #fff3cd;
--alert-compare-text: #856404;
--alert-restore-bg: #d9edf7;
--alert-restore-text: #31708f;
--btn-compare-bg: #fff;
--btn-compare-border: #ccc;
--btn-compare-text: #333;
--btn-compare-hover-bg: #e6e6e6;
--btn-compare-hover-border: #adadad;
--btn-compare-hover-text: #333;
--btn-discard-bg: #d9534f;
--btn-discard-border: #d43f3a;
--btn-discard-text: #fff;
--btn-discard-hover-bg: #c9302c;
--btn-discard-hover-border: #ac2925;
--btn-discard-hover-text: #fff;
--btn-restore-bg: #5cb85c;
--btn-restore-border: #4cae4c;
--btn-restore-text: #fff;
--btn-restore-hover-bg: #4cae4c;
--btn-restore-hover-border: #398439;
--btn-restore-hover-text: #fff;
--icon-calendar: #337ab7;
--text-calendar: #777;
--icon-fields: #5cb85c;
--text-fields: #777;
--icon-checked: #5cb85c;
--icon-unchecked: #777;
--btn-border-radius: 0;
--dialog-border: 1px solid #ddd;
--dialog-border-radius: 0;
--dialog-header: #333;
--dialog-header-bg: #f5f5f5;
--dialog-body-bg: #fff;
--dialog-footer-bg: #fff;
--text-table: #333;
--text-empty: #777;
}
.autosave-indicator {
--bg-default: #777;
--text-default: #333;
--bg-error: #d9534f;
--bg-saved: #5cb85c;
--bg-saving: #f0ad4e;
--text-error: #fff;
--text-saved: #fff;
--text-saving: #fff;
}
.autosave-dialog { border: none; font-size: 14px; padding: 0; width: 600px; border-radius: var(--dialog-border-radius); }
.autosave-dialog * { margin: 0; padding: 0; }
.autosave-dialog svg { width: 1.25em; height: 1em; vertical-align: -0.15em; fill: currentColor; text-align: center; }
.autosave-dialog::backdrop { background: rgba(0, 0, 0, .5); }
.autosave-dialog__header {color: var(--dialog-header); background-color: var(--dialog-header-bg); border-bottom: var(--dialog-border); padding: .75em 1em;}
.autosave-dialog__body { background-color: var(--dialog-body-bg); padding: 1em; }
.autosave-dialog__footer { background-color: var(--dialog-footer-bg); border-top: var(--dialog-border); padding: 1em; }
.autosave-dialog__close { background: transparent; border: none; cursor: pointer; float: right; font-size: 1.5em; line-height: 1; margin-top: -.2em; opacity: .25; padding: 0; text-shadow: 0 1px 0 #fff; }
.autosave-dialog__close:hover { opacity: .5; }
.autosave-dialog__alert { margin-bottom: 1em; padding: .75em 1em; }
.autosave-dialog__btn { border: 1px solid transparent; cursor: pointer; display: inline-block; padding: .5em 1em; border-radius: 0; outline: none !important; text-align: center; vertical-align: middle; white-space: nowrap; -webkit-user-select: none; -moz-user-select: none; -ms-user-select: none; user-select: none; -ms-touch-action: manipulation; touch-action: manipulation; }
.autosave-dialog__btn:hover { text-decoration: none; }
.autosave-dialog__table { background-color: transparent; border-collapse:collapse; width: 100%; max-width: 100%; }
.autosave-dialog__table > thead:first-child > tr:first-child > th,
.autosave-dialog__table > thead:first-child > tr:first-child > td { border-top: 0; }
.autosave-dialog__table > thead > tr > td.active,
.autosave-dialog__table > tbody > tr > td.active,
.autosave-dialog__table > tfoot > tr > td.active,
.autosave-dialog__table > thead > tr > th.active,
.autosave-dialog__table > tbody > tr > th.active,
.autosave-dialog__table > tfoot > tr > th.active,
.autosave-dialog__table > thead > tr.active > td,
.autosave-dialog__table > tbody > tr.active > td,
.autosave-dialog__table > tfoot > tr.active > td,
.autosave-dialog__table > thead > tr.active > th,
.autosave-dialog__table > tbody > tr.active > th,
.autosave-dialog__table tfoot > tr.active > th { color: var(--text-table); background-color: var(--dialog-header-bg); }
.autosave-dialog__table > thead > tr > th,
.autosave-dialog__table > tbody > tr > th,
.autosave-dialog__table > tfoot > tr > th,
.autosave-dialog__table > thead > tr > td,
.autosave-dialog__table > tbody > tr > td,
.autosave-dialog__table > tfoot > tr > td { border-top: var(--dialog-border); .25em; color: var(--text-table); padding: .25em; vertical-align: top; }
.autosave-dialog__table > thead > tr > td > em,
.autosave-dialog__table > tbody > tr > td > em,
.autosave-dialog__table > tfoot > tr > td > em { color: var(--text-empty); opacity: .5; }
.autosave-dialog--row { display: flex; gap: 1em; }
.autosave-dialog--col { flex: 1; }
.autosave-dialog--panel { border: var(--dialog-border); padding: 1em; }
.autosave-dialog--alert-compare { background-color: var(--alert-compare-bg); color: var(--alert-compare-text); }
.autosave-dialog--alert-restore { background-color: var(--alert-restore-bg); color: var(--alert-restore-text); }
.autosave-dialog--btn-compare { color: var(--btn-compare-text); background-color: var(--btn-compare-bg); border-color: var(--btn-compare-border); border-radius: var(--btn-border-radius); }
.autosave-dialog--btn-compare:hover { color: var(--btn-compare-hover-text); background-color: var(--btn-compare-hover-bg); border-color: var(--btn-compare-hover-border); }
.autosave-dialog--btn-discard { color: var(--btn-discard-text); background-color: var(--btn-discard-bg); border-color: var(--btn-discard-border); border-radius: var(--btn-border-radius); }
.autosave-dialog--btn-discard:hover { color: var(--btn-discard-hover-text); background-color: var(--btn-discard-hover-bg); border-color: var(--btn-discard-hover-border); }
.autosave-dialog--btn-restore { color: var(--btn-restore-text); background-color: var(--btn-restore-bg); border-color: var(--btn-restore-border); border-radius: var(--btn-border-radius); }
.autosave-dialog--btn-restore:hover { color: var(--btn-restore-hover-text); background-color: var(--btn-restore-hover-bg); border-color: var(--btn-restore-hover-border); }
.autosave-dialog--icon-calendar { color: var(--icon-calendar); }
.autosave-dialog--text-calendar { color: var(--text-calendar); }
.autosave-dialog--icon-fields { color: var(--icon-fields); }
.autosave-dialog--text-fields { color: var(--text-fields); }
.autosave-dialog--icon-checked { color: var(--icon-checked); }
.autosave-dialog--icon-unchecked { color: var(--icon-unchecked); }
.autosave-dialog--small { font-size: .85em; }
.autosave-dialog--text-center { text-align: center; }
.autosave-dialog--text-right { text-align: right; }
.autosave-indicator { position: absolute; top: -30px; right: 0; opacity: 0; transition: opacity 0.3s; z-index: 10; }
.autosave-indicator__label { background-color: var(--bg-default); color: var(--text-default); font-size: 11px; font-weight: 500; padding: 6px 8px; }
.autosave-indicator__selector svg { width: 1.25em; height: 1em; vertical-align: -0.15em; fill: currentColor; text-align: center; }
.autosave-indicator__status svg { width: 1.25em; height: 1em; vertical-align: -0.15em; fill: currentColor; text-align: center; }
.autosave-indicator--saving { background-color: var(--bg-saving); color: var(--text-saving); }
.autosave-indicator--saved { background-color: var(--bg-saved); color: var(--text-saved); }
.autosave-indicator--error { background-color: var(--bg-error); color: var(--text-error); }
.autosave-dialog--icon-spin svg {
-webkit-animation: autosave-dialog--icon-spin 2s linear infinite;
animation: autosave-dialog--icon-spin 2s linear infinite;
}
@-webkit-keyframes autosave-dialog--icon-spin {
0% { -webkit-transform:rotate(0deg); transform:rotate(0deg); }
to { -webkit-transform:rotate(1turn); transform:rotate(1turn) }
}
@keyframes autosave-dialog--icon-spin {
0% { -webkit-transform:rotate(0deg); transform:rotate(0deg) }
to { -webkit-transform:rotate(1turn); transform:rotate(1turn) }
}
`;
document.head.appendChild(styles);
}
#addSaveIndicator(form, formId) {
// If a global status element is defined, we won't add individual indicators
const statusElement = document.querySelector(this.statusSelector);
if (statusElement) {
statusElement.classList.add('autosave-indicator__selector');
statusElement.dataset.originalHtml = statusElement.innerHTML;
return;
}
// Create a small indicator element for this form
const indicator = document.createElement('div');
indicator.className = 'autosave-indicator';
indicator.innerHTML = `
<span class="autosave-indicator__label">
<span class="autosave-indicator__status"></span>
</span>
`;
form.style.position = 'relative';
form.appendChild(indicator);
this.#saveIndicators.set(formId, indicator);
}
// Font Awesome Free v5.15.4 by @fontawesome - https://fontawesome.com License - https://fontawesome.com/license/free Copyright 2026 Fonticons, Inc.
#fontAwesomeIcon(iconClass) {
const icons = {
'fa-calendar-alt': '<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 448 512"><path d="M0 464c0 26.5 21.5 48 48 48h352c26.5 0 48-21.5 48-48V192H0v272zm320-196c0-6.6 5.4-12 12-12h40c6.6 0 12 5.4 12 12v40c0 6.6-5.4 12-12 12h-40c-6.6 0-12-5.4-12-12v-40zm0 128c0-6.6 5.4-12 12-12h40c6.6 0 12 5.4 12 12v40c0 6.6-5.4 12-12 12h-40c-6.6 0-12-5.4-12-12v-40zM192 268c0-6.6 5.4-12 12-12h40c6.6 0 12 5.4 12 12v40c0 6.6-5.4 12-12 12h-40c-6.6 0-12-5.4-12-12v-40zm0 128c0-6.6 5.4-12 12-12h40c6.6 0 12 5.4 12 12v40c0 6.6-5.4 12-12 12h-40c-6.6 0-12-5.4-12-12v-40zM64 268c0-6.6 5.4-12 12-12h40c6.6 0 12 5.4 12 12v40c0 6.6-5.4 12-12 12H76c-6.6 0-12-5.4-12-12v-40zm0 128c0-6.6 5.4-12 12-12h40c6.6 0 12 5.4 12 12v40c0 6.6-5.4 12-12 12H76c-6.6 0-12-5.4-12-12v-40zM400 64h-48V16c0-8.8-7.2-16-16-16h-32c-8.8 0-16 7.2-16 16v48H160V16c0-8.8-7.2-16-16-16h-32c-8.8 0-16 7.2-16 16v48H48C21.5 64 0 85.5 0 112v48h448v-48c0-26.5-21.5-48-48-48z"/></svg>',
'fa-check-circle': '<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 512 512"><path d="M504 256c0 136.967-111.033 248-248 248S8 392.967 8 256 119.033 8 256 8s248 111.033 248 248zM227.314 387.314l184-184c6.248-6.248 6.248-16.379 0-22.627l-22.627-22.627c-6.248-6.249-16.379-6.249-22.628 0L216 308.118l-70.059-70.059c-6.248-6.248-16.379-6.248-22.628 0l-22.627 22.627c-6.248 6.248-6.248 16.379 0 22.627l104 104c6.249 6.249 16.379 6.249 22.628.001z"/></svg>',
'fa-check-square': '<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 448 512"><path d="M400 480H48c-26.51 0-48-21.49-48-48V80c0-26.51 21.49-48 48-48h352c26.51 0 48 21.49 48 48v352c0 26.51-21.49 48-48 48zm-204.686-98.059l184-184c6.248-6.248 6.248-16.379 0-22.627l-22.627-22.627c-6.248-6.248-16.379-6.249-22.628 0L184 302.745l-70.059-70.059c-6.248-6.248-16.379-6.248-22.628 0l-22.627 22.627c-6.248 6.248-6.248 16.379 0 22.627l104 104c6.249 6.25 16.379 6.25 22.628.001z"/></svg>',
'fa-clock': '<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 512 512"><path d="M256,8C119,8,8,119,8,256S119,504,256,504,504,393,504,256,393,8,256,8Zm92.49,313h0l-20,25a16,16,0,0,1-22.49,2.5h0l-67-49.72a40,40,0,0,1-15-31.23V112a16,16,0,0,1,16-16h32a16,16,0,0,1,16,16V256l58,42.5A16,16,0,0,1,348.49,321Z"/></svg>',
'fa-code-branch': '<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 384 512"><path d="M384 144c0-44.2-35.8-80-80-80s-80 35.8-80 80c0 36.4 24.3 67.1 57.5 76.8-.6 16.1-4.2 28.5-11 36.9-15.4 19.2-49.3 22.4-85.2 25.7-28.2 2.6-57.4 5.4-81.3 16.9v-144c32.5-10.2 56-40.5 56-76.3 0-44.2-35.8-80-80-80S0 35.8 0 80c0 35.8 23.5 66.1 56 76.3v199.3C23.5 365.9 0 396.2 0 432c0 44.2 35.8 80 80 80s80-35.8 80-80c0-34-21.2-63.1-51.2-74.6 3.1-5.2 7.8-9.8 14.9-13.4 16.2-8.2 40.4-10.4 66.1-12.8 42.2-3.9 90-8.4 118.2-43.4 14-17.4 21.1-39.8 21.6-67.9 31.6-10.8 54.4-40.7 54.4-75.9zM80 64c8.8 0 16 7.2 16 16s-7.2 16-16 16-16-7.2-16-16 7.2-16 16-16zm0 384c-8.8 0-16-7.2-16-16s7.2-16 16-16 16 7.2 16 16-7.2 16-16 16zm224-320c8.8 0 16 7.2 16 16s-7.2 16-16 16-16-7.2-16-16 7.2-16 16-16z"/></svg>',
'fa-edit': '<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 576 512"><path d="M402.6 83.2l90.2 90.2c3.8 3.8 3.8 10 0 13.8L274.4 405.6l-92.8 10.3c-12.4 1.4-22.9-9.1-21.5-21.5l10.3-92.8L388.8 83.2c3.8-3.8 10-3.8 13.8 0zm162-22.9l-48.8-48.8c-15.2-15.2-39.9-15.2-55.2 0l-35.4 35.4c-3.8 3.8-3.8 10 0 13.8l90.2 90.2c3.8 3.8 10 3.8 13.8 0l35.4-35.4c15.2-15.3 15.2-40 0-55.2zM384 346.2V448H64V128h229.8c3.2 0 6.2-1.3 8.5-3.5l40-40c7.6-7.6 2.2-20.5-8.5-20.5H48C21.5 64 0 85.5 0 112v352c0 26.5 21.5 48 48 48h352c26.5 0 48-21.5 48-48V306.2c0-10.7-12.9-16-20.5-8.5l-40 40c-2.2 2.3-3.5 5.3-3.5 8.5z"/></svg>',
'fa-exclamation-circle': '<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 512 512"><path d="M504 256c0 136.997-111.043 248-248 248S8 392.997 8 256C8 119.083 119.043 8 256 8s248 111.083 248 248zm-248 50c-25.405 0-46 20.595-46 46s20.595 46 46 46 46-20.595 46-46-20.595-46-46-46zm-43.673-165.346l7.418 136c.347 6.364 5.609 11.346 11.982 11.346h48.546c6.373 0 11.635-4.982 11.982-11.346l7.418-136c.375-6.874-5.098-12.654-11.982-12.654h-63.383c-6.884 0-12.356 5.78-11.981 12.654z"/></svg>',
'fa-exclamation-triangle': '<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 576 512"><path d="M569.517 440.013C587.975 472.007 564.806 512 527.94 512H48.054c-36.937 0-59.999-40.055-41.577-71.987L246.423 23.985c18.467-32.009 64.72-31.951 83.154 0l239.94 416.028zM288 354c-25.405 0-46 20.595-46 46s20.595 46 46 46 46-20.595 46-46-20.595-46-46-46zm-43.673-165.346l7.418 136c.347 6.364 5.609 11.346 11.982 11.346h48.546c6.373 0 11.635-4.982 11.982-11.346l7.418-136c.375-6.874-5.098-12.654-11.982-12.654h-63.383c-6.884 0-12.356 5.78-11.981 12.654z"/></svg>',
'fa-info-circle': '<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 512 512"><path d="M256 8C119.043 8 8 119.083 8 256c0 136.997 111.043 248 248 248s248-111.003 248-248C504 119.083 392.957 8 256 8zm0 110c23.196 0 42 18.804 42 42s-18.804 42-42 42-42-18.804-42-42 18.804-42 42-42zm56 254c0 6.627-5.373 12-12 12h-88c-6.627 0-12-5.373-12-12v-24c0-6.627 5.373-12 12-12h12v-64h-12c-6.627 0-12-5.373-12-12v-24c0-6.627 5.373-12 12-12h64c6.627 0 12 5.373 12 12v100h12c6.627 0 12 5.373 12 12v24z"/></svg>',
'fa-redo-alt': '<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 512 512"><path d="M256.455 8c66.269.119 126.437 26.233 170.859 68.685l35.715-35.715C478.149 25.851 504 36.559 504 57.941V192c0 13.255-10.745 24-24 24H345.941c-21.382 0-32.09-25.851-16.971-40.971l41.75-41.75c-30.864-28.899-70.801-44.907-113.23-45.273-92.398-.798-170.283 73.977-169.484 169.442C88.764 348.009 162.184 424 256 424c41.127 0 79.997-14.678 110.629-41.556 4.743-4.161 11.906-3.908 16.368.553l39.662 39.662c4.872 4.872 4.631 12.815-.482 17.433C378.202 479.813 319.926 504 256 504 119.034 504 8.001 392.967 8 256.002 7.999 119.193 119.646 7.755 256.455 8z"/></svg>',
'fa-square': '<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 448 512"><path d="M400 32H48C21.5 32 0 53.5 0 80v352c0 26.5 21.5 48 48 48h352c26.5 0 48-21.5 48-48V80c0-26.5-21.5-48-48-48zm-6 400H54c-3.3 0-6-2.7-6-6V86c0-3.3 2.7-6 6-6h340c3.3 0 6 2.7 6 6v340c0 3.3-2.7 6-6 6z"/></svg>',
'fa-sync-alt': '<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 512 512"><path d="M370.72 133.28C339.458 104.008 298.888 87.962 255.848 88c-77.458.068-144.328 53.178-162.791 126.85-1.344 5.363-6.122 9.15-11.651 9.15H24.103c-7.498 0-13.194-6.807-11.807-14.176C33.933 94.924 134.813 8 256 8c66.448 0 126.791 26.136 171.315 68.685L463.03 40.97C478.149 25.851 504 36.559 504 57.941V192c0 13.255-10.745 24-24 24H345.941c-21.382 0-32.09-25.851-16.971-40.971l41.75-41.749zM32 296h134.059c21.382 0 32.09 25.851 16.971 40.971l-41.75 41.75c31.262 29.273 71.835 45.319 114.876 45.28 77.418-.07 144.315-53.144 162.787-126.849 1.344-5.363 6.122-9.15 11.651-9.15h57.304c7.498 0 13.194 6.807 11.807 14.176C478.067 417.076 377.187 504 256 504c-66.448 0-126.791-26.136-171.315-68.685L48.97 471.03C33.851 486.149 8 475.441 8 454.059V320c0-13.255 10.745-24 24-24z"/></svg>',
'fa-times': '<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 352 512"><path d="M242.72 256l100.07-100.07c12.28-12.28 12.28-32.19 0-44.48l-22.24-22.24c-12.28-12.28-32.19-12.28-44.48 0L176 189.28 75.93 89.21c-12.28-12.28-32.19-12.28-44.48 0L9.21 111.45c-12.28 12.28-12.28 32.19 0 44.48L109.28 256 9.21 356.07c-12.28 12.28-12.28 32.19 0 44.48l22.24 22.24c12.28 12.28 32.2 12.28 44.48 0L176 322.72l100.07 100.07c12.28 12.28 32.2 12.28 44.48 0l22.24-22.24c12.28-12.28 12.28-32.19 0-44.48L242.72 256z"/></svg>',
'fa-trash-alt': '<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 448 512"><path d="M32 464a48 48 0 0 0 48 48h288a48 48 0 0 0 48-48V128H32zm272-256a16 16 0 0 1 32 0v224a16 16 0 0 1-32 0zm-96 0a16 16 0 0 1 32 0v224a16 16 0 0 1-32 0zm-96 0a16 16 0 0 1 32 0v224a16 16 0 0 1-32 0zM432 32H312l-9.4-18.7A24 24 0 0 0 281.1 0H166.8a23.72 23.72 0 0 0-21.4 13.3L136 32H16A16 16 0 0 0 0 48v32a16 16 0 0 0 16 16h416a16 16 0 0 0 16-16V48a16 16 0 0 0-16-16z"/></svg>'
}
return icons[iconClass];
}
#updateStatus(formId, status) {
// If notifications are disabled, do nothing
if (!this.showNotifications) return;
// Define status configurations
const statusConfig = {
saving: {
icon: 'fa-sync-alt',
text: 'Saving',
spin: true
},
saved: {
icon: 'fa-check-circle',
text: 'Saved'
},
error: {
icon: 'fa-exclamation-circle',
text: 'Error'
}
};
// If the status is not defined, do nothing
const config = statusConfig[status];
if (!config) return;
const spinClass = config.spin ? 'autosave-dialog--icon-spin' : '';
// If a global status element is defined, update it instead of individual indicators
const statusElement = document.querySelector(this.statusSelector);
if (statusElement !== null) {
statusElement.innerHTML = `<span class="${spinClass}">${this.#fontAwesomeIcon(config.icon)}</span> ${config.text}`;
if (status === 'saved' || status === 'error') {
setTimeout(() => {
statusElement.innerHTML = statusElement.dataset.originalHtml || '';
delete statusElement.dataset.originalHtml;
}, 2000);
}
return;
}
// Update the individual indicator for this form
const indicator = this.#saveIndicators.get(formId);
if (!indicator) return;
const indicatorLabelElement = indicator.querySelector('.autosave-indicator__label');
const indicatorStatusElement = indicator.querySelector('.autosave-indicator__status');
indicatorLabelElement.className = `autosave-indicator__label autosave-indicator--${status}`;
indicatorStatusElement.innerHTML = `<span class="${spinClass}">${this.#fontAwesomeIcon(config.icon)}</span> ${config.text}`;
indicator.style.opacity = '1';
// Fade out after a delay for saved and error statuses
if (status === 'saved' || status === 'error') {
setTimeout(() => {
indicator.style.opacity = '0';
}, 2000);
}
}
#showDialog(form, formId, title, body, buttons) {
const dialog = document.createElement('dialog');
dialog.className = 'autosave-dialog';
dialog.setAttribute('tabindex', '-1');
dialog.setAttribute('role', 'dialog');
dialog.innerHTML = `
<div class="autosave-dialog__header">
<button type="button" class="autosave-dialog__close" aria-hidden="true" aria-label="Close">×</button>
<h5 class="autosave-dialog__title">${title}</h5>
</div>
<div class="autosave-dialog__body">${body}</div>
<div class="autosave-dialog__footer">${buttons}</div>
`;
document.body.appendChild(dialog);
// Close handlers
const closeDialog = (dialog) => {
document.body.style.overflow = '';
dialog.close();
dialog.remove();
};
dialog.querySelector('.autosave-dialog__close').addEventListener('click', () => closeDialog(dialog));
dialog.addEventListener('click', (e) => {
const rect = dialog.getBoundingClientRect();
const clickedOutside =
e.clientX < rect.left ||
e.clientX > rect.right ||
e.clientY < rect.top ||
e.clientY > rect.bottom;
if (clickedOutside) closeDialog(dialog);
});
// Button handlers
dialog.querySelectorAll('button').forEach(button => {
if (button.matches('.autosave-dialog--btn-compare')) {
button.addEventListener('click', () => {
closeDialog(dialog);
this.#showDataComparison(form, formId);
});
} else if (button.matches('.autosave-dialog--btn-discard')) {
button.addEventListener('click', () => {
this.#clearFormData(formId);
closeDialog(dialog);
});
} else if (button.matches('.autosave-dialog--btn-restore')) {
button.addEventListener('click', () => {
this.#loadFormData(form, formId);
closeDialog(dialog);
});
}
});
// Prevent background scrolling when dialog is open
document.body.style.overflow = 'hidden';
// Show the dialog
dialog.showModal();
}
#showRestorePrompt(form, formId, date, metadata) {
const title = `${this.#fontAwesomeIcon('fa-clock')} Restore Form Data?`;
const body = `
<div class="autosave-dialog__alert autosave-dialog--alert-restore" role="alert">
${this.#fontAwesomeIcon('fa-info-circle')}
We found unsaved form data from a previous session.
</div>
<div class="autosave-dialog--row">
<div class="autosave-dialog--col">
<div class="autosave-dialog--panel autosave-dialog--text-center">
<div style="font-size: 3em; margin-bottom: 15px;" class="autosave-dialog--icon-calendar">${this.#fontAwesomeIcon('fa-calendar-alt')}</div>
<div class="autosave-dialog--small autosave-dialog--text-calendar">${date.toLocaleString()}</div>
</div>
</div>
<div class="autosave-dialog--col">
<div class="autosave-dialog--panel autosave-dialog--text-center">
<div style="font-size: 3em; margin-bottom: 15px;" class="autosave-dialog--icon-fields">${this.#fontAwesomeIcon('fa-edit')}</div>
<div class="autosave-dialog--small autosave-dialog--text-fields">${metadata.fieldCount || 'Unknown'} fields</div>
</div>
</div>
</div>
`;
const buttons = `
<div class="autosave-dialog--text-right">
<button type="button" class="autosave-dialog__btn autosave-dialog--btn-compare">
${this.#fontAwesomeIcon('fa-code-branch')} Compare
</button>
<button type="button" class="autosave-dialog__btn autosave-dialog--btn-discard">
${this.#fontAwesomeIcon('fa-trash-alt')} Discard
</button>
<button type="button" class="autosave-dialog__btn autosave-dialog--btn-restore">
${this.#fontAwesomeIcon('fa-redo-alt')} Restore
</button>
</div>
`;
this.#showDialog(form, formId, title, body, buttons)
}
#showDataComparison(form, formId) {
// Get the saved data for this form
const storageKey = this.storagePrefix + formId;
let saved = this.#storage.getItem(storageKey);
const { data: savedData } = JSON.parse(saved);
const { data: currentData } = this.#getFormData(form);
const formatValue = (val) => {
if (typeof val === 'boolean') {
return val
? `<span class="autosave-dialog--icon-checked">${this.#fontAwesomeIcon('fa-check-square')}</span>`
: `<span class="autosave-dialog--icon-unchecked">${this.#fontAwesomeIcon('fa-square')}</span>`
}
if (Array.isArray(val)) {
return val.length > 0
? val.map(v => `<span>${v}</span>`).join('<br>')
: '<em>empty</em>';
}
if (val === '') {
return '<em>empty</em>';
}
const str = String(val);
return str.length > 50 ? `<span title="${str}">${str.substring(0, 50)}...</span>` : str;
}
let tableRows = '';
const allFields = new Set([...Object.keys(savedData), ...Object.keys(currentData)]);
allFields.forEach(field => {
const savedVal = savedData[field] || '';
const currentVal = currentData[field] || '';
const isDifferent = savedVal !== currentVal;
tableRows += `
<tr ${isDifferent ? 'class="autosave-dialog--alert-compare"' : ''}>
<th>${field}</th>
<td>${formatValue(savedVal)}</td>
<td>${formatValue(currentVal)}</td>
</tr>
`;
});
const title = `${this.#fontAwesomeIcon('fa-code-branch')} Data Comparison`;
const body = `
<div class="autosave-dialog__alert autosave-dialog--alert-compare" role="alert">
${this.#fontAwesomeIcon('fa-exclamation-triangle')}
<strong>Hilighted rows</strong> indicate differences between saved and current data.
</div>
<div style="min-height: 0.1%; overflow-x: auto;">
<table class="autosave-dialog__table">
<thead>
<tr class="active">
<th>Field</th>
<th>Saved Value</th>
<th>Current Value</th>
</tr>
</thead>
<tbody>
${tableRows}
</tbody>
</table>
</div>
`;
const buttons = `
<div class="autosave-dialog--text-right">
<button type="button" class="autosave-dialog__btn autosave-dialog--btn-discard">
${this.#fontAwesomeIcon('fa-times')} Keep Current
</button>
<button type="button" class="autosave-dialog__btn autosave-dialog--btn-restore">
${this.#fontAwesomeIcon('fa-redo-alt')} Restore Saved
</button>
</div>
`;
this.#showDialog(form, formId, title, body, buttons)
}
// Public API methods
getFormIdentifier(form) {
const cleanString = (str) => str.trim().toLowerCase().replace(/^\/+|\/+$/g, '').replace(/[^\w\-]+/g, '_');
return form.id || form.name || cleanString(form.action) || `${cleanString(location.pathname)}_form_${Array.from(document.forms).indexOf(form)}`;
}
getStorageInfo() {
return Object.keys(this.#storage)
.filter(key => key.startsWith(this.storagePrefix))
.reduce((acc, key) => {
acc.formCount++;
acc.totalSize += (key.length + (this.#storage.getItem(key) || "").length);
acc.totalSizeKB = (acc.totalSize / 1024).toFixed(2);
return acc;
}, { formCount: 0, totalSize: 0, totalSizeKB: '0.00' });
}
export(formId) {
const storageKey = this.storagePrefix + formId;
let data = this.#storage.getItem(storageKey);
if (!data) return null;
return JSON.parse(data);
}
import(formId, data) {
const storageKey = this.storagePrefix + formId;
let dataToStore = JSON.stringify(data);
this.#storage.setItem(storageKey, dataToStore);
}
getForm(formId) {
this.#getFormData(formId);
}
saveForm(formId) {
this.#saveFormData(formId);
}
saveAllForms() {
this.#forms.forEach((form, formId) => {
// Clear debounce and save immediately
if (this.#debounceTimers.has(formId)) {
clearTimeout(this.#debounceTimers.get(formId));
}
this.#saveFormData(formId);
});
}
clearForm(formId) {
this.#clearFormData(formId);
}
clearAllForms() {
Object.keys(this.#storage)
.filter(key => key.startsWith(this.storagePrefix))
.forEach(key => this.#storage.removeItem(key));
}
}
if (typeof module !== 'undefined' && module.exports) {
module.exports = FormAutoSave;
}