feat(paradiz-web): persist client chat history in localStorage
This commit is contained in:
@@ -9,14 +9,51 @@
|
||||
|
||||
if(!fab || !modal || !closeBtn || !sendBtn || !input || !log) return;
|
||||
|
||||
const STORAGE_KEY = 'paradiz_web_chat_history_v1';
|
||||
const MAX_MESSAGES = 80;
|
||||
|
||||
const saveHistory = () => {
|
||||
try {
|
||||
const items = Array.from(log.querySelectorAll('.paradiz-msg')).map((el) => ({
|
||||
text: el.textContent || '',
|
||||
type: el.classList.contains('paradiz-user') ? 'user' : 'bot'
|
||||
}));
|
||||
const trimmed = items.slice(-MAX_MESSAGES);
|
||||
localStorage.setItem(STORAGE_KEY, JSON.stringify(trimmed));
|
||||
} catch(_) {}
|
||||
};
|
||||
|
||||
const restoreHistory = () => {
|
||||
try {
|
||||
const raw = localStorage.getItem(STORAGE_KEY);
|
||||
if(!raw) return false;
|
||||
const arr = JSON.parse(raw);
|
||||
if(!Array.isArray(arr) || !arr.length) return false;
|
||||
log.innerHTML = '';
|
||||
for(const item of arr){
|
||||
const p = document.createElement('p');
|
||||
p.className = 'paradiz-msg ' + (item.type === 'user' ? 'paradiz-user' : 'paradiz-bot');
|
||||
p.textContent = String(item.text || '');
|
||||
log.appendChild(p);
|
||||
}
|
||||
log.scrollTop = log.scrollHeight;
|
||||
return true;
|
||||
} catch(_) {
|
||||
return false;
|
||||
}
|
||||
};
|
||||
|
||||
const addMsg = (text, type) => {
|
||||
const p = document.createElement('p');
|
||||
p.className = 'paradiz-msg ' + (type === 'user' ? 'paradiz-user' : 'paradiz-bot');
|
||||
p.textContent = text;
|
||||
log.appendChild(p);
|
||||
log.scrollTop = log.scrollHeight;
|
||||
saveHistory();
|
||||
};
|
||||
|
||||
restoreHistory();
|
||||
|
||||
fab.addEventListener('click', () => {
|
||||
modal.style.display = (modal.style.display === 'block') ? 'none' : 'block';
|
||||
if(modal.style.display === 'block') input.focus();
|
||||
@@ -35,7 +72,11 @@
|
||||
|
||||
addMsg('Вы: ' + q, 'user');
|
||||
input.value = '';
|
||||
addMsg('Печатают…', 'bot');
|
||||
const typingEl = document.createElement('p');
|
||||
typingEl.className = 'paradiz-msg paradiz-bot';
|
||||
typingEl.textContent = 'Печатают…';
|
||||
log.appendChild(typingEl);
|
||||
log.scrollTop = log.scrollHeight;
|
||||
|
||||
try {
|
||||
const body = new URLSearchParams();
|
||||
@@ -51,12 +92,14 @@
|
||||
});
|
||||
|
||||
const data = await resp.json();
|
||||
if(typingEl && typingEl.parentNode) typingEl.parentNode.removeChild(typingEl);
|
||||
if(data && data.success){
|
||||
addMsg((data.data && data.data.answer) ? data.data.answer : 'Нет ответа', 'bot');
|
||||
} else {
|
||||
addMsg((data && data.data && data.data.message) ? data.data.message : 'Ошибка', 'bot');
|
||||
}
|
||||
} catch (e) {
|
||||
if(typingEl && typingEl.parentNode) typingEl.parentNode.removeChild(typingEl);
|
||||
addMsg('Сетевая ошибка: ' + (e && e.message ? e.message : 'unknown'), 'bot');
|
||||
}
|
||||
};
|
||||
|
||||
Reference in New Issue
Block a user