Laska1 / static /script.js
Aist1's picture
Update static/script.js
b8b23c0 verified
// Основные функции для работы с приложением
async function analyzeEmotions() {
const text = document.getElementById('textInput').value;
if (!text.trim()) {
showError('Пожалуйста, введите текст для анализа');
return;
}
showLoading('analysisResult', 'Анализируем эмоции...');
try {
const response = await fetch('/analyze', {
method: 'POST',
headers: {
'Content-Type': 'application/json',
},
body: JSON.stringify({
text: text,
type: 'emotion'
})
});
const data = await response.json();
if (data.error) {
showError(data.error, 'analysisResult');
return;
}
displayEmotionAnalysis(data);
} catch (error) {
showError('Ошибка при анализе: ' + error.message, 'analysisResult');
}
}
async function analyzePersonality() {
const text = document.getElementById('textInput').value;
if (!text.trim()) {
showError('Пожалуйста, введите текст для анализа');
return;
}
showLoading('analysisResult', 'Анализируем паттерны мышления...');
try {
const response = await fetch('/analyze', {
method: 'POST',
headers: {
'Content-Type': 'application/json',
},
body: JSON.stringify({
text: text,
type: 'personality'
})
});
const data = await response.json();
if (data.error) {
showError(data.error, 'analysisResult');
return;
}
displayPersonalityAnalysis(data);
} catch (error) {
showError('Ошибка при анализе: ' + error.message, 'analysisResult');
}
}
async function saveToJournal() {
const text = document.getElementById('textInput').value;
if (!text.trim()) {
showError('Пожалуйста, введите запись для дневника');
return;
}
try {
const response = await fetch('/journal', {
method: 'POST',
headers: {
'Content-Type': 'application/json',
},
body: JSON.stringify({
entry: text
})
});
const data = await response.json();
if (data.error) {
showError(data.error);
return;
}
// Очищаем поле ввода
document.getElementById('textInput').value = '';
// Добавляем запись в дневник
addJournalEntry(data.entry);
showSuccess('Запись успешно сохранена в дневник!');
} catch (error) {
showError('Ошибка при сохранении: ' + error.message);
}
}
async function getInsights() {
showLoading('insightsResult', 'Генерируем инсайты...');
try {
const response = await fetch('/insights');
const data = await response.json();
if (data.error) {
showError(data.error, 'insightsResult');
return;
}
displayInsights(data.insights);
} catch (error) {
showError('Ошибка при получении инсайтов: ' + error.message, 'insightsResult');
}
}
// Функции отображения результатов
function displayEmotionAnalysis(data) {
const container = document.getElementById('analysisResult');
let html = '<h3>Эмоциональный анализ:</h3>';
if (data.dominant_emotion) {
html += `<div class="dominant-emotion">
<strong>Преобладающая эмоция:</strong> ${data.dominant_emotion.label}
(${(data.dominant_emotion.score * 100).toFixed(1)}%)
</div>`;
}
html += '<h4>Все обнаруженные эмоции:</h4>';
if (data.emotions && data.emotions.length > 0) {
data.emotions.forEach(emotion => {
const percentage = (emotion.score * 100).toFixed(1);
html += `
<div class="emotion-item">
<span>${emotion.label}</span>
<span class="emotion-score">${percentage}%</span>
</div>
`;
});
} else {
html += '<p>Не удалось определить эмоции</p>';
}
container.innerHTML = html;
}
function displayPersonalityAnalysis(data) {
const container = document.getElementById('analysisResult');
let html = '<h3>Анализ паттернов:</h3>';
if (data.traits) {
html += `
<div class="trait-item">
<strong>Эмоциональная стабильность:</strong>
${(data.traits.emotional_stability * 100).toFixed(1)}%
</div>
<div class="trait-item">
<strong>Позитивность:</strong>
${(data.traits.positivity * 100).toFixed(1)}%
</div>
<div class="trait-item">
<strong>Сложность мышления:</strong>
${(data.traits.complexity * 100).toFixed(1)}%
</div>
<div class="trait-item">
<strong>Последовательность:</strong>
${(data.traits.consistency * 100).toFixed(1)}%
</div>
`;
} else {
html += '<p>Не удалось проанализировать паттерны</p>';
}
container.innerHTML = html;
}
function displayInsights(insights) {
const container = document.getElementById('insightsResult');
container.innerHTML = `
<div class="insight-text">
"${insights}"
</div>
`;
}
function addJournalEntry(entry) {
const container = document.getElementById('journalEntries');
const entryElement = document.createElement('div');
entryElement.className = 'journal-entry';
const date = new Date(entry.timestamp).toLocaleString('ru-RU');
let emotionsHtml = '';
if (entry.emotions && entry.emotions.length > 0) {
emotionsHtml = '<div class="entry-emotions">';
entry.emotions.forEach(emotion => {
emotionsHtml += `<span class="emotion-tag">${emotion.label} (${(emotion.score * 100).toFixed(0)}%)</span>`;
});
emotionsHtml += '</div>';
}
entryElement.innerHTML = `
<div class="entry-date">${date}</div>
<div class="entry-text">${entry.text}</div>
${emotionsHtml}
`;
container.insertBefore(entryElement, container.firstChild);
}
// Загрузка записей дневника при старте
async function loadJournalEntries() {
try {
const response = await fetch('/journal_entries');
const data = await response.json();
if (data.entries && data.entries.length > 0) {
data.entries.forEach(entry => {
addJournalEntry(entry);
});
}
} catch (error) {
console.error('Ошибка загрузки записей:', error);
}
}
async function loadProgress() {
try {
const response = await fetch('/progress');
const data = await response.json();
const progressContainer = document.getElementById('progressContent');
if (data.message) {
progressContainer.innerHTML = `<p>${data.message}</p>`;
return;
}
if (data.error) {
progressContainer.innerHTML = `<p class="error">${data.error}</p>`;
return;
}
let html = `
<div class="progress-stats">
<div class="stat-item">
<div class="stat-value">${data.total_entries}</div>
<div class="stat-label">Всего записей</div>
</div>
<div class="stat-item">
<div class="stat-value">${(data.consistency_score * 100).toFixed(0)}%</div>
<div class="stat-label">Регулярность</div>
</div>
</div>
`;
progressContainer.innerHTML = html;
} catch (error) {
console.error('Ошибка загрузки прогресса:', error);
document.getElementById('progressContent').innerHTML =
'<p class="error">Ошибка загрузки прогресса</p>';
}
}
// Вспомогательные функции
function showLoading(containerId, message = 'Загрузка...') {
const container = document.getElementById(containerId);
if (container) {
container.innerHTML = `
<div class="loading">${message}</div>
`;
}
}
function showError(message, containerId = null) {
if (containerId) {
const container = document.getElementById(containerId);
if (container) {
container.innerHTML = `
<div class="error">${message}</div>
`;
}
} else {
// Показываем временное уведомление
const notification = document.createElement('div');
notification.className = 'error';
notification.style.cssText = `
position: fixed;
top: 20px;
right: 20px;
background: #fed7d7;
color: #c53030;
padding: 15px 20px;
border-radius: 8px;
z-index: 1000;
box-shadow: 0 4px 12px rgba(0,0,0,0.3);
border-left: 4px solid #c53030;
`;
notification.textContent = message;
document.body.appendChild(notification);
setTimeout(() => {
if (document.body.contains(notification)) {
document.body.removeChild(notification);
}
}, 5000);
}
}
function showSuccess(message) {
const notification = document.createElement('div');
notification.style.cssText = `
position: fixed;
top: 20px;
right: 20px;
background: #48bb78;
color: white;
padding: 15px 20px;
border-radius: 8px;
z-index: 1000;
box-shadow: 0 4px 12px rgba(0,0,0,0.3);
border-left: 4px solid #38a169;
`;
notification.textContent = message;
document.body.appendChild(notification);
setTimeout(() => {
if (document.body.contains(notification)) {
document.body.removeChild(notification);
}
}, 3000);
}
// Инициализация при загрузке страницы
document.addEventListener('DOMContentLoaded', function() {
console.log('Приложение загружено');
loadJournalEntries();
loadProgress();
});