BeKultur/public/js/app.js
2026-10-21 21:07:54 +00:00

392 lines
14 KiB
JavaScript
Raw Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

document.addEventListener('DOMContentLoaded', () => {
const assignmentList = document.getElementById('assignmentList');
const searchInput = document.getElementById('searchInput');
const searchClear = document.getElementById('searchClear');
const subjectSelect = document.getElementById('subjectSelect');
const filterTabs = document.getElementById('filterTabs');
const filteredCountText = document.getElementById('filteredCountText');
const noResults = document.getElementById('noResults');
const btnResetFilters = document.getElementById('btnResetFilters');
const syncAlert = document.getElementById('syncAlert');
const btnSyncRecent = document.getElementById('btnSyncRecent');
const btnSyncAll = document.getElementById('btnSyncAll');
const subjectToggleHeader = document.getElementById('subjectToggleHeader');
const subjectBreakdownBody = document.getElementById('subjectBreakdownBody');
const subjectToggleIcon = document.getElementById('subjectToggleIcon');
let currentTab = 'all';
let currentSearch = '';
let currentSubject = '';
// Checkbox toggle
if (assignmentList) {
assignmentList.addEventListener('click', async (e) => {
const target = e.target;
// Exclude / Restore button
if (target.classList.contains('btn-exclude') || target.classList.contains('btn-disinclude')) {
if (window.BeKulturPWA && window.BeKulturPWA.isOffline()) {
alert('Çevrimdışı moddasınız. Ödev gizleme/geri alma işlemi için internet bağlantısı gereklidir.');
return;
}
const assignmentId = target.dataset.id;
const card = target.closest('.assignment-card');
if (!card) return;
const currentExcluded = card.dataset.excluded === 'true';
const newExcluded = !currentExcluded;
target.disabled = true;
try {
const res = await fetch('/api/exclude', {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({ assignmentId, excluded: newExcluded })
});
const data = await res.json();
if (data.success && data.stats) {
card.dataset.excluded = newExcluded ? 'true' : 'false';
card.classList.toggle('is-excluded', newExcluded);
target.textContent = newExcluded ? 'Restore' : 'Exclude';
target.title = newExcluded ? 'Restore this homework to your active list' : 'Exclude this homework (e.g. from another class)';
const checkbox = card.querySelector('.assignment-toggle');
if (checkbox) checkbox.disabled = newExcluded;
let badgeExcluded = card.querySelector('.badge-excluded');
if (newExcluded && !badgeExcluded) {
const badgesContainer = card.querySelector('.card-badges');
if (badgesContainer) {
const b = document.createElement('span');
b.className = 'badge badge-excluded';
b.textContent = 'Excluded';
badgesContainer.insertBefore(b, target);
}
} else if (!newExcluded && badgeExcluded) {
badgeExcluded.remove();
}
updateStatsUI(data.stats);
applyFilters();
}
} catch (err) {
console.error('Failed to toggle exclude:', err);
} finally {
target.disabled = false;
}
return;
}
});
assignmentList.addEventListener('change', async (e) => {
const target = e.target;
if (!target.classList.contains('assignment-toggle')) return;
if (window.BeKulturPWA && window.BeKulturPWA.isOffline()) {
target.checked = !target.checked;
alert('Çevrimdışı moddasınız. Ödev durumu internet bağlantısı olmadan değiştirilemez.');
return;
}
const assignmentId = target.dataset.id;
const isChecked = target.checked;
const card = target.closest('.assignment-card');
if (!card) return;
if (isChecked) {
card.classList.add('is-completed');
card.dataset.completed = 'true';
updateCardBadge(card, 'completed');
} else {
card.classList.remove('is-completed');
card.dataset.completed = 'false';
updateCardBadge(card, card.dataset.status);
}
try {
const res = await fetch('/api/toggle', {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({ assignmentId, completed: isChecked })
});
const data = await res.json();
if (data.success && data.stats) {
updateStatsUI(data.stats);
applyFilters();
}
} catch (err) {
console.error('Failed to toggle assignment:', err);
}
});
}
function updateCardBadge(card, status) {
const badgesContainer = card.querySelector('.card-badges');
if (!badgesContainer) return;
let existingStatusBadge = badgesContainer.querySelector(
'.badge-completed, .badge-next-week, .badge-due-soon, .badge-overdue, .badge-active'
);
if (existingStatusBadge) {
if (status === 'completed') {
existingStatusBadge.className = 'badge badge-completed';
existingStatusBadge.textContent = 'Done';
} else {
const orig = card.dataset.status;
if (orig === 'next-week') {
existingStatusBadge.className = 'badge badge-next-week';
existingStatusBadge.textContent = 'Next Week';
} else if (orig === 'due-soon') {
existingStatusBadge.className = 'badge badge-due-soon';
existingStatusBadge.textContent = 'Due Soon';
} else if (orig === 'overdue') {
existingStatusBadge.className = 'badge badge-overdue';
existingStatusBadge.textContent = 'Overdue';
} else {
existingStatusBadge.className = 'badge badge-active';
existingStatusBadge.textContent = 'Active';
}
}
}
}
function updateStatsUI(stats) {
const statCompRate = document.getElementById('statCompletionRate');
const statCompFrac = document.getElementById('statCompletionFraction');
const progressBar = document.getElementById('progressBarFill');
const statActive = document.getElementById('statActiveCount');
const statNextWeek = document.getElementById('statNextWeekCount');
const statDueSoon = document.getElementById('statDueSoonCount');
const statOverdue = document.getElementById('statOverdueCount');
const statTotal = document.getElementById('statTotalCount');
if (statCompRate) statCompRate.textContent = `${stats.completionRate}%`;
if (statCompFrac) statCompFrac.textContent = `${stats.completed} / ${stats.total} done`;
if (progressBar) progressBar.style.width = `${stats.completionRate}%`;
if (statActive) statActive.textContent = stats.active;
if (statNextWeek) statNextWeek.textContent = stats.checkedNextWeek;
if (statDueSoon) statDueSoon.textContent = stats.dueSoon;
if (statOverdue) statOverdue.textContent = stats.overdue;
if (statTotal) statTotal.textContent = stats.total;
const tabAll = document.getElementById('tabAllCount');
const tabNext = document.getElementById('tabNextWeekCount');
const tabAct = document.getElementById('tabActiveCount');
const tabDue = document.getElementById('tabDueSoonCount');
const tabComp = document.getElementById('tabCompletedCount');
const tabOver = document.getElementById('tabOverdueCount');
const tabExcluded = document.getElementById('tabExcludedCount');
if (tabAll) tabAll.textContent = stats.total;
if (tabNext) tabNext.textContent = stats.checkedNextWeek;
if (tabAct) tabAct.textContent = stats.active;
if (tabDue) tabDue.textContent = stats.dueSoon;
if (tabComp) tabComp.textContent = stats.completed;
if (tabOver) tabOver.textContent = stats.overdue;
if (tabExcluded) tabExcluded.textContent = stats.excludedCount || 0;
if (stats.bySubject) {
Object.values(stats.bySubject).forEach(s => {
const item = document.querySelector(`.subject-item[data-subject="${CSS.escape(s.subject)}"]`);
if (item) {
const frac = item.querySelector('.subject-fraction');
const fill = item.querySelector('.subject-bar-fill');
if (frac) frac.textContent = `${s.completed}/${s.total} (${s.percentage}%)`;
if (fill) fill.style.width = `${s.percentage}%`;
}
});
}
}
// Filter tabs
if (filterTabs) {
filterTabs.addEventListener('click', (e) => {
const btn = e.target.closest('.tab-btn');
if (!btn) return;
filterTabs.querySelectorAll('.tab-btn').forEach(b => b.classList.remove('active'));
btn.classList.add('active');
currentTab = btn.dataset.filter || 'all';
applyFilters();
});
}
function normalizeTurkish(str) {
if (!str) return '';
return str
.replace(/İ/g, 'i')
.replace(/I/g, 'ı')
.toLowerCase();
}
if (searchInput) {
searchInput.addEventListener('input', (e) => {
currentSearch = normalizeTurkish(e.target.value.trim());
if (searchClear) searchClear.classList.toggle('hidden', currentSearch.length === 0);
applyFilters();
});
}
if (searchClear) {
searchClear.addEventListener('click', () => {
searchInput.value = '';
currentSearch = '';
searchClear.classList.add('hidden');
applyFilters();
});
}
if (subjectSelect) {
subjectSelect.addEventListener('change', (e) => {
currentSubject = e.target.value;
applyFilters();
});
}
if (btnResetFilters) {
btnResetFilters.addEventListener('click', () => {
currentTab = 'all';
currentSearch = '';
currentSubject = '';
if (searchInput) searchInput.value = '';
if (searchClear) searchClear.classList.add('hidden');
if (subjectSelect) subjectSelect.value = '';
if (filterTabs) {
filterTabs.querySelectorAll('.tab-btn').forEach(b => b.classList.remove('active'));
const allTab = filterTabs.querySelector('[data-filter="all"]');
if (allTab) allTab.classList.add('active');
}
applyFilters();
});
}
function applyFilters() {
if (!assignmentList) return;
const cards = assignmentList.querySelectorAll('.assignment-card');
let visibleCount = 0;
cards.forEach(card => {
const status = card.dataset.status;
const isCompleted = card.dataset.completed === 'true';
const isExcluded = card.dataset.excluded === 'true';
const subject = card.dataset.subject;
const searchText = card.dataset.search || '';
let matchesTab = true;
if (currentTab === 'excluded') {
matchesTab = isExcluded;
} else {
if (isExcluded) {
matchesTab = false;
} else if (currentTab === 'completed') {
matchesTab = isCompleted;
} else if (currentTab === 'active') {
matchesTab = !isCompleted && (status === 'active' || status === 'next-week' || status === 'due-soon');
} else if (currentTab === 'next-week') {
matchesTab = !isCompleted && status === 'next-week';
} else if (currentTab === 'due-soon') {
matchesTab = !isCompleted && status === 'due-soon';
} else if (currentTab === 'overdue') {
matchesTab = !isCompleted && status === 'overdue';
}
}
let matchesSubject = true;
if (currentSubject) {
matchesSubject = (subject === currentSubject);
}
let matchesSearch = true;
if (currentSearch) {
matchesSearch = normalizeTurkish(searchText).includes(currentSearch);
}
if (matchesTab && matchesSubject && matchesSearch) {
card.style.display = 'flex';
visibleCount++;
} else {
card.style.display = 'none';
}
});
if (filteredCountText) {
filteredCountText.textContent = `Showing ${visibleCount} assignments`;
}
if (noResults) {
noResults.classList.toggle('hidden', visibleCount > 0);
}
}
// Sync actions
if (btnSyncRecent) {
btnSyncRecent.addEventListener('click', async () => {
if (window.BeKulturPWA && window.BeKulturPWA.isOffline()) {
showAlert('Çevrimdışı moddasınız. Senkronizasyon için internet bağlantısı gereklidir.', 'danger');
return;
}
btnSyncRecent.disabled = true;
btnSyncRecent.textContent = 'Syncing...';
showAlert('Fetching recent assignments...', 'info');
try {
const res = await fetch('/api/sync', { method: 'POST' });
const data = await res.json();
if (data.success) {
window.location.reload();
} else {
showAlert(`Sync failed: ${data.error}`, 'danger');
btnSyncRecent.disabled = false;
btnSyncRecent.textContent = 'Sync Recent';
}
} catch (err) {
showAlert('Network error while syncing.', 'danger');
btnSyncRecent.disabled = false;
btnSyncRecent.textContent = 'Sync Recent';
}
});
}
if (btnSyncAll) {
btnSyncAll.addEventListener('click', async () => {
if (window.BeKulturPWA && window.BeKulturPWA.isOffline()) {
showAlert('Çevrimdışı moddasınız. Senkronizasyon için internet bağlantısı gereklidir.', 'danger');
return;
}
btnSyncAll.disabled = true;
btnSyncAll.textContent = 'Syncing all...';
showAlert('Syncing full history from portal...', 'info');
try {
const res = await fetch('/api/sync-all', { method: 'POST' });
const data = await res.json();
if (data.success) {
window.location.reload();
} else {
showAlert(`Sync all failed: ${data.error}`, 'danger');
btnSyncAll.disabled = false;
btnSyncAll.textContent = 'Sync Full History';
}
} catch (err) {
showAlert('Network error while syncing full history.', 'danger');
btnSyncAll.disabled = false;
btnSyncAll.textContent = 'Sync Full History';
}
});
}
function showAlert(msg, type = 'info') {
if (!syncAlert) return;
syncAlert.className = `alert alert-${type}`;
syncAlert.textContent = msg;
syncAlert.classList.remove('hidden');
}
// Subject collapse
if (subjectToggleHeader && subjectBreakdownBody && subjectToggleIcon) {
subjectToggleHeader.addEventListener('click', () => {
const isHidden = subjectBreakdownBody.classList.toggle('collapsed');
subjectToggleIcon.textContent = isHidden ? '▶' : '▼';
});
}
});