2020-11-16 18:14:26 +02:00
import { useEffect , useState , useMemo } from 'react' ;
const md5 = require ( 'md5' ) ;
2024-04-05 13:16:49 +02:00
// eslint-disable-next-line @typescript-eslint/ban-types, @typescript-eslint/no-explicit-any -- Old code before rule was applied, Old code before rule was applied
2020-11-16 18:14:26 +02:00
export default function ( frameWindow : any , isReady : boolean , postMessage : Function , html : string ) {
const [ loadedHtmlHash , setLoadedHtmlHash ] = useState ( '' ) ;
const htmlHash = useMemo ( ( ) = > {
return md5 ( html ) ;
} , [ html ] ) ;
useEffect ( ( ) = > {
if ( ! frameWindow ) return ( ) = > { } ;
2024-04-05 13:16:49 +02:00
// eslint-disable-next-line @typescript-eslint/no-explicit-any -- Old code before rule was applied
2020-11-16 18:14:26 +02:00
function onMessage ( event : any ) {
const data = event . data ;
if ( ! data || data . target !== 'UserWebview' ) return ;
2023-02-16 12:55:24 +02:00
// eslint-disable-next-line no-console
2020-11-16 18:14:26 +02:00
console . info ( 'useHtmlLoader: message' , data ) ;
// We only update if the HTML that was loaded is the same as
// the active one. Otherwise it means the content has been
// changed between the moment it was set by the user and the
// moment it was loaded in the view.
if ( data . message === 'htmlIsSet' && data . hash === htmlHash ) {
setLoadedHtmlHash ( data . hash ) ;
}
}
frameWindow . addEventListener ( 'message' , onMessage ) ;
return ( ) = > {
2023-11-09 14:24:49 +02:00
if ( frameWindow . removeEventListener ) frameWindow . removeEventListener ( 'message' , onMessage ) ;
2020-11-16 18:14:26 +02:00
} ;
} , [ frameWindow , htmlHash ] ) ;
useEffect ( ( ) = > {
2023-02-16 12:55:24 +02:00
// eslint-disable-next-line no-console
2020-11-16 18:14:26 +02:00
console . info ( 'useHtmlLoader: isReady' , isReady ) ;
if ( ! isReady ) return ;
2023-02-16 12:55:24 +02:00
// eslint-disable-next-line no-console
2020-11-27 01:31:31 +02:00
console . info ( 'useHtmlLoader: setHtml' , htmlHash ) ;
2020-11-16 18:14:26 +02:00
postMessage ( 'setHtml' , {
hash : htmlHash ,
html : html ,
} ) ;
2022-08-19 13:10:04 +02:00
// eslint-disable-next-line @seiyab/react-hooks/exhaustive-deps -- Old code before rule was applied
2020-11-16 18:14:26 +02:00
} , [ html , htmlHash , isReady ] ) ;
return loadedHtmlHash ;
}