feat: implement epub service, navigation service, and global error boundary with updated reader UI layouts

This commit is contained in:
2026-04-25 16:16:36 +02:00
parent f3e94c4f42
commit 59074a05a0
23 changed files with 726 additions and 157 deletions
@@ -0,0 +1,9 @@
using FluentResults;
using NexusReader.Application.Queries.Reader;
namespace NexusReader.Application.Abstractions.Services;
public interface IEpubService
{
Task<Result<ReaderPageViewModel>> GetEpubContentAsync(int chapterIndex);
}
@@ -2,4 +2,4 @@ using NexusReader.Application.Abstractions.Messaging;
namespace NexusReader.Application.Queries.Reader;
public record GetReaderPageQuery : IQuery<ReaderPageViewModel>;
public record GetReaderPageQuery(int ChapterIndex = 0) : IQuery<ReaderPageViewModel>;
@@ -1,20 +1,20 @@
using FluentResults;
using NexusReader.Application.Abstractions.Messaging;
using NexusReader.Application.Abstractions.Services;
namespace NexusReader.Application.Queries.Reader;
internal sealed class GetReaderPageQueryHandler : IQueryHandler<GetReaderPageQuery, ReaderPageViewModel>
{
public Task<Result<ReaderPageViewModel>> Handle(GetReaderPageQuery request, CancellationToken cancellationToken)
{
var blocks = new List<ContentBlock>
{
new TextSegmentBlock("renesans-intro", "Renesans, nazywany również odrodzeniem, to epoka w historii kultury europejskiej, która zapoczątkowała odejście od średniowiecznego teocentryzmu na rzecz humanizmu. Narodził się we Włoszech, a dokładnie we Florencji, w XV wieku, skąd promieniował na całą Europę."),
new TextSegmentBlock("medyceusze", "Głównym mecenasem sztuki i nauki we Florencji był potężny ród Medyceuszy. To dzięki ich wsparciu miasto stało się kolebką nowożytnej myśli, gromadząc wokół siebie najwybitniejsze umysły tamtych czasów."),
new AiActionTriggerBlock("da-vinci-ai", "Leonardo da Vinci był jednym z najważniejszych twórców tego okresu. Czy chciałbyś dowiedzieć się więcej o jego najważniejszych wynalazkach, czy wolisz sprawdzić swoją dotychczasową wiedzę?", new List<string> { "Pokaż więcej", "Rozwiąż quiz" }),
new TextSegmentBlock("leonardo-detail", "Człowiek renesansu, uosabiany właśnie przez Leonarda, był wszechstronnie wykształcony. Interesował się sztuką, inżynierią, anatomią i filozofią, stawiając jednostkę w centrum wszechświata.")
};
private readonly IEpubService _epubService;
return Task.FromResult(Result.Ok(new ReaderPageViewModel(blocks)));
public GetReaderPageQueryHandler(IEpubService epubService)
{
_epubService = epubService;
}
public async Task<Result<ReaderPageViewModel>> Handle(GetReaderPageQuery request, CancellationToken cancellationToken)
{
return await _epubService.GetEpubContentAsync(request.ChapterIndex);
}
}
@@ -1,7 +1,11 @@
using System.Text.Json.Serialization;
namespace NexusReader.Application.Queries.Reader;
[JsonDerivedType(typeof(TextSegmentBlock), "text")]
[JsonDerivedType(typeof(AiActionTriggerBlock), "trigger")]
public abstract record ContentBlock(string Id);
public record TextSegmentBlock(string Id, string Content) : ContentBlock(Id);
public record AiActionTriggerBlock(string Id, string Dialogue, List<string> ActionOptions) : ContentBlock(Id);
public record ReaderPageViewModel(List<ContentBlock> Blocks);
public record ReaderPageViewModel(List<ContentBlock> Blocks, int CurrentChapterIndex, int TotalChapters, string ChapterTitle);
@@ -9,6 +9,7 @@ public static class DependencyInjection
public static IServiceCollection AddInfrastructure(this IServiceCollection services)
{
services.AddTransient<IAiGenerateQuizService, FakeAiGenerateQuizService>();
services.AddTransient<IEpubService, EpubService>();
return services;
}
}
@@ -4,6 +4,10 @@
<ProjectReference Include="..\NexusReader.Application\NexusReader.Application.csproj" />
</ItemGroup>
<ItemGroup>
<PackageReference Include="VersOne.Epub" Version="3.3.6" />
</ItemGroup>
<PropertyGroup>
<TargetFramework>net10.0</TargetFramework>
<ImplicitUsings>enable</ImplicitUsings>
@@ -0,0 +1,149 @@
using System.Text;
using System.Text.RegularExpressions;
using FluentResults;
using NexusReader.Application.Abstractions.Services;
using NexusReader.Application.Queries.Reader;
using VersOne.Epub;
namespace NexusReader.Infrastructure.Services;
public class EpubService : IEpubService
{
private const string EpubPath = "wwwroot/assets/book.epub";
private const int WordThreshold = 1000;
public async Task<Result<ReaderPageViewModel>> GetEpubContentAsync(int chapterIndex)
{
try
{
// Path handling: Recursive search upwards to find the asset in development or production
var relativePath = Path.Combine("wwwroot", "assets", "book.epub");
string? fullPath = null;
var searchPaths = new List<string>();
var currentDir = new DirectoryInfo(AppDomain.CurrentDomain.BaseDirectory);
while (currentDir != null)
{
var checkPath1 = Path.Combine(currentDir.FullName, relativePath);
var checkPath2 = Path.Combine(currentDir.FullName, "src", "NexusReader.Web.New", relativePath);
searchPaths.Add(checkPath1);
if (File.Exists(checkPath1)) { fullPath = checkPath1; break; }
searchPaths.Add(checkPath2);
if (File.Exists(checkPath2)) { fullPath = checkPath2; break; }
currentDir = currentDir.Parent;
}
if (fullPath == null)
{
return Result.Fail($"EPUB file not found. Checked {searchPaths.Count} locations, including: {string.Join(", ", searchPaths.Take(3))}");
}
EpubBook book = await EpubReader.ReadBookAsync(fullPath);
var blocks = new List<ContentBlock>();
int totalWordCount = 0;
int blockCounter = 0;
if (book.ReadingOrder == null || !book.ReadingOrder.Any())
{
return Result.Fail("The EPUB has no readable content files in ReadingOrder.");
}
// Ensure index is within bounds
if (chapterIndex < 0 || chapterIndex >= book.ReadingOrder.Count)
{
chapterIndex = 0; // Default to first chapter
}
var chapter = book.ReadingOrder[chapterIndex];
var chapterTitle = chapter.FilePath ?? $"Chapter {chapterIndex + 1}";
var paragraphs = ExtractParagraphs(chapter.Content);
foreach (var p in paragraphs)
{
var sanitizedContent = SanitizeParagraph(p);
if (string.IsNullOrWhiteSpace(sanitizedContent)) continue;
// Requirement: Each paragraph mapped to its own TextSegmentBlock
blocks.Add(new TextSegmentBlock($"seg-{blockCounter++}", sanitizedContent));
int wordsInP = CountWords(sanitizedContent);
totalWordCount += wordsInP;
// Requirement: Smart Injection after 1000 words
if (totalWordCount >= WordThreshold)
{
blocks.Add(CreateAiTrigger($"trigger-{blockCounter++}"));
totalWordCount = 0;
}
}
// End of chapter section trigger
if (blocks.Any() && blocks.Last() is not AiActionTriggerBlock)
{
blocks.Add(CreateAiTrigger($"trigger-{blockCounter++}"));
}
return Result.Ok(new ReaderPageViewModel(blocks, chapterIndex, book.ReadingOrder.Count, chapterTitle));
}
catch (Exception ex)
{
return Result.Fail(new Error($"Failed to process EPUB: {ex.Message}").CausedBy(ex));
}
}
private List<string> ExtractParagraphs(string html)
{
var paragraphs = new List<string>();
// Match <p> tags and their content
var matches = Regex.Matches(html, @"<p\b[^>]*>(.*?)</p>", RegexOptions.IgnoreCase | RegexOptions.Singleline);
foreach (Match match in matches)
{
paragraphs.Add(match.Groups[1].Value);
}
// Fallback: split by double newlines if no <p> tags found
if (paragraphs.Count == 0)
{
var bodyMatch = Regex.Match(html, @"<body\b[^>]*>(.*?)</body>", RegexOptions.IgnoreCase | RegexOptions.Singleline);
var content = bodyMatch.Success ? bodyMatch.Groups[1].Value : html;
paragraphs = content.Split(new[] { "<br />", "<br>", "\n\n" }, StringSplitOptions.RemoveEmptyEntries).ToList();
}
return paragraphs;
}
private string SanitizeParagraph(string html)
{
// 1. Remove <style> and <script> blocks
var clean = Regex.Replace(html, @"<(style|script)\b[^>]*>.*?</\1>", "", RegexOptions.IgnoreCase | RegexOptions.Singleline);
// 2. Remove all tags except <b>, <i>, <strong>, <em>
clean = Regex.Replace(clean, @"<(?!/?(b|i|strong|em)\b)[^>]+>", "", RegexOptions.IgnoreCase);
// 3. Requirement: Aggressively strip attributes (class, style, id) from allowed tags
clean = Regex.Replace(clean, @"<(b|i|strong|em)\b[^>]*>", "<$1>", RegexOptions.IgnoreCase);
// 4. Decode HTML entities
clean = System.Net.WebUtility.HtmlDecode(clean);
return clean.Trim();
}
private int CountWords(string text)
{
if (string.IsNullOrWhiteSpace(text)) return 0;
return text.Split(new[] { ' ', '\r', '\n', '\t' }, StringSplitOptions.RemoveEmptyEntries).Length;
}
private AiActionTriggerBlock CreateAiTrigger(string id)
{
return new AiActionTriggerBlock(
id,
"Wykryto ciekawy fragment! Czy chcesz, abym wygenerował podsumowanie lub quiz z tego rozdziału?",
new List<string> { "Podsumuj", "Generuj Quiz", "Pomiń" }
);
}
}
@@ -1,16 +1,18 @@
.intelligence-toolbar {
width: 50px;
height: 100%;
background: #1a1a1a;
border-right: 1px solid rgba(255, 255, 255, 0.05);
background: #080808;
border-right: 1px solid rgba(255, 255, 255, 0.03);
display: flex;
flex-direction: column;
justify-content: space-between;
padding: 1rem 0;
padding: 1.5rem 0;
align-items: center;
z-index: 20;
box-shadow: inset -2px 0 10px rgba(0,0,0,0.5);
}
.toolbar-top, .toolbar-middle, .toolbar-bottom {
display: flex;
flex-direction: column;
@@ -20,29 +22,46 @@
.toolbar-item {
background: none;
border: none;
color: #666;
color: #444;
cursor: pointer;
padding: 8px;
width: 34px;
height: 34px;
display: flex;
align-items: center;
justify-content: center;
transition: all 0.2s ease;
border-radius: 4px;
transition: all 0.3s cubic-bezier(0.4, 0, 0.2, 1);
border-radius: 8px;
position: relative;
}
.toolbar-item:hover {
color: #fff;
background: rgba(255, 255, 255, 0.05);
color: var(--nexus-neon);
background: rgba(0, 255, 153, 0.05);
}
.toolbar-item.active {
color: var(--nexus-neon);
background: rgba(0, 255, 153, 0.08);
}
.toolbar-item.active::after {
content: '';
position: absolute;
right: -2px;
top: 25%;
height: 50%;
width: 3px;
background: var(--nexus-neon);
box-shadow: 0 0 8px var(--nexus-neon);
border-radius: 2px;
}
.toolbar-item.focus-active {
filter: drop-shadow(0 0 5px var(--nexus-neon));
color: var(--nexus-neon);
filter: drop-shadow(0 0 8px var(--nexus-neon));
}
.rotate-180 {
transform: rotate(180deg);
}
@@ -7,13 +7,14 @@
@inject IJSRuntime JS
@inject IThemeService ThemeService
@inject IFocusModeService FocusMode
@inject IReaderNavigationService NavigationService
<div class="reader-canvas theme-light">
<div class="reader-canvas @(ThemeService.IsLightMode ? "theme-light" : "theme-dark")">
@if (ViewModel == null)
{
<NexusTypography Variant="NexusTypography.TypographyVariant.UI">@StatusMessage</NexusTypography>
<div class="loading-state">
<NexusTypography Variant="NexusTypography.TypographyVariant.UI">@StatusMessage</NexusTypography>
</div>
}
else
{
@@ -23,7 +24,7 @@
<div id="@block.Id" class="block-wrapper">
@if (block is TextSegmentBlock textSegment)
{
<NexusTypography Variant="NexusTypography.TypographyVariant.Ebook">@textSegment.Content</NexusTypography>
<NexusTypography Variant="NexusTypography.TypographyVariant.Ebook">@((MarkupString)textSegment.Content)</NexusTypography>
}
else if (block is AiActionTriggerBlock aiTrigger)
{
@@ -43,18 +44,37 @@
private ReaderPageViewModel? ViewModel;
private string StatusMessage = "Loading chapter...";
protected override async Task OnInitializedAsync()
protected override void OnInitialized()
{
ThemeService.OnThemeChanged += StateHasChanged;
NavigationService.OnNavigationChanged += OnNavigationChanged;
}
var result = await Mediator.Send(new GetReaderPageQuery());
protected override async Task OnParametersSetAsync()
{
await LoadChapterAsync(NavigationService.CurrentChapterIndex);
}
private async void OnNavigationChanged()
{
await LoadChapterAsync(NavigationService.CurrentChapterIndex);
StateHasChanged();
}
private async Task LoadChapterAsync(int index)
{
ViewModel = null;
StatusMessage = "Fetching content...";
var result = await Mediator.Send(new GetReaderPageQuery(index));
if (result.IsSuccess)
{
ViewModel = result.Value;
NavigationService.UpdateMetadata(ViewModel.CurrentChapterIndex, ViewModel.TotalChapters, ViewModel.ChapterTitle);
}
else
{
StatusMessage = "Failed to load chapter content.";
StatusMessage = $"Error: {result.Errors.FirstOrDefault()?.Message ?? "Failed to load"}";
}
}
@@ -75,5 +95,6 @@
public void Dispose()
{
ThemeService.OnThemeChanged -= StateHasChanged;
NavigationService.OnNavigationChanged -= OnNavigationChanged;
}
}
@@ -9,4 +9,4 @@
display: flex;
flex-direction: column;
gap: 1.5rem;
}
}
@@ -1,21 +1,49 @@
@using NexusReader.UI.Shared.Services
@inject IReaderNavigationService NavigationService
@implements IDisposable
<footer class="reader-footer">
<div class="footer-content">
<div class="page-info">
<span class="label">Postęp:</span>
<span class="value">@Progress%</span>
<div class="navigation-controls">
<button class="nav-btn" @onclick="NavigationService.GoToPreviousChapter" disabled="@(NavigationService.CurrentChapterIndex == 0)">
<NexusIcon Name="arrow-left" Size="14" />
</button>
<div class="chapter-info">
<span class="chapter-title">@NavigationService.ChapterTitle</span>
<span class="chapter-count">(@(NavigationService.CurrentChapterIndex + 1) / @NavigationService.TotalChapters)</span>
</div>
<button class="nav-btn" @onclick="NavigationService.GoToNextChapter" disabled="@(NavigationService.CurrentChapterIndex >= NavigationService.TotalChapters - 1)">
<NexusIcon Name="arrow-right" Size="14" />
</button>
</div>
<div class="progress-container">
<div class="progress-bar" style="width: @Progress%"></div>
<div class="progress-bar" style="width: @CalculateProgress()%"></div>
</div>
<div class="meta-info">
<span class="time">1:30</span>
<span class="battery">45% 🔋</span>
<span class="time">@DateTime.Now.ToString("HH:mm")</span>
</div>
</div>
</footer>
@code {
[Parameter] public int Progress { get; set; } = 45;
protected override void OnInitialized()
{
NavigationService.OnNavigationChanged += StateHasChanged;
}
private int CalculateProgress()
{
if (NavigationService.TotalChapters <= 1) return 0;
return (int)((NavigationService.CurrentChapterIndex / (float)(NavigationService.TotalChapters - 1)) * 100);
}
public void Dispose()
{
NavigationService.OnNavigationChanged -= StateHasChanged;
}
}
@@ -1,53 +1,102 @@
.reader-footer {
position: absolute;
bottom: 0;
left: 0;
width: 100%;
height: 40px;
position: relative;
height: 50px;
background: #F9F9F9;
border-top: 1px solid rgba(0, 0, 0, 0.05);
border-top: 1px solid rgba(0, 0, 0, 0.08);
display: flex;
align-items: center;
padding: 0 1.5rem;
z-index: 10;
flex-shrink: 0;
}
.footer-content {
display: flex;
justify-content: space-between;
align-items: center;
width: 100%;
font-family: var(--nexus-font-sans);
gap: 1.5rem;
}
.navigation-controls {
display: flex;
align-items: center;
gap: 1rem;
flex-shrink: 0;
}
.nav-btn {
background: white;
border: 1px solid rgba(0, 0, 0, 0.1);
border-radius: 6px;
width: 32px;
height: 32px;
display: flex;
align-items: center;
justify-content: center;
cursor: pointer;
transition: all 0.2s ease;
color: #333;
box-shadow: 0 1px 2px rgba(0, 0, 0, 0.05);
}
.nav-btn:hover:not(:disabled) {
background: #f0f0f0;
transform: translateY(-1px);
}
.nav-btn:disabled {
opacity: 0.3;
cursor: not-allowed;
}
.chapter-info {
display: flex;
align-items: center;
gap: 0.5rem;
font-size: 0.85rem;
color: #333;
white-space: nowrap;
}
.chapter-title {
font-weight: 600;
max-width: 180px;
overflow: hidden;
text-overflow: ellipsis;
}
.chapter-count {
opacity: 0.5;
font-size: 0.75rem;
color: #666;
}
.progress-container {
flex: 1;
height: 4px;
background: rgba(0, 0, 0, 0.1);
margin: 0 2rem;
border-radius: 2px;
height: 6px;
background: rgba(0, 0, 0, 0.05);
border-radius: 3px;
overflow: hidden;
max-width: 400px;
margin: 0 1rem;
}
.progress-bar {
height: 100%;
background: linear-gradient(90deg, #00ff99 0%, #00d4ff 100%);
border-radius: 2px;
background: #2ECC71;
border-radius: 3px;
transition: width 0.3s ease;
}
.page-info, .meta-info {
.meta-info {
display: flex;
gap: 0.5rem;
align-items: center;
gap: 1rem;
font-size: 0.75rem;
color: #888;
flex-shrink: 0;
}
.label {
opacity: 0.7;
}
.value {
font-weight: 600;
}
.battery {
display: flex;
align-items: center;
gap: 0.3rem;
}
@@ -11,7 +11,7 @@
<main>
@Body
</main>
<ReaderFooter Progress="45" />
<ReaderFooter />
</div>
<div class="intelligence-sidebar">
@@ -12,10 +12,18 @@
.reader-pane {
background: #F9F9F9;
position: relative;
overflow-y: auto;
overflow: hidden;
display: flex;
flex-direction: column;
z-index: 5;
height: 100vh;
}
main {
flex: 1;
overflow-y: auto;
overflow-x: hidden;
position: relative;
}
.intelligence-sidebar {
@@ -23,22 +31,30 @@
grid-template-columns: 50px 1fr;
width: 450px;
height: 100%;
background: #121212;
border-left: 1px solid rgba(255, 255, 255, 0.1);
background: #0d0d0d;
box-shadow: -10px 0 30px rgba(0, 0, 0, 0.3);
border-left: 1px solid rgba(255, 255, 255, 0.05);
transition: all 0.4s cubic-bezier(0.4, 0, 0.2, 1);
overflow: hidden;
z-index: 10;
}
.app-container.focus-mode-active {
grid-template-columns: 1fr 0px;
grid-template-columns: 1fr 50px;
}
.app-container.focus-mode-active .intelligence-sidebar {
width: 0;
border-left-width: 0;
opacity: 0;
width: 50px;
grid-template-columns: 50px 0px;
}
.app-container.focus-mode-active .intelligence-content {
opacity: 0;
pointer-events: none;
}
.intelligence-content {
display: flex;
@@ -77,11 +93,6 @@
flex-direction: column;
}
main {
flex: 1;
padding-bottom: 40px; /* footer height */
}
/* Platform Specifics */
.platform-mobile .intelligence-sidebar {
position: fixed;
@@ -91,3 +102,22 @@ main {
width: 80%;
z-index: 100;
}
#blazor-error-ui {
background: lightyellow;
bottom: 0;
box-shadow: 0 -1px 2px rgba(0, 0, 0, 0.2);
display: none;
left: 0;
padding: 0.6rem 1.25rem 0.7rem 1.25rem;
position: fixed;
width: 100%;
z-index: 1000;
}
#blazor-error-ui .dismiss {
cursor: pointer;
position: absolute;
right: 0.75rem;
top: 0.5rem;
}
+34 -6
View File
@@ -1,6 +1,34 @@
<Router AppAssembly="@typeof(Routes).Assembly">
<Found Context="routeData">
<RouteView RouteData="@routeData" DefaultLayout="@typeof(Layout.MainLayout)" />
<FocusOnNavigate RouteData="@routeData" Selector="h1" />
</Found>
</Router>
<ErrorBoundary @ref="_errorBoundary">
<ChildContent>
<Router AppAssembly="@typeof(Routes).Assembly">
<Found Context="routeData">
<RouteView RouteData="@routeData" DefaultLayout="@typeof(Layout.MainLayout)" />
<FocusOnNavigate RouteData="@routeData" Selector="h1" />
</Found>
</Router>
</ChildContent>
<ErrorContent Context="ex">
<div class="nexus-error-boundary">
<div class="error-card">
<div class="error-icon">
<NexusIcon Name="alert-triangle" Size="48" Color="#ff4444" />
</div>
<h3>Nexus System Error</h3>
<p>Wystąpił nieoczekiwany błąd podczas renderowania komponentu.</p>
<div class="error-details">
<code>@ex.Message</code>
</div>
<button class="retry-btn" @onclick="() => _errorBoundary?.Recover()">
<NexusIcon Name="refresh-cw" Size="16" />
Spróbuj ponownie
</button>
</div>
</div>
</ErrorContent>
</ErrorBoundary>
@code {
private ErrorBoundary? _errorBoundary;
}
@@ -0,0 +1,83 @@
.nexus-error-boundary {
display: flex;
align-items: center;
justify-content: center;
min-height: 300px;
width: 100%;
padding: 2rem;
background: rgba(18, 18, 18, 0.8);
backdrop-filter: blur(10px);
border-radius: 12px;
margin: 1rem 0;
}
.error-card {
background: #1e1e1e;
border: 1px solid rgba(255, 68, 68, 0.2);
border-radius: 16px;
padding: 2.5rem;
max-width: 500px;
width: 100%;
text-align: center;
box-shadow: 0 20px 40px rgba(0, 0, 0, 0.4);
}
.error-icon {
margin-bottom: 1.5rem;
animation: pulse 2s infinite;
}
@keyframes pulse {
0% { transform: scale(1); opacity: 1; }
50% { transform: scale(1.1); opacity: 0.8; }
100% { transform: scale(1); opacity: 1; }
}
h3 {
color: #fff;
font-family: var(--nexus-font-sans);
margin-bottom: 1rem;
font-weight: 700;
}
p {
color: #aaa;
font-size: 0.9rem;
margin-bottom: 1.5rem;
}
.error-details {
background: #000;
padding: 1rem;
border-radius: 8px;
margin-bottom: 2rem;
text-align: left;
overflow-x: auto;
}
code {
color: #ff4444;
font-family: 'Fira Code', monospace;
font-size: 0.8rem;
white-space: pre-wrap;
}
.retry-btn {
background: linear-gradient(135deg, #333 0%, #111 100%);
border: 1px solid rgba(255, 255, 255, 0.1);
color: #fff;
padding: 0.8rem 1.5rem;
border-radius: 8px;
cursor: pointer;
display: inline-flex;
align-items: center;
gap: 0.8rem;
font-size: 0.9rem;
transition: all 0.2s ease;
}
.retry-btn:hover {
background: linear-gradient(135deg, #444 0%, #222 100%);
border-color: rgba(255, 255, 255, 0.2);
transform: translateY(-2px);
}
@@ -0,0 +1,15 @@
namespace NexusReader.UI.Shared.Services;
public interface IReaderNavigationService
{
int CurrentChapterIndex { get; }
int TotalChapters { get; }
string ChapterTitle { get; }
event Action OnNavigationChanged;
void GoToChapter(int index);
void GoToNextChapter();
void GoToPreviousChapter();
void UpdateMetadata(int currentIndex, int totalChapters, string title);
}
@@ -0,0 +1,47 @@
namespace NexusReader.UI.Shared.Services;
public class ReaderNavigationService : IReaderNavigationService
{
public int CurrentChapterIndex { get; private set; } = 0;
public int TotalChapters { get; private set; } = 1;
public string ChapterTitle { get; private set; } = "Loading...";
public event Action? OnNavigationChanged;
public void GoToChapter(int index)
{
if (index < 0 || index >= TotalChapters) return;
CurrentChapterIndex = index;
OnNavigationChanged?.Invoke();
}
public void GoToNextChapter()
{
if (CurrentChapterIndex < TotalChapters - 1)
{
GoToChapter(CurrentChapterIndex + 1);
}
}
public void GoToPreviousChapter()
{
if (CurrentChapterIndex > 0)
{
GoToChapter(CurrentChapterIndex - 1);
}
}
public void UpdateMetadata(int currentIndex, int totalChapters, string title)
{
bool changed = false;
if (CurrentChapterIndex != currentIndex) { CurrentChapterIndex = currentIndex; changed = true; }
if (TotalChapters != totalChapters) { TotalChapters = totalChapters; changed = true; }
if (ChapterTitle != title) { ChapterTitle = title; changed = true; }
if (changed)
{
OnNavigationChanged?.Invoke();
}
}
}
+26
View File
@@ -27,6 +27,12 @@
}
* {
box-sizing: border-box;
-webkit-font-smoothing: antialiased;
-moz-osx-font-smoothing: grayscale;
}
body {
background-color: var(--nexus-bg);
color: var(--nexus-text);
@@ -44,6 +50,26 @@ body {
overflow-x: hidden;
}
/* Modern Scrollbars */
::-webkit-scrollbar {
width: 6px;
height: 6px;
}
::-webkit-scrollbar-track {
background: transparent;
}
::-webkit-scrollbar-thumb {
background: rgba(255, 255, 255, 0.1);
border-radius: 10px;
}
::-webkit-scrollbar-thumb:hover {
background: rgba(255, 255, 255, 0.2);
}
/* Platform Specific Tweaks */
.platform-mobile .nexus-button {
min-height: var(--touch-target-size);
+23 -18
View File
@@ -1,18 +1,23 @@
using Microsoft.AspNetCore.Components.WebAssembly.Hosting;
using NexusReader.Application.Abstractions.Services;
using NexusReader.Web.Client.Services;
using NexusReader.UI.Shared.Services;
using NexusReader.Application;
using NexusReader.Infrastructure;
var builder = WebAssemblyHostBuilder.CreateDefault(args);
builder.Services.AddScoped<IPlatformService, WebPlatformService>();
builder.Services.AddScoped<IThemeService, ThemeService>();
builder.Services.AddScoped<IQuizStateService, QuizStateService>();
builder.Services.AddScoped<IFocusModeService, FocusModeService>();
builder.Services.AddApplication();
builder.Services.AddInfrastructure();
await builder.Build().RunAsync();
using Microsoft.AspNetCore.Components.WebAssembly.Hosting;
using NexusReader.Application.Abstractions.Services;
using NexusReader.Web.Client.Services;
using NexusReader.UI.Shared.Services;
using NexusReader.Application;
using NexusReader.Infrastructure;
using NexusReader.Infrastructure.Services;
var builder = WebAssemblyHostBuilder.CreateDefault(args);
builder.Services.AddScoped<IPlatformService, WebPlatformService>();
builder.Services.AddScoped<IThemeService, ThemeService>();
builder.Services.AddScoped<IQuizStateService, QuizStateService>();
builder.Services.AddScoped<IFocusModeService, FocusModeService>();
builder.Services.AddScoped<IReaderNavigationService, ReaderNavigationService>();
builder.Services.AddScoped(sp => new HttpClient { BaseAddress = new Uri(builder.HostEnvironment.BaseAddress) });
builder.Services.AddApplication();
builder.Services.AddScoped<IEpubService, WasmEpubService>();
builder.Services.AddTransient<IAiGenerateQuizService, FakeAiGenerateQuizService>();
await builder.Build().RunAsync();
@@ -0,0 +1,38 @@
using System.Net.Http.Json;
using FluentResults;
using NexusReader.Application.Abstractions.Services;
using NexusReader.Application.Queries.Reader;
namespace NexusReader.Web.Client.Services;
public class WasmEpubService : IEpubService
{
private readonly HttpClient _httpClient;
public WasmEpubService(HttpClient httpClient)
{
_httpClient = httpClient;
}
public async Task<Result<ReaderPageViewModel>> GetEpubContentAsync(int chapterIndex)
{
try
{
var response = await _httpClient.GetAsync($"/api/epub/{chapterIndex}");
if (response.IsSuccessStatusCode)
{
var viewModel = await response.Content.ReadFromJsonAsync<ReaderPageViewModel>();
return viewModel != null ? Result.Ok(viewModel) : Result.Fail("Failed to deserialize response.");
}
// Try to read the error message from the body
var errorBody = await response.Content.ReadAsStringAsync();
return Result.Fail($"Server error ({response.StatusCode}): {errorBody}");
}
catch (Exception ex)
{
// Fallback for network errors or parsing exceptions
return Result.Fail(new Error($"Network or parsing error: {ex.Message}").CausedBy(ex));
}
}
}
+68 -58
View File
@@ -1,58 +1,68 @@
using NexusReader.Web.Components;
using NexusReader.Application;
using NexusReader.Infrastructure;
using NexusReader.Application.Abstractions.Services;
using NexusReader.Web.Client.Services;
using NexusReader.UI.Shared.Services;
var builder = WebApplication.CreateBuilder(args);
// Add services to the container.
builder.Services.AddRazorComponents()
.AddInteractiveServerComponents()
.AddInteractiveWebAssemblyComponents();
// Enable detailed circuit errors for ServerSide Blazor components
builder.Services.AddServerSideBlazor()
.AddCircuitOptions(options =>
{
options.DetailedErrors = true;
});
builder.Services.AddScoped<IPlatformService, WebPlatformService>();
builder.Services.AddScoped<IThemeService, ThemeService>();
builder.Services.AddScoped<IQuizStateService, QuizStateService>();
builder.Services.AddScoped<IFocusModeService, FocusModeService>();
builder.Services.AddApplication();
builder.Services.AddInfrastructure();
var app = builder.Build();
// Configure the HTTP request pipeline.
if (app.Environment.IsDevelopment())
{
app.UseWebAssemblyDebugging();
}
else
{
app.UseExceptionHandler("/Error", createScopeForErrors: true);
// The default HSTS value is 30 days. You may want to change this for production scenarios, see https://aka.ms/aspnetcore-hsts.
app.UseHsts();
}
app.UseStatusCodePagesWithReExecute("/not-found", createScopeForStatusCodePages: true);
if (!app.Environment.IsDevelopment())
{
app.UseHttpsRedirection();
}
app.UseAntiforgery();
app.MapStaticAssets();
app.MapRazorComponents<App>()
.AddInteractiveServerRenderMode()
.AddInteractiveWebAssemblyRenderMode()
.AddAdditionalAssemblies(typeof(NexusReader.UI.Shared._Imports).Assembly);
app.Run();
using NexusReader.Web.Components;
using NexusReader.Application;
using NexusReader.Infrastructure;
using NexusReader.Application.Abstractions.Services;
using NexusReader.Web.Client.Services;
using NexusReader.UI.Shared.Services;
var builder = WebApplication.CreateBuilder(args);
// Add services to the container.
builder.Services.AddRazorComponents()
.AddInteractiveServerComponents()
.AddInteractiveWebAssemblyComponents();
// Enable detailed circuit errors for ServerSide Blazor components
builder.Services.AddServerSideBlazor()
.AddCircuitOptions(options =>
{
options.DetailedErrors = true;
});
builder.Services.AddScoped<IPlatformService, WebPlatformService>();
builder.Services.AddScoped<IThemeService, ThemeService>();
builder.Services.AddScoped<IQuizStateService, QuizStateService>();
builder.Services.AddScoped<IFocusModeService, FocusModeService>();
builder.Services.AddScoped<IReaderNavigationService, ReaderNavigationService>();
builder.Services.AddApplication();
builder.Services.AddInfrastructure();
var app = builder.Build();
// Configure the HTTP request pipeline.
if (app.Environment.IsDevelopment())
{
app.UseWebAssemblyDebugging();
}
else
{
app.UseExceptionHandler("/Error", createScopeForErrors: true);
app.UseHsts();
}
app.UseStatusCodePagesWithReExecute("/not-found", createScopeForStatusCodePages: true);
if (!app.Environment.IsDevelopment())
{
app.UseHttpsRedirection();
}
app.UseAntiforgery();
app.MapStaticAssets();
// API endpoint for WASM client to fetch EPUB content
app.MapGet("/api/epub/{index}", async (int index, IEpubService epubService) =>
{
var result = await epubService.GetEpubContentAsync(index);
if (result.IsSuccess) return Results.Ok(result.Value);
var errorMsg = result.Errors.FirstOrDefault()?.Message ?? "Unknown server error";
return Results.BadRequest(errorMsg);
});
app.MapRazorComponents<App>()
.AddInteractiveServerRenderMode()
.AddInteractiveWebAssemblyRenderMode()
.AddAdditionalAssemblies(typeof(NexusReader.UI.Shared._Imports).Assembly);
app.Run();