johnfactotum / epubjs-tips

Tips and tricks for using Epub.js
Creative Commons Zero v1.0 Universal
33 stars 4 forks source link

Fast Selection issue #2

Open fciannella opened 1 year ago

fciannella commented 1 year ago

Would you have an easy way to use the mouseup event to trigger the "selected" event with React? The selection at the moment with epubjs is unusable because it fires the selected event way too fast.

johnfactotum commented 1 year ago

I don't know about React but you can add the event in the content hook. An example is right in the README: https://github.com/johnfactotum/epubjs-tips/blob/1576204152938c1856e2f2a7276be390ed5d7cc6/README.md?plain=1#L63-L86

fciannella commented 1 year ago

Thanks, this works, I am able to get the text. Would you explain to me how to get the cfi range too? Would I have to do what epubjs is doing here:

https://github.com/futurepress/epub.js/blob/master/src/contents.js#L964

And if that's the case, how would I get the this.cfiBase?

fciannella commented 1 year ago

This is what I have done so far:

          rendition.hooks.content.register((contents /*view*/) => {
            const frame = contents.document.defaultView.frameElement;
            contents.document.onmouseup = (e) => {
              const selection = contents.window.getSelection();
              const range = selection.getRangeAt(0);
            //   const { left, right, top, bottom } = getRect(range, frame);
            //   console.log("Here is the range:" + (left, right, top, bottom));

            const epubcfi = new EpubCFI(range, contents.cfiBase)
            const cfi = epubcfi.toString()
            console.log("This is the cfibase: " + contents.cfiBase)
            console.log("Here is the CFI: " + cfi)
            console.log("Here is the text:" + selection)
            // Note: besides a range object, the same method can also be used to get the position of any element
            };
          });