// --- Data --- const USER = { name: 'Алексей', avatar: 'http://static.photos/people/200x200/42', level: 'B1', levelNum: 3, interventionsLeft: 5, maxInterventions: 5 }; const BOOK = { title: 'The Great Gatsby', author: 'F. Scott Fitzgerald', cover: 'http://static.photos/vintage/320x240/7', chapters: [ { id: 0, title: 'Chapter I' }, { id: 1, title: 'Chapter II' }, { id: 2, title: 'Chapter III' } ] }; const CHAPTER_CONTENT = { 0: { title: 'Chapter I', paragraphs: [ { id: 'p1', text: "In my younger and more vulnerable years my father gave me some advice that I've been turning over in my mind ever since.", difficulty: 3, levelLabel: 'B1' }, { id: 'p2', text: "Whenever you feel like criticizing any one, he told me, just remember that all the people in this world haven't had the advantages that you've had.", difficulty: 3, levelLabel: 'B1' }, { id: 'p3', text: "He didn't say any more, but we've always been unusually communicative in a reserved way, and I understood that he meant a great deal more than that.", difficulty: 4, levelLabel: 'B2' }, { id: 'p4', text: "In consequence, I'm inclined to reserve all judgments, a habit that has opened up many curious natures to me and also made me the victim of not a few veteran bores.", difficulty: 6, levelLabel: 'C1' }, { id: 'p5', text: "The abnormal mind is quick to detect and attach itself to this quality when it appears in a normal person, and so in college I was unjustly accused of being a politician, because I was privy to the secret griefs of wild, unknown men.", difficulty: 7, levelLabel: 'C1' }, { id: 'p6', text: "Most of the confidences were unsought — frequently I have feigned sleep, preoccupation, or a hostile levity when I realized by some unmistakable sign that an intimate revelation was quivering on the horizon.", difficulty: 8, levelLabel: 'C2' } ] } }; const LIBRARY = { gatsby: { id: 'gatsby', title: BOOK.title, author: BOOK.author, cover: BOOK.cover, type: 'builtin', chapters: BOOK.chapters, content: CHAPTER_CONTENT } }; let customBookIdCounter = 0; const SUPPORT_TYPES = { NONE: 'none', HINT: 'hint', DETAILED: 'detailed', SIMPLIFIED: 'simplified' }; // --- Support Policy Logic --- function getAvailableSupportTypes(difficulty, userLevelNum) { const gap = difficulty - userLevelNum; if (gap <= 0) return [SUPPORT_TYPES.NONE]; if (gap === 1) return [SUPPORT_TYPES.HINT]; if (gap === 2) return [SUPPORT_TYPES.HINT, SUPPORT_TYPES.DETAILED]; return [SUPPORT_TYPES.HINT, SUPPORT_TYPES.DETAILED, SUPPORT_TYPES.SIMPLIFIED]; } function getSupportLabel(type) { switch(type) { case SUPPORT_TYPES.NONE: return 'Не требуется'; case SUPPORT_TYPES.HINT: return 'Короткая подсказка'; case SUPPORT_TYPES.DETAILED: return 'Развёрнутое объяснение'; case SUPPORT_TYPES.SIMPLIFIED: return 'Упрощённая версия'; default: return ''; } } // --- Mock LLM Responses --- function generateResponse(type, paragraph) { const { id } = paragraph; const responses = { p3: { hint: "Рассказчик говорит, что с отцом у них была особая связь: мало слов, но много понимания без слов.", detailed: "В этом абзаце раскрывается характер отношений с отцом. Фраза 'unusually communicative in a reserved way' — оксюморон, показывающий, что они понимали друг друга без лишних слов. Рассказчик догадывается о скрытом смысле совета отца.", simplified: "He didn't say more, but we always understood each other without many words. I knew he meant much more than he said." }, p4: { hint: "Главный герой привык не судить людей. Это помогает ему узнать интересных людей, но и втягивает в общение с занудами.", detailed: "Автор иронично описывает последствие отцовского совета. 'Reserve all judgments' — воздержание от осуждения. 'Curious natures' — здесь 'curious' значит 'странные', а не 'любопытные'. 'Veteran bores' — заезженные, хронические зануды. Рассказчик понимает цену своей открытости.", simplified: "Because of my father's advice, I try not to judge people. This has let me meet many strange and interesting people, but it has also trapped me with some very boring ones." }, p5: { hint: "В колледже его считали политиком, потому что чужие люди доверяли ему свои тайны.", detailed: "Здесь описывается социальный эффект: люди с психологическими проблемами ('abnormal mind') чувствуют, когда обычный человек готов слушать. Рассказчик стал 'жертвой' своего качества — к нему тянулись незнакомцы с секретами. Фраза 'privy to the secret griefs' означает 'посвящённый в тайные горести'. Обвинение в политиканстве иронично: он просто умел слушать.", simplified: "Strange people quickly notice a good listener. So in college, others wrongly thought I was a politician, because unknown men told me their secret sorrows." }, p6: { hint: "Он часто притворялся спящим или занятым, чтобы избежать нежелательных исповедей.", detailed: "Этот абзац — кульминация темы нежелательного доверия. 'Confidences' — доверительные признания. 'Unsought' — непрошенные. Рассказчик прибегает к маскировке: 'feigned sleep' (притворялся спящим), 'preoccupation' (занятость), 'hostile levity' (враждебная легкомысленность). 'Unmistakable sign' — явный признак. 'Quivering on the horizon' — поэтический образ приближающейся исповеди.", simplified: "Most of these secret talks were unwanted. I often pretended to be asleep, busy, or joking, when I saw that someone was about to tell me their personal secrets." } }; if (responses[id] && responses[id][type]) { return responses[id][type]; } if (type === 'hint') return "Этот фрагмент содержит сложную лексику. Обратите внимание на контекст предложения."; if (type === 'detailed') return "В данном абзаце автор использует сложные конструкции и идиоматические выражения. Рекомендуется разобрать предложение по частям и определить подлежащее и сказуемое в каждой клаузе."; if (type === 'simplified') return "This paragraph describes a situation in simpler terms for better understanding."; return ""; } // --- State --- let state = { currentBookId: 'gatsby', currentChapterId: 0, selectedParagraphId: null, activeSupportType: null, helpOpen: false, mobileMenuOpen: false, uploadModalOpen: false }; // --- Init --- function init() { if (typeof pdfjsLib !== 'undefined') { pdfjsLib.GlobalWorkerOptions.workerSrc = 'https://cdnjs.cloudflare.com/ajax/libs/pdf.js/3.11.174/pdf.worker.min.js'; } renderSidebar(); renderHeader(); renderContent(); renderHelpPanels(); renderLibrary(); lucide.createIcons(); document.getElementById('mobile-menu-btn').addEventListener('click', toggleMobileMenu); document.getElementById('close-sidebar-btn').addEventListener('click', toggleMobileMenu); document.getElementById('close-help-btn').addEventListener('click', closeHelp); document.getElementById('mobile-close-help-btn').addEventListener('click', closeHelp); document.getElementById('overlay').addEventListener('click', () => { state.mobileMenuOpen = false; closeHelp(); renderMobileMenu(); }); // Upload modal listeners const dropZone = document.getElementById('drop-zone'); const fileInput = document.getElementById('file-input'); if (dropZone && fileInput) { dropZone.addEventListener('click', () => fileInput.click()); dropZone.addEventListener('dragover', (e) => { e.preventDefault(); dropZone.classList.add('border-blue-400', 'bg-blue-50/50'); }); dropZone.addEventListener('dragleave', () => { dropZone.classList.remove('border-blue-400', 'bg-blue-50/50'); }); dropZone.addEventListener('drop', (e) => { e.preventDefault(); dropZone.classList.remove('border-blue-400', 'bg-blue-50/50'); if (e.dataTransfer.files.length > 0) { handleFileSelect(e.dataTransfer.files[0]); } }); } } // --- Rendering --- function renderHeader() { const counter = document.getElementById('intervention-counter'); if (counter) { counter.textContent = `${USER.interventionsLeft}/${USER.maxInterventions}`; const colorClass = USER.interventionsLeft === 0 ? 'bg-red-100 text-red-700' : USER.interventionsLeft <= 2 ? 'bg-amber-100 text-amber-700' : 'bg-emerald-100 text-emerald-700'; counter.className = `px-2.5 py-1 rounded-full text-xs font-semibold ${colorClass}`; } const headerTitle = document.getElementById('header-book-title'); if (headerTitle) { const book = getCurrentBook(); headerTitle.textContent = book.title; } } function getCurrentBook() { return LIBRARY[state.currentBookId] || LIBRARY['gatsby']; } function renderSidebar() { const book = getCurrentBook(); const chapterList = document.getElementById('chapter-list'); if (!chapterList) return; chapterList.innerHTML = book.chapters.map(ch => ` `).join(''); // Update sidebar book info const cover = document.getElementById('sidebar-cover'); const title = document.getElementById('sidebar-title'); const author = document.getElementById('sidebar-author'); const badge = document.getElementById('sidebar-badge'); if (cover) cover.src = book.cover || 'http://static.photos/minimal/200x200/1'; if (title) title.textContent = book.title; if (author) author.textContent = book.author; if (badge) { badge.textContent = book.type === 'builtin' ? 'Classic' : (book.type === 'pdf' ? 'PDF' : 'TXT'); badge.className = `inline-flex mt-2 items-center px-2 py-0.5 rounded text-[10px] font-bold uppercase tracking-wider ${book.type === 'builtin' ? 'bg-blue-50 text-blue-700' : 'bg-slate-100 text-slate-600'}`; } } function renderLibrary() { const list = document.getElementById('library-list'); if (!list) return; list.innerHTML = Object.values(LIBRARY).map(book => ` `).join(''); } function selectBook(bookId) { if (!LIBRARY[bookId]) return; state.currentBookId = bookId; state.currentChapterId = 0; state.selectedParagraphId = null; state.activeSupportType = null; state.helpOpen = false; renderLibrary(); renderSidebar(); renderContent(); renderHelpPanels(); lucide.createIcons(); if (window.innerWidth < 1024) { state.mobileMenuOpen = false; renderMobileMenu(); } } function selectChapter(id) { state.currentChapterId = id; state.selectedParagraphId = null; state.activeSupportType = null; state.helpOpen = false; renderSidebar(); renderContent(); renderHelpPanels(); lucide.createIcons(); if (window.innerWidth < 1024) { state.mobileMenuOpen = false; renderMobileMenu(); } } let currentFontSize = 18; function changeFontSize(delta) { currentFontSize = Math.min(Math.max(currentFontSize + delta * 2, 14), 24); document.querySelectorAll('.reading-text').forEach(el => { el.style.fontSize = currentFontSize + 'px'; el.style.lineHeight = '1.75'; }); } function renderContent() { const book = getCurrentBook(); const chapter = book.content[state.currentChapterId] || book.content[0] || Object.values(book.content)[0]; if (!chapter) return; const titleEl = document.getElementById('chapter-title'); if (titleEl) titleEl.textContent = chapter.title; const bookTitleEl = document.getElementById('content-book-title'); if (bookTitleEl) bookTitleEl.textContent = book.title; const container = document.getElementById('reading-container'); if (!container) return; container.innerHTML = chapter.paragraphs.map(p => { const gap = (p.difficulty || 3) - USER.levelNum; let badgeColor = 'bg-emerald-100 text-emerald-700'; if (gap === 1) badgeColor = 'bg-amber-100 text-amber-700'; if (gap >= 2) badgeColor = 'bg-red-100 text-red-700'; const isSelected = state.selectedParagraphId === p.id; return `

