import { useState, useRef, useEffect, useCallback } from 'react' import { ReactReader } from '../../lib/index' import type { Contents, Rendition } from 'epubjs' import { DEMO_URL, DEMO_NAME } from '../components/config' import { Example } from '../components/Example' type ITextSelection = { text: string cfiRange: string } /* This example are trying out dynamic change color of epubjs hightlight, but its not working.. */ export const Selection = () => { const [selections, setSelections] = useState([]) const [rendition, setRendition] = useState(undefined) const [location, setLocation] = useState(0) const [color, setColor] = useState('red') useEffect(() => { console.log('effect', color) if (rendition) { /* rendition.annotations.each().forEach((annotation) => { annotation.style = { fill: color } })*/ console.log('set color', rendition) } }, [rendition, color]) useEffect(() => { if (rendition) { function setRenderSelection(cfiRange: string, contents: Contents) { if (rendition) { setSelections((list) => list.concat({ text: rendition.getRange(cfiRange).toString(), cfiRange, }) ) rendition.annotations.add( 'highlight', cfiRange, {}, (e: MouseEvent) => console.log('click on selection', cfiRange, e), 'my-class', { fill: color } ) console.log('rendition', { rendition, contents }) const selection = contents.window.getSelection() selection?.removeAllRanges() } } rendition.on('selected', setRenderSelection) return () => { rendition?.off('selected', setRenderSelection) } } }, [setSelections, rendition]) return (

Selections

    {selections.map(({ text, cfiRange }, i) => (
  • {text}
  • ))}
{['red', 'pink'].map((item) => ( ))}
} > setLocation(loc)} epubOptions={{ allowPopups: true, // Adds `allow-popups` to sandbox-attribute allowScriptedContent: true, // Adds `allow-scripts` to sandbox-attribute }} getRendition={(_rendition: Rendition) => { setRendition(_rendition) _rendition.hooks.content.register((contents: Contents) => { const document = contents.window.document console.log('document', document) if (document) { const css = ` .epubjs-hl { border: 1px solid black; } ` const style = document.createElement('style') style.appendChild(document.createTextNode(css)) document.head.appendChild(style) } }) }} />
) }