forked from WorkofAditya/ChatBot
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathapp.js
More file actions
315 lines (266 loc) · 9 KB
/
app.js
File metadata and controls
315 lines (266 loc) · 9 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
// IndexedDB Wrapper
const DB_NAME = "VaultDB";
const STORE_NAME = "documents";
const DB_VERSION = 1;
function openDB() {
return new Promise((resolve, reject) => {
const request = indexedDB.open(DB_NAME, DB_VERSION);
request.onupgradeneeded = (e) => {
const db = e.target.result;
if (!db.objectStoreNames.contains(STORE_NAME)) {
db.createObjectStore(STORE_NAME, { keyPath: "id", autoIncrement: true });
}
};
request.onsuccess = (e) => resolve(e.target.result);
request.onerror = (e) => reject(e.target.error);
});
}
async function saveDocToDB(doc) {
const db = await openDB();
const tx = db.transaction(STORE_NAME, "readwrite");
tx.objectStore(STORE_NAME).add(doc);
return tx.complete;
}
async function getAllDocs() {
const db = await openDB();
return new Promise((resolve, reject) => {
const tx = db.transaction(STORE_NAME, "readonly");
const store = tx.objectStore(STORE_NAME);
const request = store.getAll();
request.onsuccess = () => resolve(request.result);
request.onerror = reject;
});
}
async function clearVaultDB() {
const db = await openDB();
const tx = db.transaction(STORE_NAME, "readwrite");
tx.objectStore(STORE_NAME).clear();
return tx.complete;
}
// DOM Elements
const chatbox = document.getElementById('chatbox');
const userInput = document.getElementById('userInput');
const sendBtn = document.getElementById('sendBtn');
const addDocBtn = document.getElementById('addDocBtn');
const popup = document.getElementById('popup');
const saveDocBtn = document.getElementById('saveDocBtn');
const cancelBtn = document.getElementById('cancelBtn');
const clearBtn = document.getElementById('clearBtn');
const exportBtn = document.getElementById('exportBtn');
const importBtn = document.getElementById('importBtn');
const importFile = document.getElementById('importFile');
// Helper Functions
function addMessage(text, sender) {
const div = document.createElement('div');
div.className = sender === 'user' ? 'user-message' : 'bot-message';
div.textContent = text;
chatbox.appendChild(div);
chatbox.scrollTop = chatbox.scrollHeight;
}
let vault = [];
(async () => {
vault = await getAllDocs();
})();
function findDoc(query) {
query = query.toLowerCase();
return vault.filter(d => query.includes(d.name.toLowerCase()) || d.name.toLowerCase().includes(query));
}
// Typing Animation
function showTyping() {
const typing = document.createElement('div');
typing.className = 'typing';
typing.innerHTML = `<span></span><span></span><span></span>`;
chatbox.appendChild(typing);
chatbox.scrollTop = chatbox.scrollHeight;
return typing;
}
function removeTyping(el) {
if (el && el.parentNode) el.parentNode.removeChild(el);
}
// Toast Feedback
function showToast(msg, type = 'info') {
const toast = document.createElement('div');
toast.className = `toast ${type}`;
toast.textContent = msg;
document.body.appendChild(toast);
setTimeout(() => toast.classList.add('show'), 10);
setTimeout(() => {
toast.classList.remove('show');
setTimeout(() => toast.remove(), 300);
}, 3000);
}
// Chat Logic
sendBtn.onclick = () => {
const text = userInput.value.trim();
if (!text) return;
addMessage(text, 'user');
userInput.value = '';
const typingEl = showTyping();
setTimeout(() => {
removeTyping(typingEl);
const matches = findDoc(text); // now returns multiple docs
if (matches.length > 0) {
matches.forEach((doc, index) => {
let reply = `${index + 1}. ${doc.name}: ${doc.value}`;
if (doc.info) reply += `<br>${doc.info}`;
addMessage(reply, 'bot');
if (doc.file) {
if (doc.file.type.startsWith('image/')) {
const img = document.createElement('img');
img.src = doc.file.data;
img.alt = doc.file.name;
img.style.maxWidth = '180px';
img.style.borderRadius = '10px';
img.style.marginTop = '6px';
img.style.display = 'block';
chatbox.appendChild(img);
const downloadLink = document.createElement('a');
downloadLink.href = doc.file.data;
downloadLink.download = doc.file.name;
downloadLink.textContent = `Download ${doc.file.name}`;
downloadLink.style.display = 'inline-block';
downloadLink.style.marginTop = '6px';
downloadLink.style.color = '#8ab4ff';
chatbox.appendChild(downloadLink);
} else {
const link = document.createElement('a');
link.href = doc.file.data;
link.download = doc.file.name;
link.textContent = `Download ${doc.file.name}`;
link.style.display = 'inline-block';
link.style.marginTop = '6px';
link.style.color = '#8ab4ff';
chatbox.appendChild(link);
}
}
});
setTimeout(() => {
chatbox.scrollTop = chatbox.scrollHeight;
}, 200);
} else {
addMessage('No record found for that query.', 'bot');
}
}, 400 + Math.random() * 600); // Natural delay
};
// Pressing Enter also sends the message
userInput.addEventListener("keypress", (e) => {
if (e.key === "Enter") {
e.preventDefault();
sendBtn.click();
}
});
// Add Document Popup
addDocBtn.onclick = () => (popup.style.display = 'flex');
cancelBtn.onclick = () => (popup.style.display = 'none');
saveDocBtn.onclick = async () => {
const name = document.getElementById('docName').value.trim();
const value = document.getElementById('docValue').value.trim();
const info = document.getElementById('docInfo').value.trim();
const fileInput = document.getElementById('docFile');
const file = fileInput.files[0];
if (!name) {
return showToast('Document name and value are required', 'error');
}
let fileData = null;
if (file) {
fileData = await new Promise((resolve, reject) => {
const reader = new FileReader();
reader.onload = () => resolve({
name: file.name,
type: file.type,
data: reader.result
});
reader.onerror = reject;
reader.readAsDataURL(file);
});
}
const doc = { name, value, info, file: fileData };
await saveDocToDB(doc);
vault.push(doc);
popup.style.display = 'none';
document.getElementById('docName').value = '';
document.getElementById('docValue').value = '';
document.getElementById('docInfo').value = '';
fileInput.value = '';
addMessage(`${name} added successfully.`, 'bot');
showToast('Document saved securely in vault', 'success');
};
// Clear Vault
clearBtn.onclick = async () => {
if (confirm('Are you sure you want to clear the vault?')) {
await clearVaultDB();
vault = [];
addMessage('Vault cleared successfully.', 'bot');
showToast('Vault cleared', 'success');
}
};
// Export Vault
exportBtn.onclick = () => {
const blob = new Blob([JSON.stringify(vault, null, 2)], { type: 'application/json' });
const url = URL.createObjectURL(blob);
const a = document.createElement('a');
a.href = url;
a.download = 'vault_backup.json';
a.click();
showToast('Vault exported', 'success');
};
// Import Vault
importBtn.onclick = () => importFile.click();
importFile.onchange = async (e) => {
const file = e.target.files[0];
if (!file) return;
const reader = new FileReader();
reader.onload = async (event) => {
try {
const data = JSON.parse(event.target.result);
// Validate it’s an array
if (!Array.isArray(data)) {
alert("Invalid file format. Expected a list of documents.");
return;
}
// Convert legacy entries (from old localStorage system)
const converted = data.map(d => {
return {
name: d.name || "Unnamed",
value: d.value || "",
info: d.info || "",
file: d.file || null, // may already be a DataURL or null
};
});
// Save each document to IndexedDB
for (const doc of converted) {
await saveDocToDB(doc);
}
vault = await getAllDocs();
addMessage("Vault imported successfully.", "bot");
showToast("Vault imported successfully!", "success");
} catch (err) {
console.error("Import error:", err);
alert("Invalid file format or corrupted JSON.");
}
};
reader.readAsText(file);
};
if ("serviceWorker" in navigator) {
window.addEventListener("load", () => {
navigator.serviceWorker
.register("./service-worker.js")
.then(() => console.log("Service Worker Registered"))
.catch((err) => console.error("Service Worker failed:", err));
});
}
function addMessage(content, sender) {
const div = document.createElement('div');
div.className = sender === 'user' ? 'user-message' : 'bot-message';
// Render HTML if content contains <br> or <a> or <img>
if (typeof content === "string" && (content.includes("<br>") || content.includes("<a") || content.includes("<img"))) {
div.innerHTML = content;
} else {
div.textContent = content;
}
chatbox.appendChild(div);
// Auto-scroll
setTimeout(() => {
chatbox.scrollTop = chatbox.scrollHeight;
}, 1000);
}