diff --git a/.gitignore b/.gitignore index 4c0a0e5..2d0e373 100644 --- a/.gitignore +++ b/.gitignore @@ -7,3 +7,4 @@ dist/ /tasks/ /resource/notes/ /resource/pr-notes/ +/sample-book/testing.code-workspace \ No newline at end of file diff --git a/sample-book/META-INF/container.xml b/sample-book/META-INF/container.xml new file mode 100644 index 0000000..8b80cd0 --- /dev/null +++ b/sample-book/META-INF/container.xml @@ -0,0 +1,6 @@ + + + + + + diff --git a/sample-book/OEBPS/ch_1.xhtml b/sample-book/OEBPS/ch_1.xhtml new file mode 100644 index 0000000..a276fb5 --- /dev/null +++ b/sample-book/OEBPS/ch_1.xhtml @@ -0,0 +1,48 @@ + + + + + Chapter 1: The Cross-File Discovery + + + +

Chapter 1: The Cross-File Discovery

+ +

+ Di era modern penerbitan buku digital, berkas bab utama sering kali memisahkan catatan kaki ke dalam dokumen terpisah untuk menjaga keringkasan naskah utama[1]. +

+ +

+ Sayangnya, banyak konversi EPUB lawas sama sekali tidak menyertakan atribut semantik formal. Sebagian besar hanya menggunakan teks berangka di dalam kurung siku biasa[2] tanpa atribut epub:type="noteref". +

+ +

+ Bahkan, ada pula penerbit yang hanya menggunakan tanda bintang tunggal tanpa tag superscript* untuk memberikan keterangan tambahan khusus pembaca. +

+ +

+ Tantangan lainnya muncul ketika target catatan di berkas akhir dibungkus di dalam paragraf dengan tautan kosong pembuka4. +

+ +

+ Sebagai pembanding, reader previewer kita juga tetap harus mampu menampilkan catatan lokal di halaman yang sama dengan mulus[5] tanpa kendala. +

+ +

+ Uji skenario batas (Edge Case): tautan catatan yang mengarah ke ID yang sengaja tidak ada di berkas tujuan[99]. +

+ +

+ Uji skenario batas lokal (Intra-file Edge Case): tautan catatan lokal yang mengarah ke ID yang tidak ada di bab ini[100]. +

+ +
+ + +
+ +
+ + diff --git a/sample-book/OEBPS/content.opf b/sample-book/OEBPS/content.opf new file mode 100644 index 0000000..fbd4afa --- /dev/null +++ b/sample-book/OEBPS/content.opf @@ -0,0 +1,18 @@ + + + + Sample EPUB - Cross-File Footnotes Demo + XHTML Reader Previewer + en + + + + + + + + + + + + diff --git a/sample-book/OEBPS/notes.xhtml b/sample-book/OEBPS/notes.xhtml new file mode 100644 index 0000000..0a3f257 --- /dev/null +++ b/sample-book/OEBPS/notes.xhtml @@ -0,0 +1,42 @@ + + + + + Endnotes + + + +

Endnotes

+ +
+ + + +
    + +
  1. +

    + 2. [Deteksi Heuristik] Catatan ini membuktikan bahwa tautan berpola teks [2] tanpa atribut semantik formal tetap sukses dideteksi dan ditampilkan di popover. ↵ +

    +
  2. +
+ + +
+

+ * [Simbol Bintang] Catatan tambahan untuk simbol bintang tunggal. Seluruh simbol pengembalian (↑) telah otomatis dibersihkan. ↑ +

+
+ + +

+ + 4. [Enclosing Paragraph] Catatan ini membuktikan bahwa jika atribut ID berada di dalam tag <a> pembuka, seluruh paragraf penjelas tetap berhasil diekstrak utuh. ↩ +

