sozday-veb-prilozhenie-dlya/script.js

241 lines
6.8 KiB
JavaScript
Raw Permalink 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.

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 = `
<button class="category-tab active" data-category="all" onclick="filterByCategory('all')">
📚 Все документы
</button>
`;
// Вкладки по категориям
allCategories.forEach(category => {
tabsHTML += `
<button class="category-tab" data-category="${category.id}" onclick="filterByCategory('${category.id}')">
${category.icon} ${category.name}
</button>
`;
});
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 => `
<div class="document-card">
<h3>${doc.title}</h3>
<p>${doc.description}</p>
<div class="document-meta">
<span class="document-type">${doc.categoryIcon} ${doc.categoryName}</span>
<button class="view-btn" onclick="viewDocument(${doc.id})">
Просмотр
</button>
</div>
</div>
`).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(`
<!DOCTYPE html>
<html lang="ru">
<head>
<meta charset="utf-8">
<title>${currentDocument.title}</title>
<style>
body {
font-family: "Times New Roman", Times, serif;
font-size: 14px;
line-height: 1.8;
padding: 40px;
max-width: 800px;
margin: 0 auto;
}
h1 {
font-size: 18px;
text-align: center;
margin-bottom: 30px;
}
pre {
white-space: pre-wrap;
font-family: "Courier New", Courier, monospace;
font-size: 13px;
}
</style>
</head>
<body>
<h1>${currentDocument.title}</h1>
<pre>${currentDocument.content}</pre>
</body>
</html>
`);
printWindow.document.close();
printWindow.print();
}
// Утилита для очистки имени файла
function sanitizeFilename(filename) {
return filename
.replace(/[^a-zа-яё0-9\s]/gi, '')
.replace(/\s+/g, '_')
.substring(0, 50);
}
// Инициализация
loadData();