Adds book reading support with EPUB and PDF reader plugins

This commit is contained in:
BinaryAlley committed 2026-09-02 04:45:11 -07:00
1 parent 275fd83ff2
commit f7ccdf3d1c
271 files changed
+11501 -361

No files matched your search

@@ -238,6 +238,22 @@
</table>
<small class="form-label text-disabled form-description">@_localizer["DescriptionArtworkProviders"]</small>
</div>
<h3 class="text-light-two">@_localizer["BookReaders"]</h3>
<div class="form-row">
<table id="book-readers-table" class="w-100">
<thead>
<tr>
<th class="w-35">@_localizer["Name"]</th>
<th class="w-40">@_localizer["SupportedExtensions"]</th>
<th class="w-25 text-center">@_localizer["Enabled"]</th>
</tr>
</thead>
<tbody>
<!-- book readers will be populated here -->
</tbody>
</table>
<small class="form-label text-disabled form-description">@_localizer["DescriptionBookReaders"]</small>
</div>
}
<div class="form-row">
<button type="submit" class="confirm-button w-100px">@_localizer["Save"]</button>
@@ -522,6 +538,49 @@
}
};
const bookReadersTable = document.getElementById('book-readers-table');
const bookReadersTbody = bookReadersTable ? bookReadersTable.querySelector('tbody') : null;
// loads the book readers configured for the library, when editing an existing library
async function loadBookReadersAsync() {
if (!id || !bookReadersTbody) return;
const url = '@_urlService.GetAbsoluteUrl(WebRoutes.LibraryManagement.GET_BOOK_READERS, new { libraryId = default(Guid) })'
.replace('/@(default(Guid))', `/${id}`); // libraryId needs to be replaced here, because GetAbsoluteUrl is server side, libraryId is client side
const response = await callApiGetAsync(url);
if (response && response.length > 0) {
bookReadersTbody.innerHTML = response.map(reader => renderBookReaderRow(reader)).join('');
}
}
// renders a book reader row of the library
function renderBookReaderRow(reader) {
const extensions = (reader.supportedExtensions || []).join(', ');
return `
<tr data-reader-plugin-id="${reader.pluginId}">
<td>${reader.name}</td>
<td>${extensions}</td>
<td class="text-center">
<label class="enlightenment-checkbox-label">
<input type="checkbox" class="enlightenment-checkbox-hidden book-reader-enabled" ${reader.isEnabled ? 'checked' : ''} />
<span class="enlightenment-checkbox"></span>
</label>
</td>
</tr>`;
}
// on book reader enabled checkbox change, persists the new state
async function handleBookReaderEnabledChangeAsync(e) {
if (e.target.matches('.book-reader-enabled')) {
const row = e.target.closest('tr');
const pluginId = row.getAttribute('data-reader-plugin-id');
const isEnabled = e.target.checked;
const result = await callApiPutAsync('@_urlService.GetAbsoluteUrl(WebRoutes.LibraryManagement.SET_BOOK_READER_ENABLED)', { libraryId: id, pluginId: pluginId, isEnabled: isEnabled });
if (!result.success) {
e.target.checked = !isEnabled;
}
}
};
// add listeners
form.addEventListener('keypress', handleEnterKey);
form.addEventListener('submit', handleSubmit);
@@ -539,6 +598,9 @@
artworkProvidersTbody.addEventListener('click', handleArtworkProviderReorderAsync);
artworkProvidersTbody.addEventListener('change', handleArtworkProviderEnabledChangeAsync);
}
if (bookReadersTbody) {
bookReadersTbody.addEventListener('change', handleBookReaderEnabledChangeAsync);
}
// register cleanup for these listeners
cleanupFunctions.push(() => {
@@ -558,12 +620,16 @@
artworkProvidersTbody.removeEventListener('click', handleArtworkProviderReorderAsync);
artworkProvidersTbody.removeEventListener('change', handleArtworkProviderEnabledChangeAsync);
}
if (bookReadersTbody) {
bookReadersTbody.removeEventListener('change', handleBookReaderEnabledChangeAsync);
}
});
// load the metadata and artwork providers when editing an existing library
// load the metadata and artwork providers and book readers when editing an existing library
if (id) {
loadMetadataProvidersAsync();
loadArtworkProvidersAsync();
loadBookReadersAsync();
}
// store all cleanups for this view on window object using the scriptId
@@ -7,7 +7,7 @@
@using Microsoft.AspNetCore.Mvc.Localization
@{
// generate a unique id for the scripts section of this view, so it can be dynamically loaded/unloaded by the global AJAX navigator handler
// Generate a unique id for the scripts section of this view, so it can be dynamically loaded/unloaded by the global AJAX navigator handler.
var scriptId = ScriptIdentifierHelper.GenerateScriptId();
}
@@ -18,8 +18,8 @@
<div class="cotton-candy">
<div style="display: grid; grid-template-rows: auto 1fr;">
<!--container with two rows, one fixed, one filling remaining space-->
<div style="min-height: 1rem;"></div><!--the first row is a dummy row for "margin", because setting a margin on the next row would offset the parent's position-->
<!--Container with two rows, one fixed, one filling remaining space.-->
<div style="min-height: 1rem;"></div><!--The first row is a dummy row for "margin", because setting a margin on the next row would offset the parent's position.-->
<div class="pl-10 pr-10 pb-10">
<div class="text-center">
<h1 class="text-light-two engraved-title">@(Model.Title ?? string.Empty)</h1>
@@ -48,12 +48,14 @@
@section Scripts {
<!-- The "text/plain" type is a design choice, not a mistake: it keeps the browser from executing this view script during HTML parsing, before site.js defines the API helpers it calls (callApiGetAsync, callApiPostAsync, ...). site.js (which loads deferred) executes these scripts once it is loaded, both on the initial page load and during AJAX navigation. -->
<script type="text/plain" data-form="@scriptId">
// create cleanup registry for this view
// Create cleanup registry for this view.
const cleanupFunctions = [];
let isInitialized = false;
let requestSequence = 0;
const libraryId = '@(Model.Id ?? Guid.Empty)';
const readUrlTemplate = '@_urlService.GetAbsoluteUrl(WebRoutes.Books.READ, new { bookId = default(Guid) })';
const availabilityUrlTemplate = '@_urlService.GetAbsoluteUrl(WebRoutes.Books.GET_READING_AVAILABILITY, new { bookId = default(Guid) })';
const booksContainer = document.getElementById('books-container');
const noItemsMessage = document.getElementById('no-items');
const noItemsMatchingMessage = document.getElementById('no-items-matching');
@@ -67,7 +69,7 @@
const nextPageButton = document.getElementById('next-page');
const pageIndicator = document.getElementById('page-indicator');
// the special alpha keys for numbers and symbols, followed by the letters
// The special alpha keys for numbers and symbols, followed by the letters.
const alphaKeys = ['#', '*', ...Array.from({ length: 26 }, (_, index) => String.fromCharCode(65 + index))];
const state = {
@@ -85,10 +87,12 @@
of: '@_localizer["Of"]',
page: '@_localizer["Page"]',
sortAscending: '@_localizer["SortAscending"]',
sortDescending: '@_localizer["SortDescending"]'
sortDescending: '@_localizer["SortDescending"]',
readerUnavailable: '@_localizer["ReaderUnavailable"]',
readerDisabled: '@_localizer["ReaderDisabled"]'
};
// builds the URL of the retrieval endpoint, from the current state
// Builds the URL of the retrieval endpoint, from the current state.
function buildItemsUrl() {
const url = '@_urlService.GetAbsoluteUrl(WebRoutes.Books.GET_LIBRARY_ITEMS)';
const params = new URLSearchParams();
@@ -106,7 +110,7 @@
return `${url}?${params.toString()}`;
}
// retrieves the books and renders them, ignoring stale responses of earlier requests
// Retrieves the books and renders them, ignoring stale responses of earlier requests.
async function loadItemsAsync() {
const requestId = ++requestSequence;
const response = await callApiGetAsync(buildItemsUrl());
@@ -116,7 +120,7 @@
renderItems(response);
}
// renders the retrieved books, the count label and the pagination controls
// Renders the retrieved books, the count label and the pagination controls.
function renderItems(response) {
booksContainer.querySelectorAll('.media-panel').forEach(card => card.remove());
@@ -132,16 +136,29 @@
response.data.forEach(book => booksContainer.appendChild(createBookCard(book)));
}
// Bind the AJAX navigation behavior to the book cards, which were created after the initial navigation binding, so that
// navigating to the reader does not reload the page (and, for example, does not interrupt the audio player).
bindNavigationLinks();
updateCountLabel(response);
updatePagination(response);
}
// creates a portrait card for a book, with its cover image (or a placeholder) and its title
// Creates a portrait card for a book, with its cover image (or a placeholder) and its title, that opens the reader when clicked.
function createBookCard(book) {
const card = document.createElement('div');
card.className = 'media-panel';
const card = document.createElement('a');
card.className = 'media-panel nav-link no-underline';
card.style.width = '160px';
card.style.height = '240px';
card.href = readUrlTemplate.replace('/@(default(Guid))', `/${book.id}`);
card.dataset.bookId = book.id;
// Opening the reader is conditional on the reader being available and enabled for the library, so the generic nav-link
// navigation is intercepted and replaced by one that first checks the reading availability, warning instead of navigating
// when the book cannot be read.
card.addEventListener('click', async event => {
event.preventDefault();
event.stopImmediatePropagation();
await handleBookCardClickAsync(card);
});
const image = document.createElement('img');
image.src = book.coverPath
@@ -160,7 +177,26 @@
return card;
}
// updates the count label: total items when pagination is off, displayed range out of total when it is on
// Opens the reader of the book when it can be read, and warns the user otherwise; the navigation is done through the same
// AJAX navigation used by the nav-links, so that the page is not reloaded (and the audio player is not interrupted).
async function handleBookCardClickAsync(card) {
const availabilityUrl = availabilityUrlTemplate.replace('/@(default(Guid))', `/${card.dataset.bookId}`);
const response = await fetch(availabilityUrl, {
headers: {
'Accept': 'application/json',
'X-Requested-With': 'XMLHttpRequest'
}
});
const jsonResponse = await response.json();
if (jsonResponse.success) {
await updateContentAsync(card.href, true);
} else {
const message = jsonResponse.errorCode === 'ReaderDisabled' ? jsLocalizedStrings.readerDisabled : jsLocalizedStrings.readerUnavailable;
notificationService.show(message, NotificationType.WARNING);
}
}
// Updates the count label: total items when pagination is off, displayed range out of total when it is on.
function updateCountLabel(response) {
if (state.perPage === null)
countLabel.textContent = `${response.count} ${jsLocalizedStrings.items}`;
@@ -173,7 +209,7 @@
}
}
// updates the pagination controls, which are only visible when pagination is enabled
// Updates the pagination controls, which are only visible when pagination is enabled.
function updatePagination(response) {
if (state.perPage === null) {
pagination.classList.add('hidden');
@@ -186,7 +222,7 @@
nextPageButton.disabled = response.currentPage >= totalPages;
}
// builds the alpha picker column, with the "All" key followed by the numbers, symbols and letters keys
// Builds the alpha picker column, with the "All" key followed by the numbers, symbols and letters keys.
function buildAlphaPicker() {
const allKey = document.createElement('span');
allKey.className = 'alpha-key';
@@ -207,7 +243,7 @@
updateAlphaPickerActiveState();
}
// highlights the currently active key of the alpha picker
// Highlights the currently active key of the alpha picker.
function updateAlphaPickerActiveState() {
alphaPicker.querySelectorAll('.alpha-key').forEach(key => {
const keyValue = key.dataset.alphaKey === '' ? null : key.dataset.alphaKey;
@@ -215,7 +251,7 @@
});
}
// applies the given alpha key (null clears the alpha filter) and reloads the books
// Applies the given alpha key (null clears the alpha filter) and reloads the books.
function handleAlphaKeyClick(key) {
state.alphaKey = key;
state.currentPage = 1;
@@ -223,14 +259,14 @@
loadItemsAsync();
}
// applies the search term and reloads the books
// Applies the search term and reloads the books.
function handleSearch() {
state.searchTerm = searchInput.value.trim();
state.currentPage = 1;
loadItemsAsync();
}
// triggers the search when the Enter key is pressed in the search input
// Triggers the search when the Enter key is pressed in the search input.
function handleSearchKeydown(event) {
if (event.key === 'Enter') {
event.preventDefault();
@@ -238,7 +274,7 @@
}
}
// toggles the sort direction and reloads the books
// Toggles the sort direction and reloads the books.
function handleSortToggle() {
state.sortOrder = state.sortOrder === 'Ascending' ? 'Descending' : 'Ascending';
sortToggle.textContent = state.sortOrder === 'Ascending' ? jsLocalizedStrings.sortAscending : jsLocalizedStrings.sortDescending;
@@ -246,7 +282,7 @@
loadItemsAsync();
}
// applies an alpha filter when a letter is pressed while the search input does not have focus; Escape clears the alpha filter
// Applies an alpha filter when a letter is pressed while the search input does not have focus; Escape clears the alpha filter.
function handleAlphaKeydown(event) {
if (document.activeElement === searchInput)
return;
@@ -256,7 +292,7 @@
handleAlphaKeyClick(null);
}
// loads the settings of the current user, which drive pagination and the alpha picker prefix handling
// Loads the settings of the current user, which drive pagination and the alpha picker prefix handling.
async function loadSettingsAsync() {
const data = await callApiGetAsync('@_urlService.GetAbsoluteUrl(WebRoutes.Settings.GET_USER_SETTINGS)');
if (data) {
@@ -265,19 +301,19 @@
}
}
// navigates to the previous page
// Navigates to the previous page.
function handlePrevPageClick() {
state.currentPage = Math.max(1, state.currentPage - 1);
loadItemsAsync();
}
// navigates to the next page
// Navigates to the next page.
function handleNextPageClick() {
state.currentPage = state.currentPage + 1;
loadItemsAsync();
}
// add listeners
// Add listeners.
searchButton.addEventListener('click', handleSearch);
searchInput.addEventListener('keydown', handleSearchKeydown);
sortToggle.addEventListener('click', handleSortToggle);
@@ -286,7 +322,7 @@
document.addEventListener('keydown', handleAlphaKeydown);
document.addEventListener('DOMContentLoaded', InitializeAsync);
// register cleanup for these listeners
// Register cleanup for these listeners.
cleanupFunctions.push(() => {
searchButton.removeEventListener('click', handleSearch);
searchInput.removeEventListener('keydown', handleSearchKeydown);
@@ -307,7 +343,7 @@
await loadItemsAsync();
}
// store all cleanups for this view on window object using the scriptId
// Store all cleanups for this view on window object using the scriptId.
window.viewCleanups = window.viewCleanups || {};
window.viewCleanups['@scriptId'] = () => {
cleanupFunctions.forEach(cleanup => cleanup());
@@ -0,0 +1,320 @@
@*
/library/written-content-library/books-library/books/{bookId}/read
*@
@using Lumina.Presentation.Web.Common.Requests.Library.WrittenContentLibrary.BookLibrary.Books.Reading
@using Lumina.Presentation.Web.Common.Services
@using Microsoft.AspNetCore.Mvc.Localization
@{
// Generate a unique id for the scripts section of this view, so it can be dynamically loaded/unloaded by the global AJAX navigator handler.
var scriptId = ScriptIdentifierHelper.GenerateScriptId();
}
@inject IViewLocalizer _localizer
@inject IUrlService _urlService
@model ReadBookViewRequest
<div class="cotton-candy reader-root">
<div class="reader-toolbar form-row">
<button id="btn-back" type="button" class="abort-button">@_localizer["Back"]</button>
<button id="btn-toc-toggle" type="button" class="confirm-button">@_localizer["TableOfContents"]</button>
<button id="btn-prev" type="button" class="abort-button">@_localizer["Previous"]</button>
<button id="btn-next" type="button" class="confirm-button">@_localizer["Next"]</button>
<span id="reader-position" class="text-light-two"></span>
<span class="text-light-two">@_localizer["FontSize"]</span>
<button id="btn-font-decrease" type="button" class="abort-button">A-</button>
<button id="btn-font-increase" type="button" class="confirm-button">A+</button>
<h2 id="reader-title" class="text-light-two engraved-title"></h2>
</div>
<div id="toc-panel" class="reader-toc hidden">
<ul id="toc-list"></ul>
</div>
<p id="reader-status" class="text-light-two">@_localizer["Loading"]</p>
<div id="reader-content" class="reader-content"></div>
</div>
@section Scripts {
<!-- The "text/plain" type is a design choice, not a mistake: it keeps the browser from executing this view script during HTML parsing, before site.js defines the API helpers it calls (callApiGetAsync, callApiPutAsync, ...). site.js (which loads deferred) executes these scripts once it is loaded, both on the initial page load and during AJAX navigation. -->
<script type="text/plain" data-form="@scriptId">
// Create cleanup registry for this view.
const cleanupFunctions = [];
let isInitialized = false;
const bookId = '@Model.BookId';
const manifestUrl = '@_urlService.GetAbsoluteUrl(WebRoutes.Books.GET_READING_MANIFEST, new { bookId = default(Guid) })'.replace('/@(default(Guid))', `/${bookId}`);
const availabilityUrl = '@_urlService.GetAbsoluteUrl(WebRoutes.Books.GET_READING_AVAILABILITY, new { bookId = default(Guid) })'.replace('/@(default(Guid))', `/${bookId}`);
const libraryIndexUrl = '@_urlService.GetAbsoluteUrl(WebRoutes.Books.INDEX)';
const sectionUrlTemplate = '@_urlService.GetAbsoluteUrl(WebRoutes.Books.GET_READING_SECTION, new { bookId = default(Guid) })'.replace('/@(default(Guid))', `/${bookId}`) + '?locationRef=';
const resourceUrlTemplate = '@_urlService.GetAbsoluteUrl(WebRoutes.Books.GET_READING_RESOURCE, new { bookId = default(Guid) })'.replace('/@(default(Guid))', `/${bookId}`) + '?resourceKey=';
// Escapes a string for safe interpolation into HTML markup; the table of contents labels and location references come from
// the book file itself, so they are escaped before they are placed into innerHTML, keeping a malicious book from injecting markup.
function escapeHtml(value) {
return String(value).replace(/&/g, '&amp;').replace(/</g, '&lt;').replace(/>/g, '&gt;').replace(/"/g, '&quot;').replace(/'/g, '&#39;');
}
const readerTitle = document.getElementById('reader-title');
const readerContent = document.getElementById('reader-content');
const readerStatus = document.getElementById('reader-status');
const readerPosition = document.getElementById('reader-position');
const tocPanel = document.getElementById('toc-panel');
const tocList = document.getElementById('toc-list');
const btnBack = document.getElementById('btn-back');
const btnTocToggle = document.getElementById('btn-toc-toggle');
const btnPrev = document.getElementById('btn-prev');
const btnNext = document.getElementById('btn-next');
const btnFontDecrease = document.getElementById('btn-font-decrease');
const btnFontIncrease = document.getElementById('btn-font-increase');
// The strings are serialized as JSON, so that single quotes and other characters are escaped into valid JavaScript string literals.
const jsLocalizedStrings = {
loading: @Json.Serialize(_localizer["Loading"].Value),
readFailed: @Json.Serialize(_localizer["ReadFailed"].Value),
readerUnavailable: @Json.Serialize(_localizer["ReaderUnavailable"].Value),
readerDisabled: @Json.Serialize(_localizer["ReaderDisabled"].Value),
imageOnlyPdf: @Json.Serialize(_localizer["ImageOnlyPdf"].Value)
};
let manifest = null;
let currentIndex = -1;
let fontSize = 18;
// Loads the reading manifest of the book, and opens the first reading section.
async function loadManifestAsync() {
readerStatus.textContent = jsLocalizedStrings.loading;
const response = await fetch(manifestUrl, {
headers: {
'Accept': 'application/json',
'X-Requested-With': 'XMLHttpRequest'
}
});
if (response.redirected) {
window.location.href = response.url;
return;
}
if (!response.ok) {
readerStatus.textContent = jsLocalizedStrings.readFailed;
return;
}
const jsonResponse = await response.json();
if (!jsonResponse.success) {
// The manifest endpoint reports the absence of a book reader, or its disabled state, with distinct error codes, so
// that the user is told what must be fixed to read the book instead of being shown a generic failure. The reading page
// cannot display anything for such a book, so the user is also sent back to the library page of the book, using the same
// AJAX navigation as the nav-links, so that the page is not reloaded (and the audio player is not interrupted).
if (jsonResponse.errorCode === 'NoReaderAvailable') {
readerStatus.textContent = jsLocalizedStrings.readerUnavailable;
notificationService.show(jsLocalizedStrings.readerUnavailable, NotificationType.WARNING);
await redirectToLibraryPageAsync();
} else if (jsonResponse.errorCode === 'ReaderDisabled') {
readerStatus.textContent = jsLocalizedStrings.readerDisabled;
notificationService.show(jsLocalizedStrings.readerDisabled, NotificationType.WARNING);
await redirectToLibraryPageAsync();
} else
readerStatus.textContent = jsLocalizedStrings.readFailed;
return;
}
const manifestResponse = jsonResponse.data;
if (!manifestResponse) {
readerStatus.textContent = jsLocalizedStrings.readFailed;
return;
}
manifest = manifestResponse;
readerTitle.textContent = manifest.title || '';
renderTableOfContents(manifest.tableOfContents || []);
if (manifest.spine && manifest.spine.length > 0)
await goToIndexAsync(0);
else
readerStatus.textContent = jsLocalizedStrings.readFailed;
// A scanned PDF has no text layer, so its pages are empty unless they are rendered as images; when the user has not
// enabled the render-as-images setting, the book cannot be displayed, so the user is told that the setting exists and
// is sent back to the library page, exactly like a book whose reader is not available or not enabled.
if (manifest.hasTextContent === false)
await notifyIfPdfImageOnlyAsync();
}
// Warns the user when the book is a PDF whose pages could not be displayed because they have no extractable text and the
// render-as-images setting is off, since enabling that setting is the way to make such a book readable, and navigates back
// to the library page, because the reading page cannot display anything for such a book.
async function notifyIfPdfImageOnlyAsync() {
const settings = await callApiGetAsync('@_urlService.GetAbsoluteUrl(WebRoutes.Settings.GET_USER_SETTINGS)');
if (settings && settings.shouldRenderPdfAsImages !== true) {
notificationService.show(jsLocalizedStrings.imageOnlyPdf, NotificationType.WARNING);
await redirectToLibraryPageAsync();
}
}
// Navigates back to the library page of the book, using the same AJAX navigation as the nav-links, so that the page is not
// reloaded (and, for example, the audio player is not interrupted); the library page is the one the book was opened from,
// and it is the only page that makes sense for a book whose reader is not available or not enabled.
async function redirectToLibraryPageAsync() {
const response = await fetch(availabilityUrl, {
headers: {
'Accept': 'application/json',
'X-Requested-With': 'XMLHttpRequest'
}
});
if (!response.ok)
return;
const jsonResponse = await response.json();
if (jsonResponse.libraryId) {
const libraryUrl = `${libraryIndexUrl}?libraryId=${encodeURIComponent(jsonResponse.libraryId)}`;
await updateContentAsync(libraryUrl, true);
}
}
// Opens the reading section at the given spine index.
async function goToIndexAsync(index) {
if (!manifest || index < 0 || index >= manifest.spine.length)
return;
currentIndex = index;
// The status line lives outside the content container, so that replacing the section content cannot destroy it; it is
// shown while a section loads and hidden once the section is rendered, and a failing section load leaves it visible with
// the failure message.
readerStatus.classList.remove('hidden');
readerStatus.textContent = jsLocalizedStrings.loading;
const response = await callApiGetAsync(sectionUrlTemplate + encodeURIComponent(manifest.spine[index].locationRef));
if (!response) {
readerStatus.textContent = jsLocalizedStrings.readFailed;
return;
}
readerContent.innerHTML = response.contentHtml || '';
resolveResources();
updatePosition();
readerStatus.classList.add('hidden');
}
// Resolves the resource marker attributes of the rendered content, pointing them at the reading resource endpoint.
function resolveResources() {
readerContent.querySelectorAll('[data-lumina-resource]').forEach(element => {
const key = element.getAttribute('data-lumina-resource');
if (!key)
return;
if (element.tagName === 'IMG' || element.tagName === 'SOURCE' || element.tagName === 'VIDEO' || element.tagName === 'AUDIO')
element.setAttribute('src', resourceUrlTemplate + encodeURIComponent(key));
else if (element.tagName === 'A')
element.addEventListener('click', event => {
event.preventDefault();
navigateToLocation(key);
});
});
}
// Navigates to the reading section identified by the location reference, when it is part of the spine.
function navigateToLocation(locationRef) {
const index = manifest.spine.findIndex(item => item.locationRef === locationRef);
if (index >= 0)
goToIndexAsync(index);
}
// Updates the position label with the current reading section index.
function updatePosition() {
if (!manifest || manifest.spine.length === 0)
readerPosition.textContent = '';
else
readerPosition.textContent = `${currentIndex + 1} / ${manifest.spine.length}`;
}
// Renders the table of contents of the book into the table of contents panel.
function renderTableOfContents(entries) {
tocList.innerHTML = entries.map(entry => renderTableOfContentsEntry(entry)).join('');
}
// Renders a table of contents entry, recursively rendering its children; the label and the location reference are escaped so
// that a book cannot inject markup or break out of the data-location-ref attribute.
function renderTableOfContentsEntry(entry) {
const children = entry.children && entry.children.length > 0
? '<ul>' + entry.children.map(child => renderTableOfContentsEntry(child)).join('') + '</ul>'
: '';
return `<li><a href="#" data-location-ref="${escapeHtml(entry.locationRef || '')}">${escapeHtml(entry.label || '')}</a>${children}</li>`;
}
// Toggles the visibility of the table of contents panel.
function handleTocToggleClick() {
tocPanel.classList.toggle('hidden');
}
// On table of contents entry click, navigates to the reading section.
function handleTocClick(event) {
const anchor = event.target.closest('a[data-location-ref]');
if (!anchor)
return;
event.preventDefault();
navigateToLocation(anchor.getAttribute('data-location-ref'));
}
// On back button click, returns to the previous page.
function handleBackClick() {
window.history.back();
}
// On previous button click, opens the previous reading section.
function handlePrevClick() {
goToIndexAsync(currentIndex - 1);
}
// On next button click, opens the next reading section.
function handleNextClick() {
goToIndexAsync(currentIndex + 1);
}
// Applies the current font size to the reading content.
function applyFontSize() {
readerContent.style.fontSize = `${fontSize}px`;
}
// On font size decrease button click, decreases the font size of the reading content.
function handleFontDecreaseClick() {
fontSize = Math.max(12, fontSize - 2);
applyFontSize();
}
// On font size increase button click, increases the font size of the reading content.
function handleFontIncreaseClick() {
fontSize = Math.min(32, fontSize + 2);
applyFontSize();
}
// Add listeners.
btnBack.addEventListener('click', handleBackClick);
btnTocToggle.addEventListener('click', handleTocToggleClick);
tocList.addEventListener('click', handleTocClick);
btnPrev.addEventListener('click', handlePrevClick);
btnNext.addEventListener('click', handleNextClick);
btnFontDecrease.addEventListener('click', handleFontDecreaseClick);
btnFontIncrease.addEventListener('click', handleFontIncreaseClick);
document.addEventListener('DOMContentLoaded', InitializeAsync);
// Register cleanup for these listeners.
cleanupFunctions.push(() => {
btnBack.removeEventListener('click', handleBackClick);
btnTocToggle.removeEventListener('click', handleTocToggleClick);
tocList.removeEventListener('click', handleTocClick);
btnPrev.removeEventListener('click', handlePrevClick);
btnNext.removeEventListener('click', handleNextClick);
btnFontDecrease.removeEventListener('click', handleFontDecreaseClick);
btnFontIncrease.removeEventListener('click', handleFontIncreaseClick);
document.removeEventListener('DOMContentLoaded', InitializeAsync);
});
// Initializes the reader, loading the reading manifest of the book; the DOMContentLoaded listener covers the initial
// full page load, while the site.js script processor invokes InitializeAsync directly after an AJAX navigation, when
// the DOMContentLoaded event has already fired.
async function InitializeAsync() {
if (isInitialized)
return;
isInitialized = true;
await loadManifestAsync();
}
// Store all cleanups for this view on window object using the scriptId.
window.viewCleanups = window.viewCleanups || {};
window.viewCleanups['@scriptId'] = () => {
cleanupFunctions.forEach(cleanup => cleanup());
console.log(`Unloaded @scriptId`);
};
console.log(`Loaded @scriptId`);
</script>
}
@@ -7,7 +7,7 @@
@using Microsoft.AspNetCore.Mvc.Localization
@{
// generate a unique id for the scripts section of this view, so it can be dynamically loaded/unloaded by the global AJAX navigator handler
// Generate a unique id for the scripts section of this view, so it can be dynamically loaded/unloaded by the global AJAX navigator handler.
var scriptId = ScriptIdentifierHelper.GenerateScriptId();
}
@@ -16,8 +16,8 @@
@model UserSettingsDto
<div style="display: grid; grid-template-rows: auto 1fr;"><!--container with two rows, one fixed, one filling remaining space-->
<div style="min-height: 1rem;"></div><!--the first row is a dummy row for "margin", because setting a margin on the next row would offset the parent's position-->
<div style="display: grid; grid-template-rows: auto 1fr;"><!--Container with two rows, one fixed, one filling remaining space.-->
<div style="min-height: 1rem;"></div><!--The first row is a dummy row for "margin", because setting a margin on the next row would offset the parent's position.-->
<div class="enlightenment-panel shadow-effect mx-auto panel w-50 mb-10" style="min-width: 320px;">
<div class="shine-effect"></div>
<form method="post" id="user-settings-form" class="inline">
@@ -28,7 +28,7 @@
</h1>
</div>
<div class="form-container">
<!-- Pagination -->
<!-- Pagination. -->
<div class="form-row">
<div class="form-label">
<label asp-for="IsPaginationEnabled">@_localizer["EnablePagination"]</label>:
@@ -41,7 +41,7 @@
</div>
<small class="form-label text-disabled form-description">@_localizer["DescriptionEnablePagination"]</small>
</div>
<!-- Items per page -->
<!-- Items per page. -->
<div class="form-row">
<div class="form-label">
<label asp-for="ItemsPerPage">@_localizer["ItemsPerPage"]</label>
@@ -65,7 +65,7 @@
</div>
<small class="form-label text-disabled form-description">@_localizer["DescriptionShouldIgnoreThePrefixForAlphaPicker"]</small>
</div>
<!-- Theme caching -->
<!-- Theme caching. -->
<div class="form-row">
<div class="form-label">
<label asp-for="IsThemeCachingEnabled">@_localizer["EnableThemeCaching"]</label>:
@@ -78,6 +78,32 @@
</div>
<small class="form-label text-disabled form-description">@_localizer["DescriptionEnableThemeCaching"]</small>
</div>
<!-- Render PDFs as images. -->
<div class="form-row">
<div class="form-label">
<label asp-for="ShouldRenderPdfAsImages">@_localizer["ShouldRenderPdfAsImages"]</label>:
</div>
<div class="form-field">
<label class="enlightenment-checkbox-label">
<input type="checkbox" asp-for="ShouldRenderPdfAsImages" class="enlightenment-checkbox-hidden" />
<span class="enlightenment-checkbox"></span>
</label>
</div>
<small class="form-label text-disabled form-description">@_localizer["DescriptionShouldRenderPdfAsImages"]</small>
</div>
<!-- Preserve book styles. -->
<div class="form-row">
<div class="form-label">
<label asp-for="ShouldPreserveBookStyles">@_localizer["ShouldPreserveBookStyles"]</label>:
</div>
<div class="form-field">
<label class="enlightenment-checkbox-label">
<input type="checkbox" asp-for="ShouldPreserveBookStyles" class="enlightenment-checkbox-hidden" />
<span class="enlightenment-checkbox"></span>
</label>
</div>
<small class="form-label text-disabled form-description">@_localizer["DescriptionShouldPreserveBookStyles"]</small>
</div>
<div class="form-row" style="justify-content: center;">
<button type="submit" class="confirm-button h-22px">@_localizer["Save"]</button>
</div>
@@ -88,7 +114,7 @@
@section Scripts {
<!-- The "text/plain" type is a design choice, not a mistake: it keeps the browser from executing this view script during HTML parsing, before site.js defines the API helpers it calls (callApiGetAsync, callApiPostAsync, ...). site.js (which loads deferred) executes these scripts once it is loaded, both on the initial page load and during AJAX navigation. -->
<script type="text/plain" data-form="@scriptId">
// create cleanup registry for this view
// Create cleanup registry for this view.
const cleanupFunctions = [];
let isInitialized = false;
@@ -97,14 +123,16 @@
const inputItemsPerPage = document.getElementById('ItemsPerPage');
const checkboxShouldIgnoreThePrefixForAlphaPicker = document.getElementById('ShouldIgnoreThePrefixForAlphaPicker');
const checkboxIsThemeCachingEnabled = document.getElementById('IsThemeCachingEnabled');
const checkboxShouldRenderPdfAsImages = document.getElementById('ShouldRenderPdfAsImages');
const checkboxShouldPreserveBookStyles = document.getElementById('ShouldPreserveBookStyles');
let shouldAggregateMetadataWhenMissing = false;
// toggle the enabled state of the items per page input based on the pagination checkbox
// Toggle the enabled state of the items per page input based on the pagination checkbox.
function updateItemsPerPageEnabledState() {
inputItemsPerPage.disabled = !checkboxIsPaginationEnabled.checked;
}
// load the settings of the current user
// Load the settings of the current user.
async function loadUserSettingsAsync() {
const data = await callApiGetAsync('@_urlService.GetAbsoluteUrl(WebRoutes.Settings.GET_USER_SETTINGS)');
if (data) {
@@ -112,42 +140,46 @@
inputItemsPerPage.value = data.itemsPerPage;
checkboxShouldIgnoreThePrefixForAlphaPicker.checked = data.shouldIgnoreThePrefixForAlphaPicker === true;
checkboxIsThemeCachingEnabled.checked = data.isThemeCachingEnabled === true;
checkboxShouldRenderPdfAsImages.checked = data.shouldRenderPdfAsImages === true;
checkboxShouldPreserveBookStyles.checked = data.shouldPreserveBookStyles === true;
shouldAggregateMetadataWhenMissing = data.shouldAggregateMetadataWhenMissing === true;
updateItemsPerPageEnabledState();
}
}
// save the settings of the current user
// Save the settings of the current user.
async function handleSaveUserSettingsAsync() {
const formData = {
IsPaginationEnabled: checkboxIsPaginationEnabled.checked,
ItemsPerPage: Number(inputItemsPerPage.value),
ShouldIgnoreThePrefixForAlphaPicker: checkboxShouldIgnoreThePrefixForAlphaPicker.checked,
IsThemeCachingEnabled: checkboxIsThemeCachingEnabled.checked,
ShouldAggregateMetadataWhenMissing: shouldAggregateMetadataWhenMissing
ShouldAggregateMetadataWhenMissing: shouldAggregateMetadataWhenMissing,
ShouldRenderPdfAsImages: checkboxShouldRenderPdfAsImages.checked,
ShouldPreserveBookStyles: checkboxShouldPreserveBookStyles.checked
};
const data = await callApiPostAsync('@_urlService.GetAbsoluteUrl(WebRoutes.Settings.UPDATE_USER_SETTINGS)', formData);
if (data && data.isUpdated === true)
notificationService.show('@_localizer["SettingsSaved"]', NotificationType.SUCCESS);
}
// on form submit event
// On form submit event.
const handleSubmit = async function(e) {
e.preventDefault();
await handleSaveUserSettingsAsync();
};
// on pagination checkbox change, update the enabled state of the items per page input
// On pagination checkbox change, update the enabled state of the items per page input.
const handlePaginationCheckboxChange = function() {
updateItemsPerPageEnabledState();
};
// add listeners
// Add listeners.
form.addEventListener('submit', handleSubmit);
checkboxIsPaginationEnabled.addEventListener('change', handlePaginationCheckboxChange);
document.addEventListener('DOMContentLoaded', InitializeAsync);
// register cleanup for these listeners
// Register cleanup for these listeners.
cleanupFunctions.push(() => {
form.removeEventListener('submit', handleSubmit);
checkboxIsPaginationEnabled.removeEventListener('change', handlePaginationCheckboxChange);
@@ -161,7 +193,7 @@
await loadUserSettingsAsync();
}
// store all cleanups for this view on window object using the scriptId
// Store all cleanups for this view on window object using the scriptId.
window.viewCleanups = window.viewCleanups || {};
window.viewCleanups['@scriptId'] = () => {
cleanupFunctions.forEach(cleanup => cleanup());