/
a_silinenko
/
project1
Обзор
Документация
Войти
/
a_silinenko
/
project1
Код
Запросы
0
Задачи
Вики
Пакеты
0
Релизы
0
CI/CD
Аналитика
Безопасность
master
script.js
240 строк
9 KB
a_silinenko
Отлажен UX
26 май 2026, 16:37
26 май 2026, 16:37
43a5a52
Код
Авторство
О чём код?
let selectedFile = null; // Обновляем отображение имени файла document.getElementById("fileInput").addEventListener("change", function (event) { const file = event.target.files[0]; const error = document.getElementById("error"); const contentArea = document.getElementById("content"); const fileNameSpan = document.querySelector(".file-name"); // Очистка предыдущих данных error.textContent = ""; contentArea.innerHTML = ""; if (file) { selectedFile = file; fileNameSpan.textContent = file.name; document.getElementById("checkBtn").disabled = false; } else { selectedFile = null; fileNameSpan.textContent = "Не выбрано"; document.getElementById("checkBtn").disabled = true; } }); // Обработка по нажатию кнопки "Проверить" // Обработка по нажатию кнопки "Проверить" document.getElementById("checkBtn").addEventListener("click", function () { if (!selectedFile) return; const fileName = selectedFile.name.toLowerCase(); const fileExt = fileName.split(".").pop(); const error = document.getElementById("error"); const statusArea = document.getElementById("statusArea"); const contentArea = document.getElementById("content"); // Очистка предыдущих данных error.textContent = ""; contentArea.innerHTML = ""; // Показываем статус "Идёт проверка..." statusArea.innerHTML = ` <div class="loader"></div> Идёт проверка файла <strong>${selectedFile.name}</strong>... `; statusArea.classList.add("active"); if (fileExt === "docx") { readDocx(selectedFile); } else if (fileExt === "pdf") { readPdf(selectedFile); } else { error.textContent = "❌ Неверный тип файла. Допустимые форматы: .docx, .pdf"; statusArea.classList.remove("active"); } }); function readDocx(file) { console.log("🔄 Чтение .docx файла:", file.name); const reader = new FileReader(); reader.onload = function (e) { console.log("✅ Файл успешно прочитан"); const arrayBuffer = e.target.result; if (!arrayBuffer || arrayBuffer.byteLength === 0) { console.error("❌ Пустой массив данных"); document.getElementById("error").textContent = "Файл пустой или повреждён."; return; } console.log("➡️ Передача в Mammoth.js..."); mammoth.extractRawText({ arrayBuffer: arrayBuffer }) .then((result) => { console.log("🟢 Текст извлечён:", result.value.substring(0, 200) + "..."); displayText(result.value); }) .catch((err) => { console.error("🔴 Ошибка Mammoth:", err); document.getElementById("error").textContent = "Ошибка при чтении .docx: " + (err.message || String(err)); document.getElementById("content").innerHTML = ""; }); }; reader.onerror = () => { console.error("🔴 Ошибка FileReader:", reader.error); document.getElementById("error").textContent = "Ошибка при чтении файла."; }; reader.readAsArrayBuffer(file); } function readPdf(file) { const reader = new FileReader(); reader.onload = function (e) { const arrayBuffer = e.target.result; // Получаем ArrayBuffer // Преобразуем в typed array для pdf.js const typedarray = new Uint8Array(arrayBuffer); pdfjsLib.getDocument({ data: typedarray }).promise .then((pdf) => { let text = ""; const pages = []; for (let i = 1; i <= pdf.numPages; i++) { pages.push( pdf.getPage(i).then((page) => { return page.getTextContent().then((content) => { const pageText = content.items.map((item) => item.str).join(" "); text += pageText + "\n\n"; }); }) ); } Promise.all(pages).then(() => { displayText(text); }); }) .catch((err) => { console.error("Ошибка при обработке PDF:", err); document.getElementById("error").textContent = "Ошибка при чтении .pdf файла: " + err.message; document.getElementById("content").innerHTML = ""; }); }; reader.readAsArrayBuffer(file); // ✅ Правильный метод } function displayText(text) { const statusArea = document.getElementById("statusArea"); const contentArea = document.getElementById("content"); const statusTitle = document.getElementById("statusTitle"); const contentTitle = document.getElementById("contentTitle"); // Запуск проверок const checkResults = runChecks(text); // Формируем HTML для результатов (без буллетов) const checkHtml = ` <div style="text-align: left; margin: 0; line-height: 1.6;"> ${checkResults.map(result => `${result}<br>`).join('')} </div> `; // Выводим только HTML с проверками statusArea.innerHTML = checkHtml; // Выводим текст без заголовка внутри contentArea.innerHTML = ` <pre style=" white-space: pre-wrap; font-family: sans-serif; font-size: 14px; margin: 0; padding: 8px; background-color: #f9f9f9; border-radius: 4px; width: 100%; box-sizing: border-box; ">${text}</pre> `; // Показываем заголовки и блоки statusTitle.classList.add("visible"); statusArea.classList.add("active"); contentTitle.classList.add("visible"); contentArea.classList.add("has-content"); } function runChecks(text) { const results = []; // 1. Проверка наличия ключевых разделов const lowerText = text.toLowerCase(); if (lowerText.includes("титульный лист") || lowerText.includes("титульная страница")) { results.push("✅ Титульный лист найден."); } else { results.push("❌ Отсутствует упоминание титульного листа."); } if (lowerText.includes("цель") && lowerText.includes("задачи")) { results.push("✅ Цель и задачи указаны."); } else { results.push("⚠️ Не найдены цель или задачи."); } if (lowerText.includes("введение")) { results.push("✅ Введение присутствует."); } else { results.push("❌ Отсутствует введение."); } if (lowerText.includes("заключение") || lowerText.includes("выводы")) { results.push("✅ Заключение или выводы найдены."); } else { results.push("⚠️ Отсутствуют выводы или заключение."); } // 2. Проверка структуры (наличие хотя бы 3 разделов) const sections = text.match(/^[#\s]*\d+\.\s+.+$/gm); if (sections && sections.length >= 3) { results.push(`✅ Найдено ${sections.length} структурированных разделов.`); } else { results.push("⚠️ Мало структурированных разделов (рекомендуется ≥3)."); } // 3. Проверка объёма — теперь в самом конце const wordCount = text.trim().split(/\s+/).length; if (wordCount < 100) { results.push(`⚠️ Маленький объём: ${wordCount} слов. Рекомендуется не менее 100.`); } else { results.push(`✅ Объём достаточен: ${wordCount} слов.`); } return results; } // Кнопка "Очистить" document.getElementById("clearBtn").addEventListener("click", function () { selectedFile = null; document.getElementById("fileInput").value = ""; document.querySelector(".file-name").textContent = "Не выбрано"; document.getElementById("checkBtn").disabled = true; document.getElementById("error").textContent = ""; // Очищаем статус document.getElementById("statusArea").innerHTML = ""; document.getElementById("statusArea").classList.remove("active"); document.getElementById("statusTitle").classList.remove("visible"); // ← Скрываем заголовок // Очищаем содержимое document.getElementById("content").innerHTML = ""; document.getElementById("content").classList.remove("has-content"); document.getElementById("contentTitle").classList.remove("visible"); // ← Скрываем заголовок });