-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathstorage-manager.js
More file actions
256 lines (232 loc) · 6.2 KB
/
storage-manager.js
File metadata and controls
256 lines (232 loc) · 6.2 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
/**
* storage-manager.js
* Local and cloud storage abstraction
*
* Manages localStorage operations, CSV/JSON export, and data persistence.
*/
// Storage key constants
const STORAGE_KEYS = {
RETRY_QUEUE: 'spelldle_fsrs_retry_queue',
PERMANENT_FAILURES: 'spelldle_permanent_failures',
LESSON_STATS: 'spelldle_lesson_stats',
LAST_LESSON: 'spelldle_last_lesson',
SESSION_DATA: 'spelldle_session_data'
};
/**
* Get item from localStorage
* @param {string} key - Storage key
* @param {*} defaultValue - Default value if key not found
* @returns {*} Stored value or default
*/
export function getFromLocalStorage(key, defaultValue = null) {
try {
const stored = localStorage.getItem(key);
if (stored === null) {
return defaultValue;
}
return JSON.parse(stored);
} catch (error) {
console.error(`Failed to read from localStorage [${key}]:`, error);
return defaultValue;
}
}
/**
* Set item in localStorage
* @param {string} key - Storage key
* @param {*} value - Value to store
* @returns {boolean} Success status
*/
export function setInLocalStorage(key, value) {
try {
localStorage.setItem(key, JSON.stringify(value));
return true;
} catch (error) {
console.error(`Failed to write to localStorage [${key}]:`, error);
return false;
}
}
/**
* Remove item from localStorage
* @param {string} key - Storage key
* @returns {boolean} Success status
*/
export function removeFromLocalStorage(key) {
try {
localStorage.removeItem(key);
return true;
} catch (error) {
console.error(`Failed to remove from localStorage [${key}]:`, error);
return false;
}
}
/**
* Clear all Spelldle-related storage
* @returns {boolean} Success status
*/
export function clearAllStorage() {
try {
Object.values(STORAGE_KEYS).forEach(key => {
localStorage.removeItem(key);
});
return true;
} catch (error) {
console.error('Failed to clear localStorage:', error);
return false;
}
}
/**
* Get FSRS retry queue from storage
* @returns {Array} Retry queue
*/
export function getRetryQueue() {
return getFromLocalStorage(STORAGE_KEYS.RETRY_QUEUE, []);
}
/**
* Save FSRS retry queue to storage
* @param {Array} queue - Retry queue
* @returns {boolean} Success status
*/
export function saveRetryQueue(queue) {
return setInLocalStorage(STORAGE_KEYS.RETRY_QUEUE, queue);
}
/**
* Get permanent failures log
* @returns {Array} Permanent failures
*/
export function getPermanentFailures() {
return getFromLocalStorage(STORAGE_KEYS.PERMANENT_FAILURES, []);
}
/**
* Add permanent failure to log
* @param {Object} failure - Failure object
*/
export function addPermanentFailure(failure) {
const failures = getPermanentFailures();
failures.push(failure);
// Keep only last 50 failures to prevent storage bloat
if (failures.length > 50) {
failures.splice(0, failures.length - 50);
}
setInLocalStorage(STORAGE_KEYS.PERMANENT_FAILURES, failures);
}
/**
* Get lesson statistics
* @returns {Object} Lesson stats object
*/
export function getLessonStats() {
return getFromLocalStorage(STORAGE_KEYS.LESSON_STATS, {});
}
/**
* Save lesson statistics
* @param {string} lessonName - Lesson name
* @param {Object} stats - Stats object
*/
export function saveLessonStats(lessonName, stats) {
const allStats = getLessonStats();
allStats[lessonName] = {
...allStats[lessonName],
...stats,
lastUpdated: new Date().toISOString()
};
return setInLocalStorage(STORAGE_KEYS.LESSON_STATS, allStats);
}
/**
* Export statistics to CSV format
* @param {Array} data - Array of records
* @param {Array} headers - Column headers
* @returns {string} CSV formatted string
*/
export function exportToCSV(data, headers) {
if (!data || !Array.isArray(data) || data.length === 0) {
return '';
}
const csvHeaders = headers || Object.keys(data[0]);
const headerRow = csvHeaders.map(h => `"${h}"`).join(',');
const dataRows = data.map(row => {
return csvHeaders.map(header => {
const value = row[header];
const stringValue = value === null || value === undefined ? '' : String(value);
return `"${stringValue.replace(/"/g, '""')}"`;
}).join(',');
});
return [headerRow, ...dataRows].join('\n');
}
/**
* Export statistics to JSON format
* @param {*} data - Data to export
* @returns {string} JSON formatted string
*/
export function exportToJSON(data) {
try {
return JSON.stringify(data, null, 2);
} catch (error) {
console.error('Failed to export to JSON:', error);
return '';
}
}
/**
* Trigger file download
* @param {string} content - File content
* @param {string} filename - Filename
* @param {string} mimeType - MIME type
*/
export function downloadFile(content, filename, mimeType = 'text/plain') {
const blob = new Blob([content], { type: mimeType });
const url = URL.createObjectURL(blob);
const link = document.createElement('a');
link.href = url;
link.download = filename;
document.body.appendChild(link);
link.click();
document.body.removeChild(link);
URL.revokeObjectURL(url);
}
/**
* Parse CSV data
* @param {string} csvContent - CSV content
* @returns {Object} { headers, rows }
*/
export function parseCSV(csvContent) {
const lines = csvContent.trim().split('\n');
if (lines.length === 0) {
return { headers: [], rows: [] };
}
const headers = lines[0].split(',').map(h => h.trim().replace(/^"|"$/g, ''));
const rows = lines.slice(1).map(line => {
const values = line.split(',').map(v => v.trim().replace(/^"|"$/g, ''));
const row = {};
headers.forEach((header, index) => {
row[header] = values[index] || '';
});
return row;
});
return { headers, rows };
}
/**
* Get all statistics for export
* @returns {Object} Combined statistics object
*/
export function getAllStatisticsForExport() {
return {
lessonStats: getLessonStats(),
permanentFailures: getPermanentFailures(),
exportedAt: new Date().toISOString()
};
}
export default {
getFromLocalStorage,
setInLocalStorage,
removeFromLocalStorage,
clearAllStorage,
getRetryQueue,
saveRetryQueue,
getPermanentFailures,
addPermanentFailure,
getLessonStats,
saveLessonStats,
exportToCSV,
exportToJSON,
downloadFile,
parseCSV,
getAllStatisticsForExport
};