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

This commit is contained in:
Antigravity committed 2026-10-05 16:51:08 +03:00
1 parent fdc11ed9ea
commit 6ee67c0653
4 files changed
+231 -16

No files matched your search

+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');