|
| 1 | +import { useState, useEffect } from 'react'; |
| 2 | + |
| 3 | +const CKEditorProvider = ( { |
| 4 | + attribute, |
| 5 | + onChange, |
| 6 | + name, |
| 7 | + value, |
| 8 | + disabled = false, |
| 9 | + labelAction = null, |
| 10 | + intlLabel, |
| 11 | + required = false, |
| 12 | + description = null, |
| 13 | + error = null |
| 14 | + } ) => { |
| 15 | + const [ importedEditor, setImportedEditor ] = useState( null ); |
| 16 | + |
| 17 | + useEffect( () => { |
| 18 | + const importEditor = async () => { |
| 19 | + const module = await import( '../CKEditorInput' ); |
| 20 | + const CKEditorInput = module.default; |
| 21 | + |
| 22 | + setImportedEditor(<CKEditorInput |
| 23 | + attribute={ attribute } |
| 24 | + onChange={ onChange } |
| 25 | + name={ name } |
| 26 | + value={ value } |
| 27 | + disabled={ disabled } |
| 28 | + labelAction={ labelAction } |
| 29 | + required={ required } |
| 30 | + description={ description } |
| 31 | + error={ error } |
| 32 | + intlLabel={ intlLabel } |
| 33 | + /> ); |
| 34 | + }; |
| 35 | + |
| 36 | + const injectAssetsFromCDN = setInterval( () => { |
| 37 | + const CDNScript = document.querySelector( '#ckeditor5-cdn-script' ); |
| 38 | + const CDNStyles = document.querySelector( '#ckeditor5-cdn-styles' ); |
| 39 | + |
| 40 | + if ( !CDNStyles ) { |
| 41 | + _injectStylesFromCDN(); |
| 42 | + } |
| 43 | + |
| 44 | + if ( window.CKEDITOR ) { |
| 45 | + window.CKEditorCDNLoaded = true; |
| 46 | + |
| 47 | + importEditor(); |
| 48 | + |
| 49 | + clearInterval( injectAssetsFromCDN ); |
| 50 | + |
| 51 | + return; |
| 52 | + } |
| 53 | + |
| 54 | + if ( !CDNScript ) { |
| 55 | + _injectScriptFromCDN(); |
| 56 | + |
| 57 | + } |
| 58 | + }, 100 ) |
| 59 | + |
| 60 | + return () => { |
| 61 | + const CDNScript = document.querySelector( '#ckeditor5-cdn-script' ); |
| 62 | + |
| 63 | + if ( CDNScript ) { |
| 64 | + CDNScript.remove(); |
| 65 | + } |
| 66 | + |
| 67 | + window.CKEditorCDNLoaded = false; |
| 68 | + } |
| 69 | + }, [] ); |
| 70 | + |
| 71 | + return ( |
| 72 | + <> |
| 73 | + { window.CKEditorCDNLoaded && importedEditor } |
| 74 | + </> |
| 75 | + ) |
| 76 | +} |
| 77 | + |
| 78 | +function _injectStylesFromCDN() { |
| 79 | + const link = document.createElement( 'link' ); |
| 80 | + |
| 81 | + link.rel = 'stylesheet'; |
| 82 | + link.href = 'https://cdn.ckeditor.com/ckeditor5/43.0.0/ckeditor5.css'; |
| 83 | + link.id = 'ckeditor5-cdn-styles'; |
| 84 | + |
| 85 | + document.head.appendChild( link ); |
| 86 | +} |
| 87 | + |
| 88 | +function _injectScriptFromCDN() { |
| 89 | + const script = document.createElement( 'script' ); |
| 90 | + |
| 91 | + script.src = "https://cdn.ckeditor.com/ckeditor5/43.0.0/ckeditor5.umd.js"; |
| 92 | + script.async = true; |
| 93 | + script.id = 'ckeditor5-cdn-script' |
| 94 | + |
| 95 | + document.body.appendChild( script ); |
| 96 | +} |
| 97 | + |
| 98 | +export default CKEditorProvider; |
0 commit comments