multi language support for books and book page redesigned

This commit is contained in:
2025-12-31 17:57:33 +01:00
parent 20261159a4
commit 1e144c4bad
14 changed files with 1687 additions and 1917 deletions

View File

@@ -1,3 +1,7 @@
// reader.js refactorizado
const urlParams = new URLSearchParams(window.location.search);
const lang = urlParams.get('lang') ?? 'none';
const reader = document.getElementById('reader');
const panel = document.getElementById('settings-panel');
const overlay = document.getElementById('overlay');
@@ -33,11 +37,12 @@ let currentType = null;
let currentPages = [];
let observer = null;
// === CAMBIO: Parseo de URL para obtener ID ===
const parts = window.location.pathname.split('/');
const bookId = parts[4];
let chapter = parts[3];
let currentChapterId = parts[3]; // Ahora es un ID (string)
let provider = parts[2];
let chaptersList = []; // Buffer para guardar el orden de capítulos
function loadConfig() {
try {
@@ -116,6 +121,31 @@ function updateSettingsVisibility() {
mangaSettings.classList.toggle('hidden', currentType !== 'manga');
}
// === CAMBIO: Nueva función para traer la lista de capítulos y saber el orden ===
async function fetchChapterList() {
const urlParams = new URLSearchParams(window.location.search);
const source = urlParams.get('source') || 'anilist';
try {
// Reusamos el endpoint que lista capítulos
const res = await fetch(`/api/book/${bookId}/chapters?source=${source}&provider=${provider}`);
const data = await res.json();
// Ordenamos por número para asegurar navegación correcta
let list = data.chapters || [];
list.sort((a, b) => Number(a.number) - Number(b.number));
// Si hay filtro de idioma en la URL, filtramos la navegación también
if (lang !== 'none') {
list = list.filter(c => c.language === lang);
}
chaptersList = list;
} catch (e) {
console.error("Error fetching chapter list:", e);
}
}
async function loadChapter() {
reader.innerHTML = `
<div class="loading-container">
@@ -126,23 +156,35 @@ async function loadChapter() {
const urlParams = new URLSearchParams(window.location.search);
let source = urlParams.get('source');
if (!source) {
source = 'anilist';
if (!source) source = 'anilist';
// === CAMBIO: Si no tenemos la lista de capítulos (y no es local), la pedimos ===
if (provider !== 'local' && chaptersList.length === 0) {
await fetchChapterList();
}
let newEndpoint;
if (provider === 'local') {
newEndpoint = `/api/library/${bookId}/units`;
} else {
newEndpoint = `/api/book/${bookId}/${chapter}/${provider}?source=${source}`;
// === CAMBIO: Usamos currentChapterId en la URL ===
newEndpoint = `/api/book/${bookId}/${currentChapterId}/${provider}?source=${source}&lang=${lang}`;
}
try {
const res = await fetch(newEndpoint);
const data = await res.json();
// Lógica específica para contenido LOCAL
if (provider === 'local') {
const unit = data.units[Number(chapter)];
if (!unit) return;
const unitIndex = Number(currentChapterId); // En local el ID suele ser el índice
const unit = data.units[unitIndex];
if (!unit) {
reader.innerHTML = '<div class="loading-container"><span>Chapter not found (Local)</span></div>';
return;
}
chapterLabel.textContent = unit.name;
document.title = unit.name;
@@ -152,50 +194,46 @@ async function loadChapter() {
reader.innerHTML = '';
// ===== MANGA =====
// Setup navegación manual para local (simple index +/- 1)
setupLocalNavigation(unitIndex, data.units.length);
if (manifest.type === 'manga') {
currentType = 'manga';
updateSettingsVisibility();
applyStyles();
currentPages = manifest.pages;
loadManga(currentPages);
return;
}
// ===== LN =====
if (manifest.type === 'ln') {
currentType = 'ln';
updateSettingsVisibility();
applyStyles();
const contentRes = await fetch(manifest.url);
const html = await contentRes.text();
loadLN(html);
return;
}
}
// Lógica para Extensiones / Anilist
if (data.error) {
reader.innerHTML = `<div class="loading-container"><span style="color: #ef4444;">Error: ${data.error}</span></div>`;
return;
}
if (data.title) {
chapterLabel.textContent = data.title;
document.title = data.title;
} else {
chapterLabel.textContent = `Chapter ${chapter}`;
document.title = `Chapter ${chapter}`;
chapterLabel.textContent = `Chapter ${data.number ?? currentChapterId}`;
document.title = `Chapter ${data.number ?? currentChapterId}`;
}
setupProgressTracking(data, source);
if (data.error) {
reader.innerHTML = `
<div class="loading-container">
<span style="color: #ef4444;">Error: ${data.error}</span>
</div>
`;
return;
}
// === CAMBIO: Actualizar botones basado en IDs ===
updateNavigationButtons();
currentType = data.type;
updateSettingsVisibility();
@@ -209,6 +247,7 @@ async function loadChapter() {
loadLN(data.content);
}
} catch (error) {
console.error(error);
reader.innerHTML = `
<div class="loading-container">
<span style="color: #ef4444;">Error loading chapter: ${error.message}</span>
@@ -217,6 +256,87 @@ async function loadChapter() {
}
}
// === CAMBIO: Lógica de navegación basada en IDs ===
function updateNavigationButtons() {
if (provider === 'local') return; // Se maneja aparte
// Buscamos el índice actual en la lista completa
const currentIndex = chaptersList.findIndex(c => String(c.id) === String(currentChapterId));
if (currentIndex === -1) {
console.warn("Current chapter not found in list, navigation disabled");
prevBtn.disabled = true;
nextBtn.disabled = true;
prevBtn.style.opacity = 0.5;
nextBtn.style.opacity = 0.5;
return;
}
// Configurar botón ANTERIOR
if (currentIndex > 0) {
const prevId = chaptersList[currentIndex - 1].id;
prevBtn.onclick = () => changeChapter(prevId);
prevBtn.disabled = false;
prevBtn.style.opacity = 1;
} else {
prevBtn.onclick = null;
prevBtn.disabled = true;
prevBtn.style.opacity = 0.5;
}
// Configurar botón SIGUIENTE
if (currentIndex < chaptersList.length - 1) {
const nextId = chaptersList[currentIndex + 1].id;
nextBtn.onclick = () => changeChapter(nextId);
nextBtn.disabled = false;
nextBtn.style.opacity = 1;
} else {
nextBtn.onclick = null;
nextBtn.disabled = true;
nextBtn.style.opacity = 0.5;
}
}
// Fallback para navegación local (basada en índices)
function setupLocalNavigation(currentIndex, totalUnits) {
if (currentIndex > 0) {
prevBtn.onclick = () => changeChapter(currentIndex - 1);
prevBtn.disabled = false;
prevBtn.style.opacity = 1;
} else {
prevBtn.disabled = true;
prevBtn.style.opacity = 0.5;
}
if (currentIndex < totalUnits - 1) {
nextBtn.onclick = () => changeChapter(currentIndex + 1);
nextBtn.disabled = false;
nextBtn.style.opacity = 1;
} else {
nextBtn.disabled = true;
nextBtn.style.opacity = 0.5;
}
}
// === CAMBIO: Función helper para cambiar de capítulo ===
function changeChapter(newId) {
currentChapterId = newId;
updateURL(newId);
window.scrollTo(0, 0);
loadChapter();
}
function updateURL(newId) {
const urlParams = new URLSearchParams(window.location.search);
const source = urlParams.get('source') ?? 'anilist';
// La URL ahora contiene el ID en lugar del número/índice
const newUrl = `/read/${provider}/${newId}/${bookId}?source=${source}&lang=${lang}`;
window.history.pushState({}, '', newUrl);
}
// --- Resto de funciones UI (Manga/LN loading) sin cambios lógicos mayores ---
function loadManga(pages) {
if (!pages || pages.length === 0) {
reader.innerHTML = '<div class="loading-container"><span>No pages found</span></div>';
@@ -227,7 +347,6 @@ function loadManga(pages) {
container.className = 'manga-container';
let isLongStrip = false;
if (config.manga.mode === 'longstrip') {
isLongStrip = true;
} else if (config.manga.mode === 'auto' && detectLongStrip(pages)) {
@@ -250,15 +369,12 @@ function loadManga(pages) {
function shouldUseDoublePage(pages) {
if (pages.length <= 5) return false;
const widePages = pages.filter(p => {
if (!p.height || !p.width) return false;
const ratio = p.width / p.height;
return ratio > 1.3;
});
if (widePages.length > pages.length * 0.3) return false;
return true;
}
@@ -298,7 +414,6 @@ function loadDoublePage(container, pages) {
i++;
} else {
const rightPage = createImageElement(nextPage, i + 1);
if (config.manga.direction === 'rtl') {
doubleContainer.appendChild(rightPage);
doubleContainer.appendChild(leftPage);
@@ -306,7 +421,6 @@ function loadDoublePage(container, pages) {
doubleContainer.appendChild(leftPage);
doubleContainer.appendChild(rightPage);
}
container.appendChild(doubleContainer);
i += 2;
}
@@ -349,31 +463,23 @@ function createImageElement(page, index) {
img.dataset.src = url;
img.loading = 'lazy';
}
img.alt = `Page ${index + 1}`;
return img;
}
function buildProxyUrl(url, headers = {}) {
const params = new URLSearchParams({ url });
if (headers.Referer || headers.referer)
params.append("referer", headers.Referer || headers.referer);
if (headers["User-Agent"] || headers["user-agent"])
params.append("userAgent", headers["User-Agent"] || headers["user-agent"]);
if (headers.Origin || headers.origin)
params.append("origin", headers.Origin || headers.origin);
return `/api/proxy?${params.toString()}`;
}
function detectLongStrip(pages) {
if (!pages || pages.length === 0) return false;
const relevant = pages.slice(1);
const tall = relevant.filter(p => p.height && p.width && (p.height / p.width) > 2);
return tall.length >= 2 || (tall.length / relevant.length) > 0.3;
@@ -381,7 +487,6 @@ function detectLongStrip(pages) {
function setupLazyLoading() {
if (observer) observer.disconnect();
observer = new IntersectionObserver((entries) => {
entries.forEach(entry => {
if (entry.isIntersecting) {
@@ -393,10 +498,7 @@ function setupLazyLoading() {
}
}
});
}, {
rootMargin: '200px'
});
}, { rootMargin: '200px' });
document.querySelectorAll('img[data-src]').forEach(img => observer.observe(img));
}
@@ -407,161 +509,102 @@ function loadLN(html) {
reader.appendChild(div);
}
// Listeners de configuración
document.getElementById('font-size').addEventListener('input', (e) => {
config.ln.fontSize = parseInt(e.target.value);
document.getElementById('font-size-value').textContent = e.target.value + 'px';
applyStyles();
saveConfig();
applyStyles(); saveConfig();
});
document.getElementById('line-height').addEventListener('input', (e) => {
config.ln.lineHeight = parseFloat(e.target.value);
document.getElementById('line-height-value').textContent = e.target.value;
applyStyles();
saveConfig();
applyStyles(); saveConfig();
});
document.getElementById('max-width').addEventListener('input', (e) => {
config.ln.maxWidth = parseInt(e.target.value);
document.getElementById('max-width-value').textContent = e.target.value + 'px';
applyStyles();
saveConfig();
applyStyles(); saveConfig();
});
document.getElementById('font-family').addEventListener('change', (e) => {
config.ln.fontFamily = e.target.value;
applyStyles();
saveConfig();
applyStyles(); saveConfig();
});
document.getElementById('text-color').addEventListener('change', (e) => {
config.ln.textColor = e.target.value;
applyStyles();
saveConfig();
applyStyles(); saveConfig();
});
document.getElementById('bg-color').addEventListener('change', (e) => {
config.ln.bg = e.target.value;
applyStyles();
saveConfig();
applyStyles(); saveConfig();
});
document.querySelectorAll('[data-align]').forEach(btn => {
btn.addEventListener('click', () => {
document.querySelectorAll('[data-align]').forEach(b => b.classList.remove('active'));
btn.classList.add('active');
config.ln.textAlign = btn.dataset.align;
applyStyles();
saveConfig();
applyStyles(); saveConfig();
});
});
document.querySelectorAll('[data-preset]').forEach(btn => {
btn.addEventListener('click', () => {
const preset = btn.dataset.preset;
const presets = {
dark: { bg: '#14141b', textColor: '#e5e7eb' },
sepia: { bg: '#f4ecd8', textColor: '#5c472d' },
light: { bg: '#fafafa', textColor: '#1f2937' },
amoled: { bg: '#000000', textColor: '#ffffff' }
};
if (presets[preset]) {
Object.assign(config.ln, presets[preset]);
document.getElementById('bg-color').value = config.ln.bg;
document.getElementById('text-color').value = config.ln.textColor;
applyStyles();
saveConfig();
applyStyles(); saveConfig();
}
});
});
document.getElementById('display-mode').addEventListener('change', (e) => {
config.manga.mode = e.target.value;
saveConfig();
loadChapter();
saveConfig(); loadChapter();
});
document.getElementById('image-fit').addEventListener('change', (e) => {
config.manga.imageFit = e.target.value;
saveConfig();
loadChapter();
saveConfig(); loadChapter();
});
document.getElementById('page-spacing').addEventListener('input', (e) => {
config.manga.spacing = parseInt(e.target.value);
document.getElementById('page-spacing-value').textContent = e.target.value + 'px';
applyStyles();
saveConfig();
applyStyles(); saveConfig();
});
document.getElementById('preload-count').addEventListener('change', (e) => {
config.manga.preloadCount = parseInt(e.target.value);
saveConfig();
});
document.querySelectorAll('[data-direction]').forEach(btn => {
btn.addEventListener('click', () => {
document.querySelectorAll('[data-direction]').forEach(b => b.classList.remove('active'));
btn.classList.add('active');
config.manga.direction = btn.dataset.direction;
saveConfig();
loadChapter();
saveConfig(); loadChapter();
});
});
prevBtn.addEventListener('click', () => {
const current = parseInt(chapter);
if (current <= 0) return;
const newChapter = String(current - 1);
updateURL(newChapter);
window.scrollTo(0, 0);
loadChapter();
});
nextBtn.addEventListener('click', () => {
const newChapter = String(parseInt(chapter) + 1);
updateURL(newChapter);
window.scrollTo(0, 0);
loadChapter();
});
function updateURL(newChapter) {
chapter = newChapter;
const urlParams = new URLSearchParams(window.location.search);
let source = urlParams.get('source');
let src;
if (source === 'anilist') {
src= "?source=anilist"
} else {
src= `?source=${source}`
}
const newUrl = `/read/${provider}/${chapter}/${bookId}${src}`;
window.history.pushState({}, '', newUrl);
}
// Botón "Atrás"
document.getElementById('back-btn').addEventListener('click', () => {
const parts = window.location.pathname.split('/');
const mangaId = parts[4];
const urlParams = new URLSearchParams(window.location.search);
let source = urlParams.get('source');
let source = urlParams.get('source')?.split('?')[0];
if (source === 'anilist') {
window.location.href = `/book/${mangaId}`;
if (source === 'anilist' || !source) {
window.location.href = `/book/${bookId}`;
} else {
window.location.href = `/book/${source}/${mangaId}`;
window.location.href = `/book/${source}/${bookId}`;
}
});
// Panel de configuración
settingsBtn.addEventListener('click', () => {
panel.classList.add('open');
overlay.classList.add('active');
});
closePanel.addEventListener('click', closeSettings);
overlay.addEventListener('click', closeSettings);
@@ -569,7 +612,6 @@ function closeSettings() {
panel.classList.remove('open');
overlay.classList.remove('active');
}
document.addEventListener('keydown', (e) => {
if (e.key === 'Escape' && panel.classList.contains('open')) {
closeSettings();
@@ -579,37 +621,24 @@ document.addEventListener('keydown', (e) => {
function enableMangaPageNavigation() {
if (currentType !== 'manga') return;
const logicalPages = [];
document.querySelectorAll('.manga-container > *').forEach(el => {
if (el.classList.contains('double-container')) {
logicalPages.push(el);
} else if (el.tagName === 'IMG') {
if (el.classList.contains('double-container') || el.tagName === 'IMG') {
logicalPages.push(el);
}
});
if (logicalPages.length === 0) return;
function scrollToLogical(index) {
if (index < 0 || index >= logicalPages.length) return;
const topBar = document.querySelector('.top-bar');
const offset = topBar ? -topBar.offsetHeight : 0;
const y = logicalPages[index].getBoundingClientRect().top
+ window.pageYOffset
+ offset;
window.scrollTo({
top: y,
behavior: 'smooth'
});
const y = logicalPages[index].getBoundingClientRect().top + window.pageYOffset + offset;
window.scrollTo({ top: y, behavior: 'smooth' });
}
function getCurrentLogicalIndex() {
let closest = 0;
let minDist = Infinity;
logicalPages.forEach((el, i) => {
const rect = el.getBoundingClientRect();
const dist = Math.abs(rect.top);
@@ -618,53 +647,36 @@ function enableMangaPageNavigation() {
closest = i;
}
});
return closest;
}
const rtl = () => config.manga.direction === 'rtl';
document.addEventListener('keydown', (e) => {
if (currentType !== 'manga') return;
if (e.target.tagName === 'INPUT' || e.target.tagName === 'SELECT') return;
const index = getCurrentLogicalIndex();
if (e.key === 'ArrowLeft') {
scrollToLogical(rtl() ? index + 1 : index - 1);
}
if (e.key === 'ArrowRight') {
scrollToLogical(rtl() ? index - 1 : index + 1);
}
if (e.key === 'ArrowLeft') scrollToLogical(rtl() ? index + 1 : index - 1);
if (e.key === 'ArrowRight') scrollToLogical(rtl() ? index - 1 : index + 1);
});
reader.addEventListener('click', (e) => {
if (currentType !== 'manga') return;
const bounds = reader.getBoundingClientRect();
const x = e.clientX - bounds.left;
const half = bounds.width / 2;
const index = getCurrentLogicalIndex();
if (x < half) {
scrollToLogical(rtl() ? index + 1 : index - 1);
} else {
scrollToLogical(rtl() ? index - 1 : index + 1);
}
if (x < half) scrollToLogical(rtl() ? index + 1 : index - 1);
else scrollToLogical(rtl() ? index - 1 : index + 1);
});
}
let resizeTimer;
window.addEventListener('resize', () => {
clearTimeout(resizeTimer);
resizeTimer = setTimeout(() => {
applyStyles();
}, 250);
resizeTimer = setTimeout(() => { applyStyles(); }, 250);
});
let progressSaved = false;
function setupProgressTracking(data, source) {
progressSaved = false;
@@ -677,25 +689,16 @@ function setupProgressTracking(data, source) {
source: source,
entry_type: data.type === 'manga' ? 'MANGA' : 'NOVEL',
status: 'CURRENT',
progress: source === 'anilist'
? Math.floor(chapterNumber)
: chapterNumber
progress: source === 'anilist' ? Math.floor(chapterNumber) : chapterNumber
};
try {
await fetch('/api/list/entry', {
method: 'POST',
headers: {
'Content-Type': 'application/json',
'Authorization': `Bearer ${token}`
},
headers: { 'Content-Type': 'application/json', 'Authorization': `Bearer ${token}` },
body: JSON.stringify(body)
});
} catch (err) {
console.error('Error updating progress:', err);
}
} catch (err) { console.error('Error updating progress:', err); }
}
function checkProgress() {
@@ -705,25 +708,24 @@ function setupProgressTracking(data, source) {
if (percent >= 0.8 && !progressSaved) {
progressSaved = true;
// Usamos el número real del capítulo, no el ID
const chapterNumber = (typeof data.number !== 'undefined' && data.number !== null)
? data.number
: Number(chapter);
: 0; // Fallback si no hay numero
sendProgress(chapterNumber);
window.removeEventListener('scroll', checkProgress);
}
}
window.removeEventListener('scroll', checkProgress);
window.addEventListener('scroll', checkProgress);
}
if (!bookId || !chapter || !provider) {
// Inicialización
if (!bookId || !currentChapterId || !provider) {
reader.innerHTML = `
<div class="loading-container">
<span style="color: #ef4444;">Missing required parameters (bookId, chapter, provider)</span>
<span style="color: #ef4444;">Missing required parameters (bookId, chapterId, provider)</span>
</div>
`;
} else {