${p.text}

${p.levelLabel}
${isSelected ? `
Открыть панель помощи
` : ''}
`; }).join(''); } function selectParagraph(pid) { if (state.selectedParagraphId === pid && !state.helpOpen) { openHelp(); return; } state.selectedParagraphId = pid; state.activeSupportType = null; openHelp(); renderContent(); renderHelpPanels(); lucide.createIcons(); } function openHelp() { state.helpOpen = true; const panel = document.getElementById('help-panel'); const mobileSheet = document.getElementById('mobile-help-sheet'); const overlay = document.getElementById('overlay'); if (window.innerWidth >= 1024) { panel.classList.remove('hidden'); panel.classList.add('block'); } else { mobileSheet.classList.remove('translate-y-full'); overlay.classList.remove('hidden'); } } function closeHelp() { state.helpOpen = false; state.selectedParagraphId = null; state.activeSupportType = null; const panel = document.getElementById('help-panel'); const mobileSheet = document.getElementById('mobile-help-sheet'); const overlay = document.getElementById('overlay'); panel.classList.add('hidden'); panel.classList.remove('block'); mobileSheet.classList.add('translate-y-full'); if (!state.mobileMenuOpen) overlay.classList.add('hidden'); renderContent(); renderHelpPanels(); } function renderHelpPanels() { const book = getCurrentBook(); const chapter = book.content[state.currentChapterId] || book.content[0] || Object.values(book.content)[0]; if (!chapter) return; const p = chapter.paragraphs.find(x => x.id === state.selectedParagraphId); const desktopContent = document.getElementById('help-content-desktop'); const mobileContent = document.getElementById('help-content-mobile'); const html = p ? buildHelpHtml(p) : buildEmptyHelpHtml(); if (desktopContent) desktopContent.innerHTML = html; if (mobileContent) mobileContent.innerHTML = html; setTimeout(() => { document.querySelectorAll('.support-btn').forEach(btn => { btn.addEventListener('click', (e) => { const type = e.currentTarget.dataset.type; requestSupport(type, p); }); }); lucide.createIcons(); }, 0); } function buildEmptyHelpHtml() { return `

