let allCategories = []; let allDocuments = []; let currentCategory = 'all'; let currentDocument = null; // Загрузка данных async function loadData() { try { const response = await fetch('data.json'); const data = await response.json(); allCategories = data.categories; // Собираем все документы в плоский список allDocuments = []; allCategories.forEach(category => { category.docs.forEach(doc => { allDocuments.push({ ...doc, categoryId: category.id, categoryName: category.name, categoryIcon: category.icon }); }); }); renderCategoryTabs(); renderDocuments(allDocuments); } catch (error) { console.error('Ошибка загрузки данных:', error); } } // Рендеринг вкладок категорий function renderCategoryTabs() { const tabsContainer = document.getElementById('categoryTabs'); // Первая вкладка - все документы let tabsHTML = ` `; // Вкладки по категориям allCategories.forEach(category => { tabsHTML += ` `; }); tabsContainer.innerHTML = tabsHTML; } // Фильтрация по категории function filterByCategory(categoryId) { currentCategory = categoryId; // Обновляем активную вкладку document.querySelectorAll('.category-tab').forEach(tab => { tab.classList.remove('active'); if (tab.dataset.category === categoryId) { tab.classList.add('active'); } }); // Фильтруем документы if (categoryId === 'all') { renderDocuments(allDocuments); document.getElementById('sectionTitle').innerHTML = '📚 Все документы'; } else { const category = allCategories.find(c => c.id === categoryId); const filteredDocs = allDocuments.filter(doc => doc.categoryId === categoryId); renderDocuments(filteredDocs); document.getElementById('sectionTitle').innerHTML = `${category.icon} ${category.name}`; } // Очищаем поиск document.getElementById('searchInput').value = ''; } // Рендеринг карточек документов function renderDocuments(documents) { const grid = document.getElementById('documentsGrid'); const noResults = document.getElementById('noResults'); if (documents.length === 0) { grid.innerHTML = ''; noResults.style.display = 'block'; return; } noResults.style.display = 'none'; grid.innerHTML = documents.map(doc => `

${doc.title}

${doc.description}

${doc.categoryIcon} ${doc.categoryName}
`).join(''); } // Поиск документов function searchDocuments() { const query = document.getElementById('searchInput').value.toLowerCase().trim(); if (!query) { filterByCategory(currentCategory); return; } const filtered = allDocuments.filter(doc => doc.title.toLowerCase().includes(query) || doc.description.toLowerCase().includes(query) || doc.content.toLowerCase().includes(query) || doc.categoryName.toLowerCase().includes(query) ); renderDocuments(filtered); document.getElementById('sectionTitle').innerHTML = `🔍 Результаты поиска: "${query}"`; // Сбрасываем активную вкладку document.querySelectorAll('.category-tab').forEach(tab => { tab.classList.remove('active'); }); } // Поиск по Enter document.getElementById('searchInput').addEventListener('keypress', function(e) { if (e.key === 'Enter') { searchDocuments(); } }); // Просмотр документа function viewDocument(docId) { const doc = allDocuments.find(d => d.id === docId); if (!doc) return; currentDocument = doc; document.getElementById('modalTitle').textContent = doc.title; document.getElementById('documentContent').textContent = doc.content; document.getElementById('modalOverlay').classList.add('active'); // Блокируем прокрутку фона document.body.style.overflow = 'hidden'; } // Закрытие модального окна function closeModal() { document.getElementById('modalOverlay').classList.remove('active'); document.body.style.overflow = ''; currentDocument = null; } // Закрытие по клику вне модального окна document.getElementById('modalOverlay').addEventListener('click', function(e) { if (e.target === this) { closeModal(); } }); // Скачивание документа function downloadDocument() { if (!currentDocument) return; const content = currentDocument.content; const filename = sanitizeFilename(currentDocument.title) + '.txt'; const blob = new Blob([content], { type: 'text/plain;charset=utf-8' }); const url = URL.createObjectURL(blob); const a = document.createElement('a'); a.href = url; a.download = filename; document.body.appendChild(a); a.click(); document.body.removeChild(a); URL.revokeObjectURL(url); } // Печать документа function printDocument() { if (!currentDocument) return; const printWindow = window.open('', '_blank'); printWindow.document.write(` ${currentDocument.title}

${currentDocument.title}

${currentDocument.content}
`); printWindow.document.close(); printWindow.print(); } // Утилита для очистки имени файла function sanitizeFilename(filename) { return filename .replace(/[^a-zа-яё0-9\s]/gi, '') .replace(/\s+/g, '_') .substring(0, 50); } // Инициализация loadData();