qwen edit

This commit is contained in:
Курнат Андрей
2026-02-18 22:19:29 +03:00
parent 23a3563524
commit f50c918f10
3 changed files with 32 additions and 51 deletions

View File

@@ -1,4 +1,4 @@
<!DOCTYPE html> <!DOCTYPE html>
<html lang="en"> <html lang="en">
<head> <head>
<meta charset="UTF-8"> <meta charset="UTF-8">
@@ -154,12 +154,12 @@
rendition: null, // Объект отображения epub.js rendition: null, // Объект отображения epub.js
currentCfi: null, // Текущая позиция (идентификатор) в EPUB currentCfi: null, // Текущая позиция (идентификатор) в EPUB
totalPages: 0, // Всего страниц totalPages: 0, // Всего страниц
currentPage: 0, // Текущая страница
bookFormat: '', // epub или fb2 bookFormat: '', // epub или fb2
isBookLoaded: false, isBookLoaded: false,
fb2CurrentPage: 0, fb2CurrentPage: 0,
fb2TotalPages: 1, fb2TotalPages: 1,
toc: [] // Оглавление toc: [], // Оглавление
lastCfi: null // Последний CFI
}; };
// ========== УТИЛИТЫ ========== // ========== УТИЛИТЫ ==========
@@ -284,6 +284,7 @@
if (typeof ePub === 'undefined') { showError('epub.js not loaded!'); return; } if (typeof ePub === 'undefined') { showError('epub.js not loaded!'); return; }
state.book = ePub(arrayBuffer); // Создание объекта книги из данных state.book = ePub(arrayBuffer); // Создание объекта книги из данных
state.lastCfi = null;
els.fb2Content.style.display = 'none'; els.fb2Content.style.display = 'none';
els.bookContent.style.display = 'block'; els.bookContent.style.display = 'block';
@@ -322,15 +323,17 @@
debugLog("Загрузка из кэша..."); debugLog("Загрузка из кэша...");
state.book.locations.load(cachedLocations); state.book.locations.load(cachedLocations);
state.totalPages = state.book.locations.length(); state.totalPages = state.book.locations.length();
state.lastCfi = null;
sendMessage('bookReady', { totalPages: state.totalPages }); sendMessage('bookReady', { totalPages: state.totalPages });
} else { } else {
// Используем setTimeout, чтобы не блокировать поток отрисовки // Используем setTimeout, чтобы не блокировать поток отрисовки
const dynamicSize = calculateOptimalLocationSize(); const dynamicSize = calculateOptimalLocationSize();
// Запускаем генерацию с динамическим размером // Запускаем генерацию с динамическим размером
setTimeout(() => { setTimeout(() => {
state.book.locations.generate(dynamicSize).then(() => { state.book.locations.generate(1000).then(() => {
state.totalPages = state.book.locations.length(); state.totalPages = state.book.locations.length();
const locationsToSave = state.book.locations.save(); const locationsToSave = state.book.locations.save();
state.lastCfi = null;
// Отправляем в C#, чтобы сохранить на будущее // Отправляем в C#, чтобы сохранить на будущее
sendMessage('saveLocations', { locations: locationsToSave }); sendMessage('saveLocations', { locations: locationsToSave });
@@ -343,7 +346,13 @@
// Событие при смене страницы // Событие при смене страницы
state.rendition.on('relocated', location => { state.rendition.on('relocated', location => {
if (!location || !location.start) return; if (!location || !location.start) return;
state.currentCfi = location.start.cfi; const newCfi = location.start.cfi;
// Получаем процент прогресса
const progress = state.book.locations.percentageFromCfi(newCfi) || 0;
// Обновляем lastCfi
state.lastCfi = newCfi;
const chapterPage = location.start.displayed ? location.start.displayed.page : 1; const chapterPage = location.start.displayed ? location.start.displayed.page : 1;
const chapterTotal = location.start.displayed ? location.start.displayed.total : 1; const chapterTotal = location.start.displayed ? location.start.displayed.total : 1;
@@ -355,11 +364,12 @@
if (foundChapter) chapterName = foundChapter.label; if (foundChapter) chapterName = foundChapter.label;
// Отправка прогресса в приложение // Отправка прогресса в приложение
// currentPage теперь показывает процент (округлённый до целого)
sendMessage('progressUpdate', { sendMessage('progressUpdate', {
progress: state.book.locations.percentageFromCfi(state.currentCfi) || 0, progress: progress,
cfi: state.currentCfi, cfi: newCfi,
currentPage: location.start.location || 0, currentPage: Math.round(progress * 100), // Процент вместо номера страницы
totalPages: state.totalPages, totalPages: 100, // 100%
chapterCurrentPage: chapterPage, chapterCurrentPage: chapterPage,
chapterTotalPages: chapterTotal, chapterTotalPages: chapterTotal,
chapter: chapterName chapter: chapterName
@@ -387,6 +397,7 @@
xmlText = new TextDecoder(encMatch[1]).decode(bytes); xmlText = new TextDecoder(encMatch[1]).decode(bytes);
} }
state.lastCfi = null;
els.bookContent.style.display = 'none'; els.bookContent.style.display = 'none';
els.fb2Content.style.display = 'block'; els.fb2Content.style.display = 'block';
@@ -597,7 +608,9 @@
}; };
window.nextPage = function () { // Листать вперед window.nextPage = function () { // Листать вперед
if (state.bookFormat === 'epub' && state.rendition) state.rendition.next(); if (state.bookFormat === 'epub' && state.rendition) {
state.rendition.next();
}
else if (state.bookFormat === 'fb2' && state.fb2CurrentPage < state.fb2TotalPages - 1) { else if (state.bookFormat === 'fb2' && state.fb2CurrentPage < state.fb2TotalPages - 1) {
showFb2Page(state.fb2CurrentPage + 1); showFb2Page(state.fb2CurrentPage + 1);
updateFb2Progress(); updateFb2Progress();
@@ -605,7 +618,9 @@
}; };
window.prevPage = function () { // Листать назад window.prevPage = function () { // Листать назад
if (state.bookFormat === 'epub' && state.rendition) state.rendition.prev(); if (state.bookFormat === 'epub' && state.rendition) {
state.rendition.prev();
}
else if (state.bookFormat === 'fb2' && state.fb2CurrentPage > 0) { else if (state.bookFormat === 'fb2' && state.fb2CurrentPage > 0) {
showFb2Page(state.fb2CurrentPage - 1); showFb2Page(state.fb2CurrentPage - 1);
updateFb2Progress(); updateFb2Progress();

View File

@@ -46,17 +46,11 @@ public partial class ReaderViewModel : BaseViewModel
[ObservableProperty] [ObservableProperty]
private int _totalPages = 1; private int _totalPages = 1;
[ObservableProperty]
private bool _isLocationsLoaded;
// Это свойство будет обновляться автоматически при изменении любого из полей выше // Это свойство будет обновляться автоматически при изменении любого из полей выше
public string ChapterProgressText => $"{ChapterCurrentPage} из {ChapterTotalPages}"; public string ChapterProgressText => $"{ChapterCurrentPage} из {ChapterTotalPages}";
// Это свойство будет обновляться автоматически при изменении любого из полей выше // Это свойство показывает процент прогресса
// Пока страницы не посчитаны, показываем 0% public string ProgressText => $"{CurrentPage}%";
public string ProgressText => !_isLocationsLoaded || TotalPages <= 0
? "0%"
: $"{CurrentPage} из {TotalPages}";
// Чтобы ChapterProgressText уведомлял интерфейс, добавим частичные методы (особенность Toolkit) // Чтобы ChapterProgressText уведомлял интерфейс, добавим частичные методы (особенность Toolkit)
partial void OnChapterCurrentPageChanged(int value) => OnPropertyChanged(nameof(ChapterProgressText)); partial void OnChapterCurrentPageChanged(int value) => OnPropertyChanged(nameof(ChapterProgressText));
@@ -65,7 +59,6 @@ public partial class ReaderViewModel : BaseViewModel
// Чтобы ProgressText уведомлял интерфейс, добавим частичные методы (особенность Toolkit) // Чтобы ProgressText уведомлял интерфейс, добавим частичные методы (особенность Toolkit)
partial void OnCurrentPageChanged(int value) => OnPropertyChanged(nameof(ProgressText)); partial void OnCurrentPageChanged(int value) => OnPropertyChanged(nameof(ProgressText));
partial void OnTotalPagesChanged(int value) => OnPropertyChanged(nameof(ProgressText)); partial void OnTotalPagesChanged(int value) => OnPropertyChanged(nameof(ProgressText));
partial void OnIsLocationsLoadedChanged(bool value) => OnPropertyChanged(nameof(ProgressText));
public List<string> AvailableFonts { get; } = new() public List<string> AvailableFonts { get; } = new()
{ {
@@ -116,25 +109,6 @@ public partial class ReaderViewModel : BaseViewModel
return; return;
} }
// Проверяем, есть ли сохранённые локации (кэш)
var hasCachedLocations = !string.IsNullOrEmpty(Book.Locations);
// Если есть кэш - сразу показываем реальный прогресс
IsLocationsLoaded = hasCachedLocations;
// Если есть кэш - восстанавливаем прогресс из книги
if (hasCachedLocations)
{
CurrentPage = Book.CurrentPage > 0 ? Book.CurrentPage : 0;
TotalPages = Book.TotalPages > 0 ? Book.TotalPages : 0;
}
else
{
// Сбрасываем прогресс в 0% пока идёт подсчёт страниц
CurrentPage = 0;
TotalPages = 0;
}
var savedFontSize = await _settingsService.GetIntAsync(SettingsKeys.DefaultFontSize, Constants.Reader.DefaultFontSize); var savedFontSize = await _settingsService.GetIntAsync(SettingsKeys.DefaultFontSize, Constants.Reader.DefaultFontSize);
var savedFontFamily = await _settingsService.GetAsync(SettingsKeys.DefaultFontFamily, "serif"); var savedFontFamily = await _settingsService.GetAsync(SettingsKeys.DefaultFontFamily, "serif");
@@ -197,13 +171,6 @@ public partial class ReaderViewModel : BaseViewModel
} }
Book.Locations = locations; Book.Locations = locations;
await _databaseService.UpdateBookAsync(Book); await _databaseService.UpdateBookAsync(Book);
// Локации сохранены - теперь показываем реальный прогресс
// (если ещё не был показан из кэша)
if (!IsLocationsLoaded)
{
IsLocationsLoaded = true;
}
} }
public async Task SaveProgressAsync(double progress, string? cfi, string? chapter, int currentPage, int totalPages) public async Task SaveProgressAsync(double progress, string? cfi, string? chapter, int currentPage, int totalPages)

View File

@@ -16,7 +16,7 @@
<Shell.TitleView> <Shell.TitleView>
<Grid ColumnDefinitions="*,Auto" Padding="0,0,5,0"> <Grid ColumnDefinitions="*,Auto" Padding="0,0,5,0">
<Label Grid.Column="0" <Label Grid.Column="0"
Text="📚 My Library" Text="📚 Моя книжная полка"
FontSize="20" FontSize="20"
FontAttributes="Bold" FontAttributes="Bold"
VerticalOptions="Center" VerticalOptions="Center"
@@ -54,11 +54,11 @@
<Label Text="📖" <Label Text="📖"
FontSize="80" FontSize="80"
HorizontalOptions="Center" /> HorizontalOptions="Center" />
<Label Text="Your bookshelf is empty" <Label Text="Ваша книжная полка пуста"
FontSize="20" FontSize="20"
TextColor="#D7CCC8" TextColor="#D7CCC8"
HorizontalOptions="Center" /> HorizontalOptions="Center" />
<Label Text="Add books from your device or Calibre library" <Label Text="Добавьте книгу из Вашего устроиства или библиотеки Calibre"
FontSize="14" FontSize="14"
TextColor="#A1887F" TextColor="#A1887F"
HorizontalOptions="Center" HorizontalOptions="Center"
@@ -104,7 +104,6 @@
<!-- Cover Image --> <!-- Cover Image -->
<Frame Grid.Row="0" <Frame Grid.Row="0"
Padding="0" Padding="0"
CornerRadius="8,8,0,0"
IsClippedToBounds="True" IsClippedToBounds="True"
HasShadow="False" HasShadow="False"
BorderColor="Transparent"> BorderColor="Transparent">