Выберите абзац для получения контекстной помощи

`; } function buildHelpHtml(p) { const types = getAvailableSupportTypes(p.difficulty, USER.levelNum); const gap = p.difficulty - USER.levelNum; let policyMessage = ''; let policyColor = ''; if (gap <= 0) { policyMessage = 'Этот фрагмент соответствует вашему уровню. Читайте смело!'; policyColor = 'text-emerald-600 bg-emerald-50 border-emerald-200'; } else if (gap === 1) { policyMessage = 'Небольшая сложность. Доступна короткая подсказка.'; policyColor = 'text-amber-600 bg-amber-50 border-amber-200'; } else { policyMessage = 'Фрагмент значительно сложнее вашего уровня. Рекомендуется помощь.'; policyColor = 'text-red-600 bg-red-50 border-red-200'; } const isNone = types.includes(SUPPORT_TYPES.NONE) && types.length === 1; let buttonsHtml = ''; if (!isNone) { buttonsHtml = `
`; if (types.includes(SUPPORT_TYPES.HINT)) { buttonsHtml += createSupportButton(SUPPORT_TYPES.HINT, 'Короткая подсказка', 'lightbulb', 'bg-amber-50 hover:bg-amber-100 text-amber-800 border-amber-200'); } if (types.includes(SUPPORT_TYPES.DETAILED)) { buttonsHtml += createSupportButton(SUPPORT_TYPES.DETAILED, 'Развёрнутое объяснение', 'book-text', 'bg-blue-50 hover:bg-blue-100 text-blue-800 border-blue-200'); } if (types.includes(SUPPORT_TYPES.SIMPLIFIED)) { buttonsHtml += createSupportButton(SUPPORT_TYPES.SIMPLIFIED, 'Упрощённая версия', 'arrow-down-circle', 'bg-violet-50 hover:bg-violet-100 text-violet-800 border-violet-200'); } buttonsHtml += `
`; } let resultHtml = ''; if (state.activeSupportType) { const response = generateResponse(state.activeSupportType, p); const typeLabel = getSupportLabel(state.activeSupportType); const isSimplified = state.activeSupportType === SUPPORT_TYPES.SIMPLIFIED; resultHtml = `
${typeLabel} generated by LLM policy
${response}
`; } return `

