Spaces:
Running
Running
File size: 6,609 Bytes
deb090d |
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 |
/**
* Conversation Storage Utility
* Handles conversation persistence with localStorage
*/
const STORAGE_KEY = 'ca_study_conversations';
const MAX_CONVERSATIONS = 50; // Limit to prevent localStorage overflow
export class ConversationStorage {
/**
* Load all conversations from localStorage
*/
static loadConversations() {
try {
const stored = localStorage.getItem(STORAGE_KEY);
if (!stored) return [];
const conversations = JSON.parse(stored);
// Convert date strings back to Date objects
return conversations.map(conv => ({
...conv,
createdAt: new Date(conv.createdAt),
messages: conv.messages.map(msg => ({
...msg,
timestamp: new Date(msg.timestamp)
}))
}));
} catch (error) {
console.error('Error loading conversations:', error);
return [];
}
}
/**
* Save conversations to localStorage
*/
static saveConversations(conversations) {
try {
// Limit the number of conversations to prevent localStorage overflow
const limitedConversations = conversations.slice(0, MAX_CONVERSATIONS);
localStorage.setItem(STORAGE_KEY, JSON.stringify(limitedConversations));
return true;
} catch (error) {
console.error('Error saving conversations:', error);
// Handle localStorage quota exceeded
if (error.name === 'QuotaExceededError') {
// Try to save with fewer conversations
const reducedConversations = conversations.slice(0, 25);
try {
localStorage.setItem(STORAGE_KEY, JSON.stringify(reducedConversations));
return true;
} catch (retryError) {
console.error('Error saving reduced conversations:', retryError);
}
}
return false;
}
}
/**
* Add a new conversation
*/
static addConversation(conversation) {
const conversations = this.loadConversations();
const newConversations = [conversation, ...conversations];
return this.saveConversations(newConversations);
}
/**
* Update an existing conversation
*/
static updateConversation(conversationId, updates) {
const conversations = this.loadConversations();
const updatedConversations = conversations.map(conv =>
conv.id === conversationId ? { ...conv, ...updates } : conv
);
return this.saveConversations(updatedConversations);
}
/**
* Delete a conversation
*/
static deleteConversation(conversationId) {
const conversations = this.loadConversations();
const filteredConversations = conversations.filter(conv => conv.id !== conversationId);
return this.saveConversations(filteredConversations);
}
/**
* Add a message to a conversation
*/
static addMessage(conversationId, message) {
const conversations = this.loadConversations();
const updatedConversations = conversations.map(conv => {
if (conv.id === conversationId) {
return {
...conv,
messages: [...conv.messages, message],
updatedAt: new Date()
};
}
return conv;
});
return this.saveConversations(updatedConversations);
}
/**
* Search conversations by title or content
*/
static searchConversations(query) {
const conversations = this.loadConversations();
const lowercaseQuery = query.toLowerCase();
return conversations.filter(conv =>
conv.title.toLowerCase().includes(lowercaseQuery) ||
conv.messages.some(msg =>
msg.content.toLowerCase().includes(lowercaseQuery)
)
);
}
/**
* Get conversation statistics
*/
static getStatistics() {
const conversations = this.loadConversations();
const totalMessages = conversations.reduce((sum, conv) => sum + conv.messages.length, 0);
return {
totalConversations: conversations.length,
totalMessages,
storageSize: this.getStorageSize(),
oldestConversation: conversations.length > 0 ?
conversations[conversations.length - 1].createdAt : null,
newestConversation: conversations.length > 0 ?
conversations[0].createdAt : null
};
}
/**
* Get storage size in KB
*/
static getStorageSize() {
try {
const stored = localStorage.getItem(STORAGE_KEY);
return stored ? Math.round(new Blob([stored]).size / 1024) : 0;
} catch (error) {
return 0;
}
}
/**
* Export conversations as JSON
*/
static exportConversations() {
const conversations = this.loadConversations();
const exportData = {
exportDate: new Date().toISOString(),
version: '1.0',
conversations
};
const blob = new Blob([JSON.stringify(exportData, null, 2)], {
type: 'application/json'
});
const url = URL.createObjectURL(blob);
const a = document.createElement('a');
a.href = url;
a.download = `ca_study_conversations_${new Date().toISOString().split('T')[0]}.json`;
document.body.appendChild(a);
a.click();
document.body.removeChild(a);
URL.revokeObjectURL(url);
}
/**
* Import conversations from JSON file
*/
static importConversations(file) {
return new Promise((resolve, reject) => {
const reader = new FileReader();
reader.onload = (e) => {
try {
const importData = JSON.parse(e.target.result);
if (!importData.conversations || !Array.isArray(importData.conversations)) {
reject(new Error('Invalid conversation file format'));
return;
}
const existingConversations = this.loadConversations();
const mergedConversations = [...importData.conversations, ...existingConversations];
// Remove duplicates based on ID
const uniqueConversations = mergedConversations.filter((conv, index, self) =>
index === self.findIndex(c => c.id === conv.id)
);
const success = this.saveConversations(uniqueConversations);
resolve({ success, count: importData.conversations.length });
} catch (error) {
reject(error);
}
};
reader.onerror = () => reject(new Error('Error reading file'));
reader.readAsText(file);
});
}
/**
* Clear all conversations
*/
static clearAllConversations() {
try {
localStorage.removeItem(STORAGE_KEY);
return true;
} catch (error) {
console.error('Error clearing conversations:', error);
return false;
}
}
}
export default ConversationStorage; |