futurepress / epub.js

Enhanced eBooks in the browser.
http://futurepress.org
Other
6.4k stars 1.1k forks source link

Renderless viewer #1397

Open way5 opened 3 weeks ago

way5 commented 3 weeks ago

Hi everyone! I was implementing renderless example of the following content:

 import ePub from 'epubjs/src/epub.js';

let currentSectionIndex = 0;
const book = ePub(};  // also tested with: const book = ePub(data, {openAs: 'binary'});

const req = new XMLHttpRequest();
req.open("GET", activeFile.src);
req.responseType = "arraybuffer";

req.onloadend = function (e: ProgressEvent) {
  const data = new Uint8Array(req.response);

  function display(item: number) {
    let section = book.section(item);
         if (section) {
             section.render().then(function (html: string) {
                 console.log(html);    // <--- html contains the whole document HTML instead of the book section
                 document.getElementById('viewer').innerHTML = html;
             });
         }
         return section;
     }

   book.open(data, "binary").then(function () {
       showLoader(false);
       display(currentSectionIndex);
   });
}
 req.send();
...
<body>
  <div id="viewer" class="scrolled"></div>
</body> 
...

The problem I am facing is that HTML which is being returned after render is actually the whole document. As I understand the above example is the only way to get section source generated.

Where am I mistaken?

johnfactotum commented 2 weeks ago

A section is a full document. "Section" in Epub.js is a name for what is technically called a content document or a spine item. It's also commonly though somewhat inaccurately called a chapter.

way5 commented 2 weeks ago

Right. It is clear to me what section is. However, the HTML which I am expecting to be section, in above example is the root page html. I mean the root page where the reader container element is, not the section/chapter.

johnfactotum commented 2 weeks ago

Ah, I see...

Well, section.render() (without any arguments) only works if the section has a full URL, which is only the case when opening unarchived books (otherwise it will try to request the path within the archive as if it is a valid URL). So for archived books, you need to specify the request method:

section.render(book.load.bind(book)).the(html => { /* ... */ })