feat(reader): remember reading position across refresh, add chapter progress bar, and plan PDF support

This commit is contained in:
2026-10-05 16:51:08 +03:00
parent fdc11ed9ea
commit 6ee67c0653
4 changed files with 231 additions and 16 deletions
+40 -5
View File
@@ -120,7 +120,42 @@
---
### 6. 🔌 Пул соединений HTTP (`httpx.AsyncClient` с Keep-Alive)
### 6. 📖 Запоминание позиции чтения и прогресс главы (Scroll position, Chapter Progress & Auto-restore)
- [x] **Индикатор прогресса текущей главы**:
- Тонкий неоновый прогресс-бар в шапке читалки (`reader-chapter-progress-bar`), плавно показывающий процент прочитанного в текущей главе.
- Процентный бейдж в центре тулбара читалки рядом с выбором главы (`reader-scroll-pct-badge`, например `42%`).
- [x] **Автоматическое сохранение позиции чтения**:
- Отслеживание скролла читалки в реальном времени (`handleReaderScroll`).
- Мгновенное сохранение в `localStorage` (`notes_book_{id}_pos`: номер главы, точные пиксели `scrollTop`, доля прогресса `fraction`).
- Фоновая отправка прогресса на бэкенд (`PUT /api/books/{id}/progress`) с дебаунсом 800 мс.
- Гарантированная фиксация позиции при закрытии/обновлении страницы через `beforeunload` + `navigator.sendBeacon`.
- [x] **Бесшовное восстановление чтения при перезагрузке страницы**:
- Сервис запоминает активный экран и ID открытой книги (`notes_active_book_id`).
- При обновлении страницы (`F5` или свайп на телефоне) приложение автоматически открывает читалку на той же книге, той же главе и восстанавливает точную позицию скролла вплоть до пикселя.
---
### 7. 📑 Поддержка чтения PDF (Cisco CCNA, O'Reilly & Tech Books с оглавлением и текстовым слоем)
- [ ] **Легковесный Pure-Python парсер (`pypdf`, Zero C-Dependency)**:
- Подключение `pypdf` (< 400 КБ, чистый Python, без раздувания Docker-образа и без системных библиотек `poppler-utils` / `mupdf`).
- [ ] **Извлечение оглавления и закладок PDF (`reader.outline`)**:
- Извлечение авторского оглавления (ToC / Bookmarks), стандартного для книг Cisco Press (CCNA Official Cert Guide), O'Reilly и Wiley.
- Разбивка книги на логические главы и разделы (`Part I`, `Chapter 1`, `Chapter 2`) точно по оглавлению автора.
- [ ] **Fallback-разбивка при отсутствии оглавления**:
- При отсутствии PDF-закладок — автоопределение заголовков через regex (`Chapter \d+`, `Глава \d+`) или группировка страниц порциями по ~12–15 страниц.
- [ ] **Очистка шума и колонтитулов**:
- Фильтрация повторяющихся верхних/нижних колонтитулов («CCNA 200-301 Official Cert Guide», «Page 45 of 900»).
- [ ] **Сохранение CLI/Console блоков**:
- Распознавание консольного вывода и команд сетевого оборудования (`Router# show ip interface brief`, `Switch(config)#`) и оборачивание в блоки кода Markdown для читалки с кнопкой «Копировать».
- [ ] **Защита от сканов без OCR (Scanned PDF Guard)**:
- Валидация наличия текстового слоя: если суммарный объём извлечённого текста < 100 слов, возврат информативной ошибки с предложением использовать текстовый PDF или OCR.
- [ ] **Интеграция в интерфейс читалки**:
- Разрешение загрузки `.pdf` в `<input type="file" accept=".epub,.txt,.md,.pdf">`.
- Обновление кнопки в библиотеке: `📁 Загрузить EPUB / PDF / TXT`.
---
### 8. 🔌 Пул соединений HTTP (`httpx.AsyncClient` с Keep-Alive)
- [ ] В [`app/dictionary.py`](file:///home/ai-projects/services/study.qpid.pro/app/dictionary.py) создать синглтон-клиент `get_http_client()` с пулом соединений:
```python
limits = httpx.Limits(max_keepalive_connections=10, max_connections=20)
@@ -130,7 +165,7 @@
---
### 7. 🗄️ Тюнинг SQLite PRAGMA и составных индексов
### 9. 🗄️ Тюнинг SQLite PRAGMA и составных индексов
- [ ] В [`app/database.py`](file:///home/ai-projects/services/study.qpid.pro/app/database.py):
- Вынести `PRAGMA journal_mode=WAL;` в `init_db()` (убрать избыточный вызов при каждом запросе).
- Включить параметры производительности памяти Linux:
@@ -143,13 +178,13 @@
---
### 8. ✂️ Де-блоатинг внешних парсеров (YAGNI)
### 10. ✂️ Де-блоатинг внешних парсеров (YAGNI)
- [ ] Удалить лишний сетевой опрос Datamuse (`fetch_datamuse`) — он дублирует определения и перегружает ответ нерелевантными рифмами.
- [ ] Упростить хрупкий regex-парсинг разметки Wikitext, опираясь на стабильные REST JSON эндпоинты.
---
### 9. 📚 Локальный оффлайн-словарь (99%+ покрытия со словоформами, SQLite 10–20 МБ)
### 11. 📚 Локальный оффлайн-словарь (99%+ покрытия со словоформами, SQLite 10–20 МБ)
- [ ] Создать в SQLite таблицу:
```sql
CREATE TABLE IF NOT EXISTS offline_dictionary (
@@ -171,7 +206,7 @@
---
### 10. 🧩 Модульность фронтенда на нативных ES-модулях (без Webpack/Vite)
### 12. 🧩 Модульность фронтенда на нативных ES-модулях (без Webpack/Vite)
- [ ] Перевести [`app/static/js/app.js`](file:///home/ai-projects/services/study.qpid.pro/app/static/js/app.js) на нативный браузерный синтаксис `<script type="module">`.
- [ ] Выделить модули с нативным `import/export`:
- `modules/reader.js` — читалку, блок-парсер и навигацию по главам.
+35
View File
@@ -3137,6 +3137,41 @@ body {
max-width: 240px;
}
.reader-progress-badge {
font-size: 11px;
font-weight: 700;
font-variant-numeric: tabular-nums;
color: var(--primary);
background: var(--primary-dim);
border: 1px solid rgba(56, 189, 248, 0.35);
padding: 3px 8px;
border-radius: var(--radius-full);
min-width: 40px;
text-align: center;
display: inline-block;
user-select: none;
line-height: 1.2;
}
.reader-chapter-progress-bar {
position: absolute;
left: 0;
right: 0;
bottom: -1px;
height: 3px;
background-color: rgba(255, 255, 255, 0.08);
overflow: hidden;
pointer-events: none;
}
.reader-chapter-progress-fill {
height: 100%;
width: 0%;
background: linear-gradient(90deg, #0284c7, #38bdf8);
box-shadow: 0 0 8px rgba(56, 189, 248, 0.5);
transition: width 0.12s cubic-bezier(0.16, 1, 0.3, 1);
}
.reader-toolbar-right {
display: flex;
align-items: center;
+7 -2
View File
@@ -5,7 +5,7 @@
<meta name="viewport" content="width=device-width, initial-scale=1.0, maximum-scale=1.0, user-scalable=no, viewport-fit=cover">
<title>Notes — Персональный тренажер и словарь английского языка</title>
<meta name="description" content="Защищённый персональный тренажёр и словарь английского языка с интервальными повторениями SRS SM-2, контекстным поиском и озвучкой">
<link rel="stylesheet" href="/static/css/style.css?v=3.3">
<link rel="stylesheet" href="/static/css/style.css?v=3.4">
<!-- PWA meta and icons -->
<link rel="manifest" href="/manifest.json">
@@ -564,6 +564,7 @@
<button id="reader-prev-ch-btn" class="btn btn-xs btn-outline" title="Предыдущая глава">◀</button>
<select id="reader-chapter-select" class="reader-select"></select>
<button id="reader-next-ch-btn" class="btn btn-xs btn-outline" title="Следующая глава">▶</button>
<span id="reader-scroll-pct-badge" class="reader-progress-badge" title="Прогресс чтения главы">0%</span>
</div>
<div class="reader-toolbar-right">
@@ -574,6 +575,10 @@
<button id="reader-toggle-highlight-btn" class="btn btn-xs btn-outline" title="Вкл/Выкл подсветку изучаемых слов">✨ Подсветка</button>
<button id="reader-train-btn" class="btn btn-xs btn-trainer" title="Тренировать слова из этой книги">🎓 Слова книги</button>
</div>
<div id="reader-chapter-progress-bar" class="reader-chapter-progress-bar">
<div id="reader-chapter-progress-fill" class="reader-chapter-progress-fill" style="width: 0%;"></div>
</div>
</header>
<!-- Reading Container -->
@@ -1051,7 +1056,7 @@
<!-- Audio Element for native streaming -->
<audio id="global-audio-player" preload="none"></audio>
<script src="/static/js/app.js?v=3.3"></script>
<script src="/static/js/app.js?v=3.4"></script>
</body>
</html>
+149 -9
View File
@@ -118,6 +118,9 @@ document.addEventListener('DOMContentLoaded', () => {
const readerTrainBtn = document.getElementById('reader-train-btn');
const readerContentBody = document.getElementById('reader-content-body');
const readerScrollArea = document.getElementById('reader-scroll-area');
const readerChapterProgressBar = document.getElementById('reader-chapter-progress-bar');
const readerChapterProgressFill = document.getElementById('reader-chapter-progress-fill');
const readerScrollPctBadge = document.getElementById('reader-scroll-pct-badge');
const readerWordPopup = document.getElementById('reader-word-popup');
const popupTerm = document.getElementById('popup-term');
@@ -392,7 +395,23 @@ document.addEventListener('DOMContentLoaded', () => {
const data = await resp.json();
currentUser = data.user;
showApp();
loadInitialData();
await loadInitialData();
// Restore last active view and reading session if page was refreshed
try {
const lastView = localStorage.getItem('notes_active_view');
const lastBookId = localStorage.getItem('notes_active_book_id');
if (lastView === 'reader-view') {
openReaderView();
if (lastBookId) {
openBook(parseInt(lastBookId, 10));
}
} else if (lastView === 'srs-view') {
openSrsView();
}
} catch (e) {
console.error('State restore error:', e);
}
} else {
showLogin();
}
@@ -1014,6 +1033,7 @@ document.addEventListener('DOMContentLoaded', () => {
if (readerView) readerView.classList.add('hidden');
dictionaryView.classList.remove('hidden');
updateMobileActiveTab('dict');
try { localStorage.setItem('notes_active_view', 'dictionary-view'); } catch (e) {}
loadInitialData();
}
@@ -1022,6 +1042,7 @@ document.addEventListener('DOMContentLoaded', () => {
if (readerView) readerView.classList.add('hidden');
srsView.classList.remove('hidden');
updateMobileActiveTab('srs');
try { localStorage.setItem('notes_active_view', 'srs-view'); } catch (e) {}
startSrsTrainingSession(false, tagFilter);
}
@@ -1030,6 +1051,7 @@ document.addEventListener('DOMContentLoaded', () => {
if (readerView) readerView.classList.add('hidden');
dictionaryView.classList.remove('hidden');
updateMobileActiveTab('dict');
try { localStorage.setItem('notes_active_view', 'dictionary-view'); } catch (e) {}
loadInitialData();
}
@@ -1038,6 +1060,7 @@ document.addEventListener('DOMContentLoaded', () => {
srsView.classList.add('hidden');
if (readerView) readerView.classList.remove('hidden');
updateMobileActiveTab('reader');
try { localStorage.setItem('notes_active_view', 'reader-view'); } catch (e) {}
loadBookshelf();
}
@@ -1990,7 +2013,25 @@ document.addEventListener('DOMContentLoaded', () => {
const resp = await fetch(`/api/books/${bookId}`);
if (!resp.ok) return alert('Не удалось открыть книгу');
currentBook = await resp.json();
currentChapterIndex = currentBook.current_chapter || 0;
// Load saved reading position from localStorage or server
let targetChapter = currentBook.current_chapter || 0;
let targetScrollTop = null;
let targetFraction = currentBook.current_position || 0;
try {
const raw = localStorage.getItem(`notes_book_${bookId}_pos`);
if (raw) {
const parsed = JSON.parse(raw);
if (parsed && typeof parsed.chapter === 'number') {
targetChapter = parsed.chapter;
targetScrollTop = parsed.scrollTop;
targetFraction = parsed.fraction;
}
}
} catch (e) {}
currentChapterIndex = targetChapter;
readerBookTitle.textContent = currentBook.title;
readerBookAuthor.textContent = currentBook.author || '';
@@ -2009,13 +2050,18 @@ document.addEventListener('DOMContentLoaded', () => {
readerInterface.classList.remove('hidden');
applyReaderSettings();
renderChapter(currentChapterIndex);
try {
localStorage.setItem('notes_active_book_id', bookId);
localStorage.setItem('notes_active_view', 'reader-view');
} catch (e) {}
renderChapter(currentChapterIndex, targetScrollTop, targetFraction);
} catch (e) {
console.error('Error opening book:', e);
}
}
function renderChapter(index) {
function renderChapter(index, restoreScrollTop = null, restoreFraction = null) {
if (!currentBook || !currentBook.chapters) return;
currentChapterIndex = Math.max(0, Math.min(index, currentBook.chapters.length - 1));
readerChapterSelect.value = currentChapterIndex;
@@ -2151,13 +2197,30 @@ document.addEventListener('DOMContentLoaded', () => {
}
});
if (readerScrollArea) readerScrollArea.scrollTop = 0;
function applyScroll() {
if (!readerScrollArea) return;
if (restoreScrollTop !== null && restoreScrollTop > 0) {
readerScrollArea.scrollTop = restoreScrollTop;
} else if (restoreFraction !== null && restoreFraction > 0) {
const maxScroll = Math.max(0, readerScrollArea.scrollHeight - readerScrollArea.clientHeight);
readerScrollArea.scrollTop = Math.round(maxScroll * restoreFraction);
} else {
readerScrollArea.scrollTop = 0;
}
updateReaderProgressBar();
}
requestAnimationFrame(() => {
applyScroll();
setTimeout(applyScroll, 100);
});
// Save progress to server
const posToSave = (restoreFraction !== null && restoreFraction > 0) ? restoreFraction : 0;
fetch(`/api/books/${currentBook.id}/progress`, {
method: 'PUT',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({ current_chapter: currentChapterIndex, current_position: 0 }),
body: JSON.stringify({ current_chapter: currentChapterIndex, current_position: posToSave }),
}).catch(err => console.log('Progress save error:', err));
}
@@ -2820,20 +2883,20 @@ document.addEventListener('DOMContentLoaded', () => {
// Chapter Navigation & Reader Toolbar
if (readerChapterSelect) {
readerChapterSelect.addEventListener('change', () => {
renderChapter(parseInt(readerChapterSelect.value, 10));
renderChapter(parseInt(readerChapterSelect.value, 10), 0, 0);
});
}
if (readerPrevChBtn) {
readerPrevChBtn.addEventListener('click', () => {
if (currentChapterIndex > 0) renderChapter(currentChapterIndex - 1);
if (currentChapterIndex > 0) renderChapter(currentChapterIndex - 1, 0, 0);
});
}
if (readerNextChBtn) {
readerNextChBtn.addEventListener('click', () => {
if (currentBook && currentChapterIndex < currentBook.chapters.length - 1) {
renderChapter(currentChapterIndex + 1);
renderChapter(currentChapterIndex + 1, 0, 0);
}
});
}
@@ -2842,10 +2905,87 @@ document.addEventListener('DOMContentLoaded', () => {
readerBackBtn.addEventListener('click', () => {
readerInterface.classList.add('hidden');
bookshelfContainer.classList.remove('hidden');
try { localStorage.removeItem('notes_active_book_id'); } catch (e) {}
loadBookshelf();
});
}
// Scroll Position Tracking & Real-Time Chapter Progress
let readerScrollSaveTimer = null;
function getReaderScrollMetrics() {
if (!readerScrollArea) return { scrollTop: 0, maxScroll: 0, pct: 0, fraction: 0 };
const scrollTop = readerScrollArea.scrollTop;
const maxScroll = Math.max(0, readerScrollArea.scrollHeight - readerScrollArea.clientHeight);
const fraction = maxScroll > 0 ? Math.min(1.0, Math.max(0, scrollTop / maxScroll)) : 0;
const pct = Math.min(100, Math.max(0, Math.round(fraction * 100)));
return { scrollTop, maxScroll, pct, fraction };
}
function updateReaderProgressBar() {
const { pct } = getReaderScrollMetrics();
if (readerChapterProgressFill) {
readerChapterProgressFill.style.width = `${pct}%`;
}
if (readerScrollPctBadge) {
readerScrollPctBadge.textContent = `${pct}%`;
}
}
function handleReaderScroll() {
if (!currentBook || !readerScrollArea) return;
updateReaderProgressBar();
const { scrollTop, fraction } = getReaderScrollMetrics();
// 1. Instant local persistence
try {
const key = `notes_book_${currentBook.id}_pos`;
localStorage.setItem(key, JSON.stringify({
chapter: currentChapterIndex,
scrollTop: scrollTop,
fraction: fraction,
savedAt: Date.now()
}));
localStorage.setItem('notes_active_book_id', currentBook.id);
localStorage.setItem('notes_active_view', 'reader-view');
} catch (e) {}
// 2. Debounced server sync (every 800ms)
clearTimeout(readerScrollSaveTimer);
readerScrollSaveTimer = setTimeout(() => {
if (!currentBook) return;
fetch(`/api/books/${currentBook.id}/progress`, {
method: 'PUT',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({ current_chapter: currentChapterIndex, current_position: fraction }),
}).catch(err => console.log('Progress save error:', err));
}, 800);
}
if (readerScrollArea) {
readerScrollArea.addEventListener('scroll', handleReaderScroll, { passive: true });
}
window.addEventListener('beforeunload', () => {
if (currentBook && readerScrollArea) {
const { scrollTop, fraction } = getReaderScrollMetrics();
try {
localStorage.setItem(`notes_book_${currentBook.id}_pos`, JSON.stringify({
chapter: currentChapterIndex,
scrollTop: scrollTop,
fraction: fraction,
savedAt: Date.now()
}));
localStorage.setItem('notes_active_book_id', currentBook.id);
} catch (e) {}
if (navigator.sendBeacon) {
const blob = new Blob([JSON.stringify({ current_chapter: currentChapterIndex, current_position: fraction })], { type: 'application/json' });
navigator.sendBeacon(`/api/books/${currentBook.id}/progress`, blob);
}
}
});
function loadSavedReaderSettings() {
try {
const saved = localStorage.getItem('notes_reader_settings');