+
+ + diff --git a/sample-book/OEBPS/style.css b/sample-book/OEBPS/style.css new file mode 100644 index 0000000..e04415f --- /dev/null +++ b/sample-book/OEBPS/style.css @@ -0,0 +1,45 @@ +body { + font-family: Georgia, serif; + line-height: 1.8; + margin: 2rem auto; + max-width: 42rem; + padding: 0 1rem; +} + +h1, h2 { + font-family: system-ui, -apple-system, sans-serif; +} + +a { + color: #2563eb; + text-decoration: none; +} + +a:hover { + text-decoration: underline; +} + +sup { + font-size: 0.75em; + line-height: 0; + vertical-align: super; +} + +.test-badge { + display: inline-block; + background: #e0f2fe; + color: #0369a1; + font-size: 0.8rem; + font-weight: 600; + padding: 0.15rem 0.5rem; + border-radius: 4px; + margin-right: 0.5rem; +} + +.notes-list { + padding-left: 1.5rem; +} + +.notes-list li { + margin-bottom: 1rem; +} diff --git a/sample-book/OEBPS/toc.xhtml b/sample-book/OEBPS/toc.xhtml new file mode 100644 index 0000000..ece72ce --- /dev/null +++ b/sample-book/OEBPS/toc.xhtml @@ -0,0 +1,17 @@ + + + + + Table of Contents + + + + + + diff --git a/src/extension.ts b/src/extension.ts index 579df73..b37490d 100644 --- a/src/extension.ts +++ b/src/extension.ts @@ -1,7 +1,7 @@ import * as vscode from 'vscode'; import * as os from 'node:os'; import * as path from 'node:path'; -import { sanitizeXhtml } from './xhtml'; +import { sanitizeXhtml, extractElementById } from './xhtml'; import { readerShell, ReaderNavInfo } from './reader-shell'; import { locateEpubContainer, parseContainerXml, parseOpfXml, loadEpubToc, EpubPackage } from './epub'; import { StateManager, ReaderPreferences } from './state-manager'; @@ -304,6 +304,51 @@ async function attachReaderToWebview( return; } + if (isRequestFootnoteMessage(message)) { + void (async () => { + try { + const target = resolveChapterLink(message.href, currentSource, watchRoot, epubPackage?.opfDir); + if (!target || !target.fragment) { + void panel.webview.postMessage({ + type: 'footnoteResponse', + requestId: message.requestId, + error: 'Missing target fragment' + }); + return; + } + + const fileBytes = await vscode.workspace.fs.readFile(target.source); + const rawXhtml = new TextDecoder('utf-8').decode(fileBytes); + const extractedHtml = extractElementById(rawXhtml, target.fragment); + + if (!extractedHtml) { + void panel.webview.postMessage({ + type: 'footnoteResponse', + requestId: message.requestId, + error: 'Anchor not found in target file' + }); + return; + } + + const targetDir = parentUri(target.source); + const rewritten = await rewriteResourceUris(extractedHtml, targetDir, panel.webview, epubPackage?.opfDir); + + void panel.webview.postMessage({ + type: 'footnoteResponse', + requestId: message.requestId, + html: rewritten + }); + } catch (error) { + void panel.webview.postMessage({ + type: 'footnoteResponse', + requestId: message.requestId, + error: String(error) + }); + } + })(); + return; + } + if (isOpenLinkMessage(message)) { const target = resolveChapterLink(message.href, currentSource, watchRoot, epubPackage?.opfDir); if (target) { @@ -360,6 +405,18 @@ function isOpenLinkMessage(message: unknown): message is { type: 'openLink'; hre && typeof (message as { href?: unknown }).href === 'string'; } +function isRequestFootnoteMessage(message: unknown): message is { + type: 'requestFootnote'; + href: string; + requestId: string; +} { + return typeof message === 'object' + && message !== null + && (message as { type?: unknown }).type === 'requestFootnote' + && typeof (message as { href?: unknown }).href === 'string' + && typeof (message as { requestId?: unknown }).requestId === 'string'; +} + function isSavePreferencesMessage(message: unknown): message is { type: 'savePreferences'; preferences: Partial; diff --git a/src/reader-shell.ts b/src/reader-shell.ts index c5a8baa..9cd6c69 100644 --- a/src/reader-shell.ts +++ b/src/reader-shell.ts @@ -191,6 +191,20 @@ export function readerShell( transition: max-width 0.2s ease; will-change: transform; } + :root:not(.light) #content, + :root:not(.light) #content p, + :root:not(.light) #content li, + :root:not(.light) #content dd, + :root:not(.light) #content dt, + :root:not(.light) #content blockquote, + :root:not(.light) #content h1, + :root:not(.light) #content h2, + :root:not(.light) #content h3, + :root:not(.light) #content h4, + :root:not(.light) #content h5, + :root:not(.light) #content h6 { + color: var(--reader-fg); + } img, video { display: block; max-width: 100%; @@ -546,7 +560,7 @@ export function readerShell( } .footnote-body { font-family: system-ui, -apple-system, BlinkMacSystemFont, "Segoe UI", Roboto, sans-serif; - max-height: 45vh; + max-height: min(260px, 45vh); overflow-y: auto; scrollbar-width: none !important; -ms-overflow-style: none !important; @@ -554,6 +568,71 @@ export function readerShell( .footnote-body p { margin: 0.25rem 0; } + .footnote-loading { + display: inline-flex; + align-items: center; + gap: 0.5rem; + color: var(--muted-fg, #9ca3af); + font-size: 0.85rem; + padding: 0.2rem 0; + } + .footnote-spinner { + display: inline-block; + width: 13px; + height: 13px; + border: 2px solid var(--popover-border); + border-top-color: #3b82f6; + border-radius: 50%; + animation: footnoteSpin 0.6s linear infinite; + } + @keyframes footnoteSpin { + to { transform: rotate(360deg); } + } + .footnote-error-card { + font-size: 0.85rem; + line-height: 1.5; + } + .footnote-error-header { + display: flex; + align-items: center; + gap: 0.45rem; + color: #f59e0b; + font-weight: 600; + margin-bottom: 0.35rem; + } + .footnote-error-desc { + color: var(--popover-fg); + margin: 0.25rem 0 0.65rem; + opacity: 0.9; + } + .footnote-error-desc code { + background: rgba(255, 255, 255, 0.1); + padding: 0.1rem 0.3rem; + border-radius: 3px; + font-family: monospace; + font-size: 0.88em; + } + .footnote-error-actions { + display: flex; + justify-content: flex-end; + gap: 0.5rem; + margin-top: 0.4rem; + } + .footnote-fallback-btn { + background: rgba(59, 130, 246, 0.15); + color: #60a5fa; + border: 1px solid rgba(59, 130, 246, 0.35); + padding: 0.3rem 0.65rem; + border-radius: 4px; + cursor: pointer; + font-size: 0.8rem; + font-weight: 500; + transition: background 0.15s ease, border-color 0.15s ease; + } + .footnote-fallback-btn:hover { + background: rgba(59, 130, 246, 0.28); + border-color: #60a5fa; + } /* Settings Popover */ .settings-popover { @@ -1357,6 +1436,9 @@ export function readerShell( if (!popover.hidden) { popover.hidden = true; } + activeFootnoteLink = null; + activeFootnoteHref = null; + activeFootnoteRequestId = null; } function toggleToc(open) { @@ -1687,30 +1769,61 @@ export function readerShell( }); } + let activeFootnoteLink = null; + let activeFootnoteHref = null; + let activeFootnoteRequestId = null; + function isFootnoteLink(link, href) { - if (!href.startsWith('#')) return false; + if (!href) return false; + if (/^(?:https?:|mailto:|tel:|ftp:)/i.test(href)) return false; + + const hashIndex = href.indexOf('#'); + if (hashIndex === -1) return false; + + const fragment = href.slice(hashIndex + 1); + if (!fragment) return false; + const epubType = (link.getAttribute('epub:type') || '').toLowerCase(); const role = (link.getAttribute('role') || '').toLowerCase(); const className = (link.className || '').toLowerCase(); const rel = (link.getAttribute('rel') || '').toLowerCase(); - if (epubType.split(/\\s+/).includes('noteref')) return true; - if (role.split(/\\s+/).includes('doc-noteref')) return true; - if (rel.split(/\\s+/).includes('footnote')) return true; - if (/\\b(?:footnote|noteref|note-ref)\\b/i.test(className)) return true; - if (link.closest('sup, sub')) return true; + // 1. Semantic attributes + if (epubType.split(/\\s+/).some((t) => t.includes('noteref') || t.includes('footnote'))) return true; + if (role.split(/\\s+/).some((r) => r.includes('doc-noteref') || r.includes('doc-biblioref'))) return true; + if (rel.split(/\\s+/).some((r) => r.includes('footnote'))) return true; + if (/\\b(?:footnote|noteref|note-ref|endnote)\\b/i.test(className)) return true; - const id = decodeURIComponent(href.slice(1)); - const target = document.getElementById(id); - if (target) { - const targetEpubType = (target.getAttribute('epub:type') || '').toLowerCase(); - const targetRole = (target.getAttribute('role') || '').toLowerCase(); - const targetClass = (target.className || '').toLowerCase(); - const targetTag = target.tagName.toLowerCase(); - if (targetTag === 'aside' || targetEpubType.includes('footnote') || targetRole.includes('doc-footnote') || /\\bfootnote\\b/i.test(targetClass)) { - return true; + // 2. Structural heuristics: sup, sub, or parent with footnote class + if (link.closest('sup, sub')) return true; + if (link.parentElement && /\\b(?:footnote|noteref|note-ref|fn)\\b/i.test(link.parentElement.className || '')) return true; + + // 3. Text heuristics: [1], (1), 1, [a], *, †, ‡ + const text = (link.textContent || '').trim(); + if (/^\\[\\s*\\d+\\s*\\]$/.test(text) || /^\\(\\s*\\d+\\s*\\)$/.test(text) || /^\\d+$/.test(text)) return true; + if (/^\\[\\s*[a-zA-Z]\\s*\\]$/.test(text)) return true; + if (/^[*†‡§#]+$/.test(text)) return true; + + // 4. Fragment identifier naming heuristics (e.g. #fn1, #note-1, #endnote_3, #n1) + const decodedFragment = decodeURIComponent(fragment).toLowerCase(); + if (/^(?:fn|note|footnote|endnote|ftn|ref|n)[-_0-9]/i.test(decodedFragment)) return true; + if (/[-_](?:fn|note|footnote|endnote)[-_0-9]?$/i.test(decodedFragment)) return true; + + // 5. If intra-file, inspect target element in DOM + if (hashIndex === 0) { + const id = decodeURIComponent(fragment); + const target = document.getElementById(id); + if (target) { + const targetEpubType = (target.getAttribute('epub:type') || '').toLowerCase(); + const targetRole = (target.getAttribute('role') || '').toLowerCase(); + const targetClass = (target.className || '').toLowerCase(); + const targetTag = target.tagName.toLowerCase(); + if (targetTag === 'aside' || targetEpubType.includes('footnote') || targetRole.includes('doc-footnote') || /\\bfootnote\\b/i.test(targetClass)) { + return true; + } } } + return false; } @@ -1731,14 +1844,8 @@ export function readerShell( return clone.innerHTML; } - function showFootnotePopover(link, target) { - if (link && typeof link.blur === 'function') { - link.blur(); - } - - noteContent.innerHTML = extractCleanFootnote(target); - popover.hidden = false; - + function positionPopover(link) { + if (!link || popover.hidden) return; const linkRect = link.getBoundingClientRect(); const popoverWidth = popover.offsetWidth; const popoverHeight = popover.offsetHeight; @@ -1784,6 +1891,28 @@ export function readerShell( }); } + function showFootnotePopover(link, contentOrTarget) { + if (link && typeof link.blur === 'function') { + link.blur(); + } + + if (typeof contentOrTarget === 'string') { + noteContent.innerHTML = contentOrTarget; + } else if (contentOrTarget && contentOrTarget.nodeType) { + noteContent.innerHTML = extractCleanFootnote(contentOrTarget); + } + + noteContent.querySelectorAll('a').forEach((el) => { + const h = el.getAttribute('href') || ''; + if (h.startsWith('#')) { + el.replaceWith(document.createTextNode(el.textContent)); + } + }); + + popover.hidden = false; + positionPopover(link); + } + // Toolbar actions document.getElementById('toolbar').addEventListener('click', (event) => { const button = event.target.closest('button[data-action]'); @@ -2029,6 +2158,48 @@ export function readerShell( return; } + // Check if it's a footnote link (intra-file or cross-file with fragment) + if (isFootnoteLink(link, href)) { + event.preventDefault(); + event.stopPropagation(); + + const hashIndex = href.indexOf('#'); + if (hashIndex === 0) { + const id = decodeURIComponent(href.slice(1)); + const target = document.getElementById(id); + if (target) { + showFootnotePopover(link, target); + return; + } + // Intra-file footnote target anchor not found + showFootnotePopover(link, + '
' + + '
' + + '⚠️' + + 'Target Not Found' + + '
' + + '

' + + 'Anchor #' + safeEscape(id) + ' tidak ditemukan di dalam bab ini.' + + '

' + + '
' + ); + return; + } + + // Cross-file footnote link + showFootnotePopover(link, '
Loading note...
'); + activeFootnoteLink = link; + activeFootnoteHref = href; + activeFootnoteRequestId = Date.now().toString(36) + Math.random().toString(36).slice(2); + + vscode.postMessage({ + type: 'requestFootnote', + href: href, + requestId: activeFootnoteRequestId + }); + return; + } + if (href.startsWith('#')) { event.preventDefault(); event.stopPropagation(); @@ -2036,11 +2207,6 @@ export function readerShell( const id = decodeURIComponent(href.slice(1)); const target = document.getElementById(id); - if (isFootnoteLink(link, href) && target) { - showFootnotePopover(link, target); - return; - } - hidePopover(); if (isPaginated && target && contentEl) { const { step } = getColumnMetrics(); @@ -2063,6 +2229,58 @@ export function readerShell( } }); + function safeEscape(str) { + return String(str || '').replace(/[&<>'"]/g, (c) => ({ '&': '&', '<': '<', '>': '>', "'": ''', '"': '"' }[c] || c)); + } + + // Fallback button click inside popover + if (popover) { + popover.addEventListener('click', (event) => { + const btn = event.target.closest('[data-action="open-fallback"]'); + if (btn && btn.dataset.href) { + const href = btn.dataset.href; + hidePopover(); + vscode.postMessage({ type: 'openLink', href }); + } + }); + } + + // Message receiver from Extension Host + window.addEventListener('message', (event) => { + const message = event.data; + if (!message || typeof message !== 'object') return; + + if (message.type === 'footnoteResponse') { + if (message.requestId && message.requestId !== activeFootnoteRequestId) { + return; + } + if (message.html && activeFootnoteLink) { + showFootnotePopover(activeFootnoteLink, message.html); + } else if (activeFootnoteLink) { + const targetHref = activeFootnoteHref || ''; + const hashIndex = targetHref.indexOf('#'); + const fileName = hashIndex > 0 ? targetHref.slice(0, hashIndex).split('/').pop() : targetHref; + const fragment = hashIndex > 0 ? targetHref.slice(hashIndex) : ''; + + const errorHtml = '
' + + '
' + + '⚠️' + + 'Target Not Found' + + '
' + + '

' + + 'Anchor ' + safeEscape(fragment) + ' tidak ditemukan di dalam berkas ' + safeEscape(fileName) + '.' + + '

' + + '
' + + '' + + '
' + + '
'; + showFootnotePopover(activeFootnoteLink, errorHtml); + } + } + }); + // Keyboard shortcuts document.addEventListener('keydown', (event) => { if (event.key === 'Escape') { diff --git a/src/xhtml.ts b/src/xhtml.ts index 19dcbed..addfcb4 100644 --- a/src/xhtml.ts +++ b/src/xhtml.ts @@ -14,3 +14,98 @@ export function sanitizeXhtml(markup: string): string { .replace(eventAttributes, '') .replace(javascriptUrls, ''); } + +function escapeRegex(str: string): string { + return str.replace(/[.*+?^${}()|[\]\\]/g, '\\$&'); +} + +/** + * Cleans extracted footnote markup by removing back-references, return arrows, + * unwrapping self-referential anchors, and sanitizing. + */ +export function cleanFootnoteMarkup(markup: string): string { + const cleaned = markup + .replace(/]*(?:role=["'][^"']*doc-backlink[^"']*|epub:type=["'][^"']*backlink[^"']*|class=["'][^"']*(?:footnote-backref|backlink)[^"']*)[^>]*>[\s\S]*?<\/a>/gi, '') + .replace(/[\s\u00A0]*[\u21A9\u2191\u21B5][\s\u00A0]*/g, '') + .replace(/]*\bhref=["']#[^"']*["'][^>]*>([\s\S]*?)<\/a>/gi, '$1'); + + return sanitizeXhtml(cleaned).trim(); +} + +/** + * Extracts the element matching `targetId` from raw XHTML/HTML content. + * Handles block elements (