refactor: Convert book viewer to idiomatic React
Replace the SSR + injected vanilla-JS navigation script with a proper client-side React app. BookIndex now uses useState/useEffect/useCallback for all navigation state, scroll tracking, keyboard shortcuts, and history management. webpack.config.js switches from renderToStaticMarkup to embedding page data as window.__BOOK_DATA__ JSON; book.js becomes a createRoot entry point. Also adds babel-loader for JSX bundling, fixes #root display:contents so the flex height chain is preserved, and restores missing CSS for header, .logo, .toolbar, and .tab buttons. Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
This commit is contained in:
@@ -1,153 +1,162 @@
|
||||
import React from 'react';
|
||||
|
||||
function buildScript(pageNums) {
|
||||
return `
|
||||
const PAGES = [${pageNums.join(',')}];
|
||||
const total = PAGES.length;
|
||||
let currentIdx = 0;
|
||||
|
||||
const content = document.getElementById('content');
|
||||
const btnPrev = document.getElementById('btn-prev');
|
||||
const btnNext = document.getElementById('btn-next');
|
||||
const indicator = document.getElementById('page-indicator');
|
||||
const titleEl = document.getElementById('page-title');
|
||||
|
||||
function updateNav(idx, push) {
|
||||
if (idx === currentIdx && indicator.textContent) return;
|
||||
currentIdx = idx;
|
||||
const n = PAGES[idx];
|
||||
indicator.textContent = (idx + 1) + ' / ' + total;
|
||||
titleEl.textContent = 'Page ' + n;
|
||||
btnPrev.disabled = idx === 0;
|
||||
btnNext.disabled = idx === total - 1;
|
||||
document.querySelectorAll('#page-list li').forEach(li => {
|
||||
li.classList.toggle('active', Number(li.dataset.page) === n);
|
||||
});
|
||||
document.querySelector('#page-list li[data-page="' + n + '"]')
|
||||
?.scrollIntoView({ block: 'nearest' });
|
||||
if (push) history.pushState(null, '', '#page-' + n);
|
||||
else history.replaceState(null, '', '#page-' + n);
|
||||
}
|
||||
|
||||
function goTo(n, smooth, push) {
|
||||
const idx = PAGES.indexOf(n);
|
||||
if (idx === -1) return;
|
||||
const sec = document.getElementById('page-' + n);
|
||||
if (!sec) return;
|
||||
sec.scrollIntoView({ behavior: smooth ? 'smooth' : 'instant', block: 'start' });
|
||||
updateNav(idx, push);
|
||||
}
|
||||
|
||||
btnPrev.addEventListener('click', () => { if (currentIdx > 0) goTo(PAGES[currentIdx - 1], true, true); });
|
||||
btnNext.addEventListener('click', () => { if (currentIdx < total - 1) goTo(PAGES[currentIdx + 1], true, true); });
|
||||
|
||||
document.getElementById('page-list').addEventListener('click', e => {
|
||||
const li = e.target.closest('li[data-page]');
|
||||
if (li) goTo(Number(li.dataset.page), false, true);
|
||||
});
|
||||
|
||||
document.addEventListener('keydown', e => {
|
||||
if (e.target.tagName === 'INPUT' || e.target.tagName === 'TEXTAREA') return;
|
||||
if (e.key === 'ArrowLeft' || e.key === 'ArrowUp') { if (currentIdx > 0) goTo(PAGES[currentIdx - 1], true, true); }
|
||||
if (e.key === 'ArrowRight' || e.key === 'ArrowDown') { if (currentIdx < total - 1) goTo(PAGES[currentIdx + 1], true, true); }
|
||||
});
|
||||
|
||||
// Track current page by scroll position (replaceState — no new history entry)
|
||||
content.addEventListener('scroll', () => {
|
||||
const containerTop = content.getBoundingClientRect().top;
|
||||
let found = 0;
|
||||
for (let i = 0; i < PAGES.length; i++) {
|
||||
const sec = document.getElementById('page-' + PAGES[i]);
|
||||
if (sec && sec.getBoundingClientRect().top - containerTop <= 40) found = i;
|
||||
else break;
|
||||
}
|
||||
if (found !== currentIdx) updateNav(found, false);
|
||||
}, { passive: true });
|
||||
|
||||
// Browser back/forward
|
||||
window.addEventListener('popstate', () => {
|
||||
const pm = location.hash.match(/^#page-(\\d+)$/);
|
||||
if (pm) {
|
||||
const n = parseInt(pm[1], 10);
|
||||
if (PAGES.includes(n)) goTo(n, false, false);
|
||||
}
|
||||
});
|
||||
|
||||
// Initial navigation from URL hash
|
||||
const m = location.hash.match(/^#page-(\\d+)$/);
|
||||
const startPage = m ? parseInt(m[1], 10) : PAGES[0];
|
||||
goTo(PAGES.includes(startPage) ? startPage : PAGES[0], false, false);
|
||||
`;
|
||||
}
|
||||
import React, { useState, useEffect, useRef, useCallback, useMemo } from 'react';
|
||||
|
||||
export default function BookIndex({ title, logoText, pages }) {
|
||||
const pageNums = pages.map(p => p.n);
|
||||
const pageNums = useMemo(() => pages.map(p => p.n), [pages]);
|
||||
const total = pageNums.length;
|
||||
|
||||
const [currentIdx, setCurrentIdx] = useState(() => {
|
||||
const m = window.location.hash.match(/^#page-(\d+)$/);
|
||||
if (m) {
|
||||
const idx = pageNums.indexOf(parseInt(m[1], 10));
|
||||
if (idx !== -1) return idx;
|
||||
}
|
||||
return 0;
|
||||
});
|
||||
|
||||
const contentRef = useRef(null);
|
||||
|
||||
const goTo = useCallback((n, smooth, push) => {
|
||||
const idx = pageNums.indexOf(n);
|
||||
if (idx === -1) return;
|
||||
const sec = document.getElementById(`page-${n}`);
|
||||
if (!sec) return;
|
||||
sec.scrollIntoView({ behavior: smooth ? 'smooth' : 'instant', block: 'start' });
|
||||
setCurrentIdx(idx);
|
||||
if (push) history.pushState(null, '', `#page-${n}`);
|
||||
else history.replaceState(null, '', `#page-${n}`);
|
||||
}, [pageNums]);
|
||||
|
||||
// Scroll active sidebar item into view when page changes
|
||||
useEffect(() => {
|
||||
document.querySelector(`#page-list li[data-page="${pageNums[currentIdx]}"]`)
|
||||
?.scrollIntoView({ block: 'nearest' });
|
||||
}, [currentIdx, pageNums]);
|
||||
|
||||
// Initial scroll to hash page
|
||||
useEffect(() => {
|
||||
const n = pageNums[currentIdx];
|
||||
goTo(n, false, false);
|
||||
}, []); // eslint-disable-line react-hooks/exhaustive-deps
|
||||
|
||||
// Scroll tracking — update currentIdx as user scrolls
|
||||
useEffect(() => {
|
||||
const container = contentRef.current;
|
||||
if (!container) return;
|
||||
const handleScroll = () => {
|
||||
const top = container.getBoundingClientRect().top;
|
||||
let found = 0;
|
||||
for (let i = 0; i < pageNums.length; i++) {
|
||||
const sec = document.getElementById(`page-${pageNums[i]}`);
|
||||
if (sec && sec.getBoundingClientRect().top - top <= 40) found = i;
|
||||
else break;
|
||||
}
|
||||
setCurrentIdx(prev => {
|
||||
if (found === prev) return prev;
|
||||
history.replaceState(null, '', `#page-${pageNums[found]}`);
|
||||
return found;
|
||||
});
|
||||
};
|
||||
container.addEventListener('scroll', handleScroll, { passive: true });
|
||||
return () => container.removeEventListener('scroll', handleScroll);
|
||||
}, [pageNums]);
|
||||
|
||||
// Keyboard navigation
|
||||
useEffect(() => {
|
||||
const handleKeyDown = e => {
|
||||
if (e.target.tagName === 'INPUT' || e.target.tagName === 'TEXTAREA') return;
|
||||
setCurrentIdx(prev => {
|
||||
if ((e.key === 'ArrowLeft' || e.key === 'ArrowUp') && prev > 0) {
|
||||
goTo(pageNums[prev - 1], true, true);
|
||||
}
|
||||
if ((e.key === 'ArrowRight' || e.key === 'ArrowDown') && prev < total - 1) {
|
||||
goTo(pageNums[prev + 1], true, true);
|
||||
}
|
||||
return prev;
|
||||
});
|
||||
};
|
||||
document.addEventListener('keydown', handleKeyDown);
|
||||
return () => document.removeEventListener('keydown', handleKeyDown);
|
||||
}, [goTo, pageNums, total]);
|
||||
|
||||
// Browser back/forward
|
||||
useEffect(() => {
|
||||
const handlePopState = () => {
|
||||
const m = location.hash.match(/^#page-(\d+)$/);
|
||||
if (m) {
|
||||
const n = parseInt(m[1], 10);
|
||||
if (pageNums.includes(n)) goTo(n, false, false);
|
||||
}
|
||||
};
|
||||
window.addEventListener('popstate', handlePopState);
|
||||
return () => window.removeEventListener('popstate', handlePopState);
|
||||
}, [goTo, pageNums]);
|
||||
|
||||
const currentPage = pageNums[currentIdx];
|
||||
|
||||
return (
|
||||
<html lang="en">
|
||||
<head>
|
||||
<meta charSet="UTF-8" />
|
||||
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
|
||||
<title>{title}</title>
|
||||
<link
|
||||
href="https://fonts.googleapis.com/css2?family=Cinzel:wght@400;600;700&family=Crimson+Text:ital,wght@0,400;0,600;1,400&family=Inconsolata:wght@400;600&display=swap"
|
||||
rel="stylesheet"
|
||||
/>
|
||||
<link rel="stylesheet" href="/css/book-page.css" />
|
||||
<link rel="stylesheet" href="/css/book-layout.css" />
|
||||
</head>
|
||||
<body>
|
||||
<header>
|
||||
<div className="logo">{logoText}</div>
|
||||
<div className="toolbar">
|
||||
<span id="page-indicator"></span>
|
||||
<>
|
||||
<header>
|
||||
<div className="logo">{logoText}</div>
|
||||
<div className="toolbar">
|
||||
<span id="page-indicator">{currentIdx + 1} / {total}</span>
|
||||
</div>
|
||||
</header>
|
||||
|
||||
<div id="layout">
|
||||
<nav id="sidebar">
|
||||
<div id="sidebar-header">
|
||||
<div
|
||||
className="section-title"
|
||||
style={{ marginBottom: 0, borderBottom: 'none', paddingBottom: 0 }}
|
||||
>
|
||||
<span className="icon">✦</span> Pages
|
||||
</div>
|
||||
<p>{pages.length} pages</p>
|
||||
</div>
|
||||
</header>
|
||||
<ul id="page-list">
|
||||
{pages.map(({ n }) => (
|
||||
<li key={n} data-page={n} className={n === currentPage ? 'active' : undefined}>
|
||||
<button onClick={() => goTo(n, false, true)}>
|
||||
<span className="page-num">{n}</span>
|
||||
<span>Page {n}</span>
|
||||
</button>
|
||||
</li>
|
||||
))}
|
||||
</ul>
|
||||
</nav>
|
||||
|
||||
<div id="layout">
|
||||
<nav id="sidebar">
|
||||
<div id="sidebar-header">
|
||||
<div
|
||||
className="section-title"
|
||||
style={{ marginBottom: 0, borderBottom: 'none', paddingBottom: 0 }}
|
||||
>
|
||||
<span className="icon">✦</span> Pages
|
||||
</div>
|
||||
<p>{pages.length} pages</p>
|
||||
</div>
|
||||
<ul id="page-list">
|
||||
{pages.map(({ n }) => (
|
||||
<li key={n} data-page={n}>
|
||||
<button>
|
||||
<span className="page-num">{n}</span>
|
||||
<span>Page {n}</span>
|
||||
</button>
|
||||
</li>
|
||||
))}
|
||||
</ul>
|
||||
</nav>
|
||||
|
||||
<div id="main">
|
||||
<div id="nav">
|
||||
<button id="btn-prev" className="tab" disabled>← Prev</button>
|
||||
<span id="page-title"></span>
|
||||
<button id="btn-next" className="tab">Next →</button>
|
||||
</div>
|
||||
<div id="content">
|
||||
{pages.map(({ n, content }) => (
|
||||
<section
|
||||
key={n}
|
||||
id={`page-${n}`}
|
||||
className="page-section"
|
||||
dangerouslySetInnerHTML={{ __html: content }}
|
||||
/>
|
||||
))}
|
||||
</div>
|
||||
<div id="main">
|
||||
<div id="nav">
|
||||
<button
|
||||
id="btn-prev"
|
||||
className="tab"
|
||||
disabled={currentIdx === 0}
|
||||
onClick={() => goTo(pageNums[currentIdx - 1], true, true)}
|
||||
>
|
||||
← Prev
|
||||
</button>
|
||||
<span id="page-title">Page {currentPage}</span>
|
||||
<button
|
||||
id="btn-next"
|
||||
className="tab"
|
||||
disabled={currentIdx === total - 1}
|
||||
onClick={() => goTo(pageNums[currentIdx + 1], true, true)}
|
||||
>
|
||||
Next →
|
||||
</button>
|
||||
</div>
|
||||
<div id="content" ref={contentRef}>
|
||||
{pages.map(({ n, content }) => (
|
||||
<section
|
||||
key={n}
|
||||
id={`page-${n}`}
|
||||
className="page-section"
|
||||
dangerouslySetInnerHTML={{ __html: content }}
|
||||
/>
|
||||
))}
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<script dangerouslySetInnerHTML={{ __html: buildScript(pageNums) }} />
|
||||
</body>
|
||||
</html>
|
||||
</div>
|
||||
</>
|
||||
);
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user