exe / TPage_Reader.html
heymilka's picture
Upload TPage_Reader.html
d6331d2 verified
Raw
History Blame Contribute Delete
28.9 kB
<!DOCTYPE html>
<html lang="ko">
<head>
<meta charset="UTF-8">
<title>페이지 리더기</title>
<style>
:root {
--bg-body: #dcdde1;
--bg-paper: #f4f1ea;
--text-main: #2c3e50;
--accent-color: #a39171;
--page-width: 500px;
--page-height: 700px;
--font-size: 15px;
--panel-width: 320px;
}
body.dark-mode {
--bg-body: #1e272e;
--bg-paper: #2f3542;
--text-main: #ced4da;
--accent-color: #f1c40f;
}
body {
background-color: var(--bg-body);
display: flex;
flex-direction: column;
align-items: center;
font-family: 'Apple SD Gothic Neo', 'Malgun Gothic', sans-serif;
margin: 0;
padding: 30px;
transition: background-color 0.3s;
}
.top-menu {
display: flex;
gap: 15px;
margin-bottom: 25px;
align-items: center;
}
/* ── 메인 레이아웃 (뷰어 + 검색 패널) ── */
.main-layout {
display: flex;
align-items: flex-start;
gap: 20px;
}
#viewer-container {
width: var(--page-width);
height: var(--page-height);
background-color: var(--bg-paper);
box-shadow: 0 15px 35px rgba(0,0,0,0.2);
overflow: hidden;
position: relative;
border-radius: 4px;
border-left: 10px solid rgba(0,0,0,0.05);
transition: background-color 0.3s;
flex-shrink: 0;
}
/* 숨겨진 측정용 div */
#measure-box {
position: fixed;
top: -9999px;
left: -9999px;
width: calc(var(--page-width) - 120px);
padding: 0;
font-family: 'Apple SD Gothic Neo', 'Malgun Gothic', sans-serif;
font-size: var(--font-size);
line-height: 1.9;
white-space: pre-wrap;
word-break: break-all;
visibility: hidden;
pointer-events: none;
}
#content {
width: 100%;
height: 100%;
padding: 50px 60px;
box-sizing: border-box;
font-size: var(--font-size);
line-height: 1.9;
color: var(--text-main);
white-space: pre-wrap;
word-break: break-all;
overflow: hidden;
opacity: 1;
transition: opacity 0.1s ease;
}
#content.fading { opacity: 0; }
#loading-overlay {
display: none;
position: absolute;
inset: 0;
background: var(--bg-paper);
align-items: center;
justify-content: center;
font-size: 14px;
color: var(--accent-color);
letter-spacing: 0.05em;
z-index: 10;
}
#loading-overlay.active { display: flex; }
/* ════════════════════════════════════
검색 패널
════════════════════════════════════ */
#search-panel {
width: var(--panel-width);
height: var(--page-height);
background-color: var(--bg-paper);
box-shadow: 0 15px 35px rgba(0,0,0,0.15);
border-radius: 4px;
display: flex;
flex-direction: column;
overflow: hidden;
transition: background-color 0.3s;
flex-shrink: 0;
}
.search-header {
padding: 16px 18px 12px;
border-bottom: 1px solid rgba(0,0,0,0.08);
background: var(--bg-paper);
transition: background-color 0.3s;
}
.search-title {
font-size: 12px;
font-weight: 700;
letter-spacing: 0.12em;
color: var(--accent-color);
text-transform: uppercase;
margin-bottom: 10px;
}
.search-input-wrap {
display: flex;
gap: 7px;
align-items: center;
}
#searchInput {
flex: 1;
padding: 8px 12px;
border: 1px solid var(--accent-color);
border-radius: 20px;
background: var(--bg-body);
color: var(--text-main);
font-size: 13px;
outline: none;
transition: 0.2s;
font-family: inherit;
}
#searchInput:focus {
box-shadow: 0 0 0 2px rgba(163,145,113,0.3);
}
#searchBtn {
padding: 7px 14px;
font-size: 12px;
border-radius: 16px;
background: var(--accent-color);
color: white;
border: none;
cursor: pointer;
white-space: nowrap;
transition: 0.2s;
}
#searchBtn:hover { opacity: 0.85; }
/* 검색 옵션 */
.search-options {
display: flex;
gap: 12px;
margin-top: 8px;
font-size: 11px;
color: var(--text-main);
opacity: 0.7;
}
.search-options label {
display: flex;
align-items: center;
gap: 4px;
cursor: pointer;
user-select: none;
}
.search-result-info {
font-size: 11px;
color: var(--accent-color);
margin-top: 8px;
min-height: 16px;
letter-spacing: 0.03em;
}
/* 결과 리스트 */
#search-results {
flex: 1;
overflow-y: auto;
padding: 8px 0;
}
#search-results::-webkit-scrollbar { width: 4px; }
#search-results::-webkit-scrollbar-track { background: transparent; }
#search-results::-webkit-scrollbar-thumb {
background: var(--accent-color);
border-radius: 4px;
opacity: 0.5;
}
.result-item {
padding: 10px 18px;
cursor: pointer;
border-bottom: 1px solid rgba(0,0,0,0.04);
transition: background 0.15s;
position: relative;
}
.result-item:hover {
background: rgba(163,145,113,0.1);
}
.result-item.active {
background: rgba(163,145,113,0.18);
border-left: 3px solid var(--accent-color);
padding-left: 15px;
}
.result-page-badge {
display: inline-block;
font-size: 10px;
font-weight: 700;
color: var(--accent-color);
letter-spacing: 0.06em;
margin-bottom: 3px;
}
.result-snippet {
font-size: 12px;
color: var(--text-main);
line-height: 1.6;
opacity: 0.85;
word-break: break-all;
display: -webkit-box;
-webkit-line-clamp: 2;
-webkit-box-orient: vertical;
overflow: hidden;
}
.result-snippet mark {
background: rgba(241,196,15,0.45);
color: inherit;
border-radius: 2px;
padding: 0 1px;
}
body:not(.dark-mode) .result-snippet mark {
background: rgba(163,145,113,0.35);
}
.no-result {
text-align: center;
padding: 40px 20px;
font-size: 13px;
color: var(--text-main);
opacity: 0.45;
line-height: 1.8;
}
/* 하이라이트된 텍스트 (#content 내부) */
#content mark {
background: rgba(241,196,15,0.5);
color: inherit;
border-radius: 2px;
}
body:not(.dark-mode) #content mark {
background: rgba(163,145,113,0.4);
}
#content mark.current-hit {
background: rgba(231,76,60,0.45);
outline: 1px solid rgba(231,76,60,0.7);
}
/* 결과 내 현재 활성 아이템 카운터 */
.result-counter-badge {
position: absolute;
right: 14px;
top: 50%;
transform: translateY(-50%);
font-size: 10px;
color: var(--accent-color);
opacity: 0.7;
}
/* ── 컨트롤 ── */
.controls {
margin-top: 30px;
display: flex;
flex-direction: column;
align-items: center;
gap: 10px;
}
.btn-group {
display: flex;
gap: 15px;
align-items: center;
margin-bottom: 5px;
}
#jumpInput {
width: 50px;
padding: 5px 10px;
border-radius: 10px;
border: 1px solid var(--accent-color);
text-align: center;
background: var(--bg-paper);
color: var(--text-main);
font-weight: bold;
}
button {
padding: 10px 25px;
cursor: pointer;
border: none;
background: var(--text-main);
color: var(--bg-paper);
border-radius: 20px;
font-size: 14px;
transition: 0.2s;
}
#darkBtn { background: var(--accent-color); color: white; }
#searchToggleBtn { background: var(--text-main); color: var(--bg-paper); font-size: 13px; padding: 8px 18px; }
input[type="file"] { color: var(--text-main); transition: color 0.3s; }
button:disabled { background: #bdc3c7; cursor: not-allowed; }
.info-text-group {
display: flex;
flex-direction: column;
align-items: center;
gap: 5px;
font-size: 13px;
color: var(--text-main);
opacity: 0.8;
}
.jump-container {
display: flex;
align-items: center;
gap: 8px;
font-size: 14px;
color: var(--text-main);
}
/* 패널 접기/펼치기 애니메이션 */
#search-panel {
transition: width 0.3s ease, opacity 0.3s ease, background-color 0.3s;
}
#search-panel.collapsed {
width: 0;
opacity: 0;
pointer-events: none;
overflow: hidden;
}
</style>
</head>
<body>
<div class="top-menu">
<input type="file" id="fileInput" accept=".txt">
<button id="searchToggleBtn">🔍 검색 패널</button>
<button id="darkBtn">🌓 테마 변경</button>
</div>
<div class="main-layout">
<!-- 뷰어 -->
<div id="viewer-container">
<div id="loading-overlay">페이지 분석 중…</div>
<div id="content">파일을 불러오면 독서가 시작됩니다.</div>
</div>
<!-- 검색 패널 -->
<div id="search-panel" class="collapsed">
<div class="search-header">
<div class="search-title">🔍 본문 검색</div>
<div class="search-input-wrap">
<input type="text" id="searchInput" placeholder="검색어를 입력하세요…">
<button id="searchBtn">검색</button>
</div>
<div class="search-options">
<label>
<input type="checkbox" id="optCase"> 대소문자 구분
</label>
<label>
<input type="checkbox" id="optWholeWord"> 단어 단위
</label>
</div>
<div class="search-result-info" id="resultInfo"></div>
</div>
<div id="search-results">
<div class="no-result">검색어를 입력하고<br>검색 버튼을 누르세요.</div>
</div>
</div>
</div>
<div id="measure-box"></div>
<div class="controls">
<div class="btn-group">
<button id="prevBtn">이전</button>
<div class="jump-container">
<input type="number" id="jumpInput" min="1" value="1">
<span id="page-total">/ 1</span>
<button id="jumpBtn" style="padding: 5px 15px; font-size: 12px;">이동</button>
</div>
<button id="nextBtn">다음</button>
</div>
<div class="info-text-group">
<div id="progress-text">진행률: 0%</div>
<div id="char-count">총 글자 수: 0자</div>
</div>
</div>
<script>
const contentEl = document.getElementById('content');
const measureBox = document.getElementById('measure-box');
const loadingEl = document.getElementById('loading-overlay');
const fileInput = document.getElementById('fileInput');
const prevBtn = document.getElementById('prevBtn');
const nextBtn = document.getElementById('nextBtn');
const jumpInput = document.getElementById('jumpInput');
const jumpBtn = document.getElementById('jumpBtn');
const pageTotal = document.getElementById('page-total');
const progressText = document.getElementById('progress-text');
const charCount = document.getElementById('char-count');
const darkBtn = document.getElementById('darkBtn');
// 검색 관련
const searchPanel = document.getElementById('search-panel');
const searchToggleBtn = document.getElementById('searchToggleBtn');
const searchInput = document.getElementById('searchInput');
const searchBtn = document.getElementById('searchBtn');
const searchResults = document.getElementById('search-results');
const resultInfo = document.getElementById('resultInfo');
const optCase = document.getElementById('optCase');
const optWholeWord = document.getElementById('optWholeWord');
let pages = [];
let currentPage = 0;
let totalChars = 0;
let pageCharEnd = [];
// 검색 상태
let searchMatches = []; // [{pageIdx, charOffset, snippet, matchText}]
let currentMatchIdx = -1;
let lastKeyword = '';
/* ── 다크모드 ── */
darkBtn.addEventListener('click', () => document.body.classList.toggle('dark-mode'));
/* ── 검색 패널 토글 ── */
searchToggleBtn.addEventListener('click', () => {
searchPanel.classList.toggle('collapsed');
if (!searchPanel.classList.contains('collapsed')) {
setTimeout(() => searchInput.focus(), 310);
}
});
/* ── 파일 로드 ── */
fileInput.addEventListener('change', function(e) {
const file = e.target.files[0];
if (!file) return;
const reader = new FileReader();
reader.onload = function(event) {
const text = event.target.result;
totalChars = text.length;
charCount.textContent = `현재: 0자 (총 ${totalChars.toLocaleString()}자)`;
clearSearch();
splitIntoPages(text);
};
reader.readAsText(file, 'UTF-8');
});
/* ── 페이지 분할 ── */
function splitIntoPages(fullText) {
loadingEl.classList.add('active');
requestAnimationFrame(() => {
requestAnimationFrame(() => {
const maxH = parseInt(getComputedStyle(document.documentElement).getPropertyValue('--page-height')) || 700;
const availH = maxH - 100;
const lines = fullText.split('\n');
const result = [];
let currentChunk = '';
measureBox.textContent = '';
for (let i = 0; i < lines.length; i++) {
const candidate = currentChunk ? currentChunk + '\n' + lines[i] : lines[i];
measureBox.textContent = candidate;
if (measureBox.scrollHeight > availH && currentChunk !== '') {
result.push(currentChunk);
currentChunk = lines[i];
measureBox.textContent = currentChunk;
} else {
currentChunk = candidate;
}
}
if (currentChunk) result.push(currentChunk);
pages = result.length > 0 ? result : [''];
currentPage = 0;
pageCharEnd = [];
let acc = 0;
for (const p of pages) { acc += p.length; pageCharEnd.push(acc); }
measureBox.textContent = '';
loadingEl.classList.remove('active');
renderPage();
});
});
}
/* ════════════════════════════════════
검색 핵심 로직
════════════════════════════════════ */
function doSearch() {
const keyword = searchInput.value.trim();
if (!keyword) { clearSearch(); return; }
const useCase = optCase.checked;
const useWholeWord = optWholeWord.checked;
lastKeyword = keyword;
searchMatches = [];
currentMatchIdx = -1;
const flagStr = useCase ? 'g' : 'gi';
let pattern = keyword.replace(/[.*+?^${}()|[\]\\]/g, '\\$&');
if (useWholeWord) pattern = `\\b${pattern}\\b`;
let regex;
try { regex = new RegExp(pattern, flagStr); }
catch(e) { resultInfo.textContent = '유효하지 않은 검색어입니다.'; return; }
// 각 페이지에서 검색
for (let pi = 0; pi < pages.length; pi++) {
const pageText = pages[pi];
let match;
regex.lastIndex = 0;
while ((match = regex.exec(pageText)) !== null) {
const start = Math.max(0, match.index - 30);
const end = Math.min(pageText.length, match.index + match[0].length + 50);
const rawSnippet = pageText.slice(start, end).replace(/\n/g, ' ');
searchMatches.push({
pageIdx : pi,
charOffset: match.index,
matchText : match[0],
snippet : rawSnippet,
matchStart: match.index - start // snippet 내 위치
});
}
}
renderResultList(keyword, useCase, useWholeWord);
}
function renderResultList(keyword, useCase, useWholeWord) {
const total = searchMatches.length;
if (total === 0) {
resultInfo.textContent = '검색 결과가 없습니다.';
searchResults.innerHTML = `<div class="no-result">「${escHtml(keyword)}」<br>에 해당하는 결과가 없습니다.</div>`;
renderPage(); // 하이라이트 초기화
return;
}
resultInfo.textContent = `총 ${total.toLocaleString()}건 발견`;
// 결과 아이템 생성
const fragment = document.createDocumentFragment();
searchMatches.forEach((m, idx) => {
const div = document.createElement('div');
div.className = 'result-item';
div.dataset.idx = idx;
const badge = document.createElement('div');
badge.className = 'result-page-badge';
badge.textContent = `P.${m.pageIdx + 1}`;
const snip = document.createElement('div');
snip.className = 'result-snippet';
snip.innerHTML = highlightSnippet(m.snippet, keyword, useCase, useWholeWord);
const counter = document.createElement('span');
counter.className = 'result-counter-badge';
counter.textContent = `#${idx + 1}`;
div.appendChild(badge);
div.appendChild(snip);
div.appendChild(counter);
div.addEventListener('click', () => jumpToMatch(idx));
fragment.appendChild(div);
});
searchResults.innerHTML = '';
searchResults.appendChild(fragment);
// 첫 번째 결과로 자동 이동
jumpToMatch(0);
}
function jumpToMatch(idx) {
if (idx < 0 || idx >= searchMatches.length) return;
// 이전 활성 아이템 해제
const prevActive = searchResults.querySelector('.result-item.active');
if (prevActive) prevActive.classList.remove('active');
currentMatchIdx = idx;
const match = searchMatches[idx];
// 아이템 활성화 + 스크롤
const itemEl = searchResults.querySelector(`.result-item[data-idx="${idx}"]`);
if (itemEl) {
itemEl.classList.add('active');
itemEl.scrollIntoView({ block: 'nearest', behavior: 'smooth' });
}
// 페이지 이동 (필요한 경우)
if (currentPage !== match.pageIdx) {
currentPage = match.pageIdx;
renderPage(match);
} else {
// 같은 페이지 내에서도 현재 매치 강조 갱신
renderPage(match);
}
}
/* ── 스니펫 하이라이트 ── */
function highlightSnippet(snippet, keyword, useCase, useWholeWord) {
const esc = keyword.replace(/[.*+?^${}()|[\]\\]/g, '\\$&');
const pattern = useWholeWord ? `\\b${esc}\\b` : esc;
const flag = useCase ? 'g' : 'gi';
let regex;
try { regex = new RegExp(pattern, flag); } catch(e) { return escHtml(snippet); }
return escHtml(snippet).replace(regex.source ? new RegExp(regex.source, regex.flags) : regex,
m => `<mark>${m}</mark>`);
}
/* ── 페이지 렌더링 (하이라이트 포함) ── */
function renderPage(activeMatch) {
const total = pages.length;
if (lastKeyword && searchMatches.length > 0) {
// 하이라이트 처리
const useCase = optCase.checked;
const useWholeWord = optWholeWord.checked;
const esc = lastKeyword.replace(/[.*+?^${}()|[\]\\]/g, '\\$&');
const pattern = useWholeWord ? `\\b${esc}\\b` : esc;
const flag = useCase ? 'g' : 'gi';
let regex;
try { regex = new RegExp(pattern, flag); } catch(e) { regex = null; }
if (regex) {
let matchCountOnPage = 0;
// 현재 페이지에서 activeMatch의 순서 계산
let activeLocalIdx = -1;
if (activeMatch && activeMatch.pageIdx === currentPage) {
const matchesOnPage = searchMatches.filter(m => m.pageIdx === currentPage);
activeLocalIdx = matchesOnPage.findIndex(m => m.charOffset === activeMatch.charOffset);
}
const rawText = pages[currentPage] || '';
let html = '';
let lastIdx = 0;
let localIdx = 0;
regex.lastIndex = 0;
let m;
while ((m = regex.exec(rawText)) !== null) {
html += escHtml(rawText.slice(lastIdx, m.index));
const isCurrent = (localIdx === activeLocalIdx);
html += `<mark${isCurrent ? ' class="current-hit"' : ''}>${escHtml(m[0])}</mark>`;
lastIdx = m.index + m[0].length;
localIdx++;
}
html += escHtml(rawText.slice(lastIdx));
contentEl.innerHTML = html;
} else {
contentEl.textContent = pages[currentPage] || '';
}
} else {
contentEl.textContent = pages[currentPage] || '';
}
jumpInput.value = currentPage + 1;
jumpInput.max = total;
pageTotal.textContent = `/ ${total}`;
const pct = Math.round(((currentPage + 1) / total) * 100);
progressText.textContent = `현재 약 ${pct}% 읽으셨습니다`;
const readChars = pageCharEnd[currentPage] || 0;
charCount.textContent = `현재: ${readChars.toLocaleString()}자 (총 ${totalChars.toLocaleString()}자)`;
prevBtn.disabled = (currentPage === 0);
nextBtn.disabled = (currentPage >= total - 1);
}
function clearSearch() {
lastKeyword = '';
searchMatches = [];
currentMatchIdx = -1;
searchInput.value = '';
resultInfo.textContent = '';
searchResults.innerHTML = `<div class="no-result">검색어를 입력하고<br>검색 버튼을 누르세요.</div>`;
renderPage();
}
/* ── HTML 이스케이프 ── */
function escHtml(str) {
return str
.replace(/&/g, '&amp;')
.replace(/</g, '&lt;')
.replace(/>/g, '&gt;')
.replace(/"/g, '&quot;');
}
/* ── 검색 이벤트 ── */
searchBtn.addEventListener('click', doSearch);
searchInput.addEventListener('keypress', e => { if (e.key === 'Enter') doSearch(); });
optCase.addEventListener('change', () => { if (lastKeyword) doSearch(); });
optWholeWord.addEventListener('change', () => { if (lastKeyword) doSearch(); });
/* ── 휠 스크롤 ── */
document.getElementById('viewer-container').addEventListener('wheel', (e) => {
if (pages.length === 0) return;
if (e.deltaY > 0) {
if (currentPage < pages.length - 1) { currentPage++; renderPage(); }
} else {
if (currentPage > 0) { currentPage--; renderPage(); }
}
}, { passive: true });
/* ── 이전 / 다음 ── */
prevBtn.addEventListener('click', () => {
if (currentPage > 0) { currentPage--; renderPage(); }
});
nextBtn.addEventListener('click', () => {
if (currentPage < pages.length - 1) { currentPage++; renderPage(); }
});
/* ── 페이지 이동 ── */
jumpBtn.addEventListener('click', () => {
const t = parseInt(jumpInput.value);
if (t >= 1 && t <= pages.length) {
currentPage = t - 1;
renderPage();
} else {
alert(`1페이지부터 ${pages.length}페이지 사이의 숫자를 입력해주세요!`);
jumpInput.value = currentPage + 1;
}
});
jumpInput.addEventListener('keypress', e => { if (e.key === 'Enter') jumpBtn.click(); });
/* ── 키보드 ── */
window.addEventListener('keydown', e => {
if (document.activeElement === jumpInput || document.activeElement === searchInput) return;
if (e.key === 'PageUp' || e.key === 'ArrowLeft') {
e.preventDefault();
if (!prevBtn.disabled) prevBtn.click();
} else if (e.key === 'PageDown' || e.key === 'ArrowRight' || e.key === ' ') {
e.preventDefault();
if (!nextBtn.disabled) nextBtn.click();
} else if (e.key === 'F3' || (e.ctrlKey && e.key === 'f')) {
// Ctrl+F 또는 F3으로 검색 패널 열기
e.preventDefault();
searchPanel.classList.remove('collapsed');
setTimeout(() => searchInput.focus(), 310);
} else if (e.key === 'Escape') {
searchPanel.classList.add('collapsed');
}
});
</script>
</body>
</html>