Анализ фрагмента

Сложность: ${p.levelLabel} (${p.difficulty}/10)
Ваш уровень: ${USER.level} (${USER.levelNum}/10)
${policyMessage}
${isNone ? `
Помощь не требуется по правилам продукта
` : `

Доступная помощь

Осталось: ${USER.interventionsLeft}
${USER.interventionsLeft === 0 ? `
Лимит интервенций исчерпан. Продолжайте чтение самостоятельно или вернитесь позже.
` : buttonsHtml} `} ${resultHtml}

Политика приложения определяет тип помощи на основе разницы между сложностью фрагмента и вашим уровнем. LLM генерирует формулировку только для выбранного типа.

`; } function createSupportButton(type, label, icon, colorClasses) { const disabled = USER.interventionsLeft === 0 ? 'opacity-50 cursor-not-allowed' : 'cursor-pointer'; const active = state.activeSupportType === type ? 'ring-2 ring-offset-1 ring-blue-400' : ''; return ` `; } function requestSupport(type, paragraph) { if (USER.interventionsLeft <= 0 && type !== SUPPORT_TYPES.NONE) return; state.activeSupportType = type; if (type !== SUPPORT_TYPES.NONE) { USER.interventionsLeft--; renderHeader(); } renderHelpPanels(); } function toggleMobileMenu() { state.mobileMenuOpen = !state.mobileMenuOpen; renderMobileMenu(); } function renderMobileMenu() { const sidebar = document.getElementById('sidebar'); const overlay = document.getElementById('overlay'); if (state.mobileMenuOpen) { sidebar.classList.remove('-translate-x-full'); overlay.classList.remove('hidden'); } else { sidebar.classList.add('-translate-x-full'); if (!state.helpOpen) overlay.classList.add('hidden'); } } // --- Upload & PDF parsing --- function showUploadModal() { state.uploadModalOpen = true; const modal = document.getElementById('upload-modal'); const overlay = document.getElementById('upload-overlay'); const dialog = document.getElementById('upload-dialog'); if (!modal) return; modal.classList.remove('hidden'); setTimeout(() => { if (overlay) overlay.classList.remove('opacity-0'); if (dialog) { dialog.classList.remove('scale-95', 'opacity-0'); dialog.classList.add('scale-100', 'opacity-100'); } }, 10); lucide.createIcons(); } function hideUploadModal() { state.uploadModalOpen = false; const modal = document.getElementById('upload-modal'); const overlay = document.getElementById('upload-overlay'); const dialog = document.getElementById('upload-dialog'); if (overlay) overlay.classList.add('opacity-0'); if (dialog) { dialog.classList.remove('scale-100', 'opacity-100'); dialog.classList.add('scale-95', 'opacity-0'); } setTimeout(() => { if (modal) modal.classList.add('hidden'); }, 300); // Reset UI const loading = document.getElementById('upload-loading'); const error = document.getElementById('upload-error'); const fileInput = document.getElementById('file-input'); if (loading) loading.classList.add('hidden'); if (error) error.classList.add('hidden'); if (fileInput) fileInput.value = ''; } async function handleFileSelect(file) { if (!file) return; const isPDF = file.type === 'application/pdf' || file.name.endsWith('.pdf'); const isTXT = file.type === 'text/plain' || file.name.endsWith('.txt'); if (!isPDF && !isTXT) { showUploadError('Поддерживаются только PDF и TXT файлы'); return; } const loading = document.getElementById('upload-loading'); const filename = document.getElementById('upload-filename'); const status = document.getElementById('upload-status'); const progress = document.getElementById('upload-progress'); if (loading) loading.classList.remove('hidden'); if (filename) filename.textContent = file.name; if (status) status.textContent = 'Чтение файла...'; if (progress) progress.style.width = '10%'; try { const arrayBuffer = await file.arrayBuffer(); if (progress) progress.style.width = '40%'; let paragraphs = []; let title = file.name.replace(/\.(pdf|txt)$/i, ''); let author = 'Unknown Author'; if (isPDF) { if (typeof pdfjsLib === 'undefined') { throw new Error('PDF.js не загружен'); } if (progress) progress.style.width = '60%'; if (status) status.textContent = 'Извлечение текста из PDF...'; paragraphs = await parsePDF(arrayBuffer); } else { if (progress) progress.style.width = '60%'; const text = new TextDecoder('utf-8').decode(arrayBuffer); paragraphs = parseTXT(text); } if (progress) progress.style.width = '90%'; if (status) status.textContent = 'Создание книги...'; if (paragraphs.length === 0) { throw new Error('Не удалось извлечь текст из файла'); } // Estimate difficulty based on avg sentence length / word complexity (simple heuristic) paragraphs = paragraphs.map((p, idx) => { const words = p.split(/\s+/).length; const longWords = p.split(/\s+/).filter(w => w.length > 6).length; const ratio = words > 0 ? longWords / words : 0; let difficulty = 3; if (ratio > 0.15) difficulty = 5; if (ratio > 0.25) difficulty = 7; if (ratio > 0.35) difficulty = 8; // Map to CEFR labels let levelLabel = 'B1'; if (difficulty <= 2) levelLabel = 'A2'; else if (difficulty <= 4) levelLabel = 'B1'; else if (difficulty <= 6) levelLabel = 'B2'; else if (difficulty <= 8) levelLabel = 'C1'; else levelLabel = 'C2'; return { id: 'p' + (idx + 1), text: p, difficulty, levelLabel }; }); customBookIdCounter++; const bookId = 'custom_' + customBookIdCounter; const chapters = [{ id: 0, title: 'Глава 1' }]; const content = { 0: { title: 'Глава 1', paragraphs } }; LIBRARY[bookId] = { id: bookId, title, author, cover: 'http://static.photos/minimal/320x240/1', type: isPDF ? 'pdf' : 'txt', chapters, content }; if (progress) progress.style.width = '100%'; setTimeout(() => { hideUploadModal(); selectBook(bookId); }, 400); } catch (err) { console.error(err); showUploadError(err.message || 'Ошибка обработки файла'); } } function showUploadError(msg) { const loading = document.getElementById('upload-loading'); const error = document.getElementById('upload-error'); const errorMsg = document.getElementById('upload-error-msg'); if (loading) loading.classList.add('hidden'); if (error) error.classList.remove('hidden'); if (errorMsg) errorMsg.textContent = msg; lucide.createIcons(); } async function parsePDF(arrayBuffer) { const pdf = await pdfjsLib.getDocument({ data: arrayBuffer }).promise; const paragraphs = []; for (let i = 1; i <= pdf.numPages; i++) { const page = await pdf.getPage(i); const textContent = await page.getTextContent(); const items = textContent.items; // Group items by lines using transform[5] (y coordinate) const lines = []; let currentLine = []; let lastY = null; const threshold = 5; // pixels for (const item of items) { const y = item.transform[5]; if (lastY !== null && Math.abs(y - lastY) > threshold) { if (currentLine.length > 0) { lines.push(currentLine.join(' ').trim()); currentLine = []; } } currentLine.push(item.str); lastY = y; } if (currentLine.length > 0) lines.push(currentLine.join(' ').trim()); // Merge lines into paragraphs based on empty-ish lines or indentation let currentParagraph = []; for (const line of lines) { if (!line) continue; currentParagraph.push(line); if (/[.!?]$/.test(line) && line.length > 40) { paragraphs.push(currentParagraph.join(' ')); currentParagraph = []; } } if (currentParagraph.length > 0) { paragraphs.push(currentParagraph.join(' ')); } } // Clean up and filter very short fragments return paragraphs .map(p => p.replace(/\s+/g, ' ').trim()) .filter(p => p.length > 20); } function parseTXT(text) { // Split by double newlines or single newlines if lines are long enough const blocks = text.split(/\n\s*\n/).map(b => b.replace(/\n+/g, ' ').trim()).filter(b => b.length > 10); if (blocks.length > 1) return blocks; // Fallback: split by sentences if no paragraph breaks return text .replace(/([.!?])\s+/g, "$1|") .split("|") .map(s => s.trim()) .filter(s => s.length > 20); } document.addEventListener('DOMContentLoaded', init);