Spaces:
Running
Running
File size: 31,757 Bytes
d7afd1e 6a60c40 d7afd1e 6a60c40 d7afd1e 6a60c40 d7afd1e 6a60c40 d7afd1e 6a60c40 d7afd1e 6a60c40 d7afd1e 6a60c40 d7afd1e 6a60c40 d7afd1e 6a60c40 d7afd1e 6a60c40 d7afd1e 6a60c40 d7afd1e 6a60c40 d7afd1e 6a60c40 d7afd1e 6a60c40 d7afd1e 6a60c40 d7afd1e | 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 683 684 685 686 687 688 689 690 691 692 693 694 695 696 697 698 699 700 701 702 703 704 705 706 707 708 709 710 711 712 713 714 715 716 717 718 719 720 721 722 723 724 725 726 727 728 729 730 731 732 733 734 735 736 737 738 739 740 741 742 743 744 745 746 747 748 749 750 751 752 753 754 755 756 757 758 759 760 761 762 763 764 765 766 767 768 769 770 771 772 773 774 775 776 777 778 779 780 781 782 783 784 | // --- 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 => `
<button onclick="selectChapter(${ch.id})"
class="w-full text-left px-4 py-3 rounded-lg text-sm font-medium transition-colors mb-1 ${state.currentChapterId === ch.id ? 'bg-slate-100 text-slate-900 border-l-4 border-blue-600' : 'text-slate-600 hover:bg-slate-50'}">
${ch.title}
</button>
`).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 => `
<button onclick="selectBook('${book.id}')"
class="w-full text-left px-3 py-2.5 rounded-lg text-sm font-medium transition-colors mb-1 flex items-center gap-3 ${state.currentBookId === book.id ? 'bg-blue-50 text-blue-900 ring-1 ring-blue-200' : 'text-slate-600 hover:bg-slate-50'}">
<img src="${book.cover || 'http://static.photos/minimal/200x200/1'}" class="w-8 h-10 object-cover rounded border border-slate-200 shrink-0" alt="">
<div class="min-w-0">
<p class="truncate font-medium">${book.title}</p>
<p class="text-xs text-slate-500 truncate">${book.author}</p>
</div>
</button>
`).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 `
<div
onclick="selectParagraph('${p.id}')"
class="group relative pl-4 pr-2 py-3 rounded-xl transition-all cursor-pointer mb-2 ${isSelected ? 'bg-blue-50 ring-1 ring-blue-400' : 'hover:bg-white/60'}"
>
<div class="absolute left-0 top-3 bottom-3 w-1 rounded-full ${isSelected ? 'bg-blue-500' : 'bg-transparent group-hover:bg-slate-200'}"></div>
<div class="flex items-start gap-3">
<p class="reading-text flex-1 text-slate-800 leading-relaxed text-lg">
${p.text}
</p>
<span class="mt-1 inline-flex items-center px-2 py-0.5 rounded text-xs font-bold ${badgeColor} select-none shrink-0">
${p.levelLabel}
</span>
</div>
${isSelected ? `
<div class="mt-3 flex items-center gap-2 lg:hidden">
<span class="text-xs text-blue-600 font-medium">Открыть панель помощи</span>
<i data-lucide="arrow-up" class="w-3 h-3 text-blue-600"></i>
</div>
` : ''}
</div>
`;
}).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 `
<div class="flex flex-col items-center justify-center h-full text-center p-6 text-slate-400 min-h-[300px]">
<i data-lucide="book-open" class="w-12 h-12 mb-3 opacity-50"></i>
<p class="text-sm">Выберите абзац для получения контекстной помощи</p>
</div>
`;
}
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 = `<div class="grid gap-2 mb-4">`;
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 += `</div>`;
}
let resultHtml = '';
if (state.activeSupportType) {
const response = generateResponse(state.activeSupportType, p);
const typeLabel = getSupportLabel(state.activeSupportType);
const isSimplified = state.activeSupportType === SUPPORT_TYPES.SIMPLIFIED;
resultHtml = `
<div class="mt-4 rounded-xl border border-slate-200 bg-white p-4 shadow-sm animate-fade-in">
<div class="flex items-center gap-2 mb-2">
<span class="text-xs font-bold uppercase tracking-wider text-slate-500">${typeLabel}</span>
<span class="ml-auto text-[10px] text-slate-400">generated by LLM policy</span>
</div>
<div class="text-sm ${isSimplified ? 'reading-text text-slate-800' : 'text-slate-700 leading-relaxed'}">
${response}
</div>
</div>
`;
}
return `
<div class="p-5">
<div class="mb-4">
<h3 class="text-sm font-semibold text-slate-500 uppercase tracking-wider mb-2">Анализ фрагмента</h3>
<div class="flex items-center justify-between text-sm mb-2">
<span class="text-slate-600">Сложность:</span>
<span class="font-bold ${gap >= 2 ? 'text-red-600' : gap === 1 ? 'text-amber-600' : 'text-emerald-600'}">${p.levelLabel} (${p.difficulty}/10)</span>
</div>
<div class="flex items-center justify-between text-sm">
<span class="text-slate-600">Ваш уровень:</span>
<span class="font-bold text-slate-900">${USER.level} (${USER.levelNum}/10)</span>
</div>
</div>
<div class="rounded-lg border p-3 mb-5 text-xs font-medium ${policyColor}">
<div class="flex items-start gap-2">
<i data-lucide="info" class="w-4 h-4 shrink-0 mt-0.5"></i>
<span>${policyMessage}</span>
</div>
</div>
${isNone ? `
<div class="flex items-center gap-3 p-4 rounded-xl bg-emerald-50 border border-emerald-100 text-emerald-800">
<i data-lucide="check-circle-2" class="w-5 h-5"></i>
<span class="text-sm font-medium">Помощь не требуется по правилам продукта</span>
</div>
` : `
<div class="mb-3 flex items-center justify-between">
<h3 class="text-sm font-semibold text-slate-500 uppercase tracking-wider">Доступная помощь</h3>
<span class="text-[10px] text-slate-400">Осталось: ${USER.interventionsLeft}</span>
</div>
${USER.interventionsLeft === 0 ? `
<div class="p-3 rounded-lg bg-slate-50 border border-slate-200 text-xs text-slate-500 text-center">
Лимит интервенций исчерпан. Продолжайте чтение самостоятельно или вернитесь позже.
</div>
` : buttonsHtml}
`}
${resultHtml}
<div class="mt-6 pt-4 border-t border-slate-100">
<p class="text-[10px] text-slate-400 leading-tight">
Политика приложения определяет тип помощи на основе разницы между сложностью фрагмента и вашим уровнем. LLM генерирует формулировку только для выбранного типа.
</p>
</div>
</div>
`;
}
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 `
<button
data-type="${type}"
class="support-btn w-full flex items-center gap-3 px-4 py-3 rounded-lg border text-left text-sm font-medium transition-colors ${colorClasses} ${disabled} ${active}"
${USER.interventionsLeft === 0 ? 'disabled' : ''}
>
<i data-lucide="${icon}" class="w-4 h-4 shrink-0"></i>
<span>${label}</span>
${state.activeSupportType === type ? '<i data-lucide="check" class="w-4 h-4 ml-auto"></i>' : ''}
</button>
`;
}
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); |