| 1 |
import { ImageUploader } from '@agent/components/ImageUploader'; |
| 2 |
import { useCallback, useEffect, useRef, useState } from '@wordpress/element'; |
| 3 |
import { __ } from '@wordpress/i18n'; |
| 4 |
|
| 5 |
const updateLinkHrefAttr = (url) => { |
| 6 |
document.querySelectorAll('link[rel*="icon"]')?.forEach((link) => { |
| 7 |
link.href = url; |
| 8 |
}); |
| 9 |
}; |
| 10 |
|
| 11 |
export const UpdateSiteIconConfirm = ({ onConfirm, onCancel }) => { |
| 12 |
const [originalSiteIconUrl, setOriginalSiteIconUrl] = useState(); |
| 13 |
|
| 14 |
useEffect(() => { |
| 15 |
setOriginalSiteIconUrl( |
| 16 |
document.querySelector('link[rel="icon"]')?.href ?? null, |
| 17 |
); |
| 18 |
}, []); |
| 19 |
|
| 20 |
const undoSiteIconChange = useCallback(() => { |
| 21 |
if (originalSiteIconUrl) { |
| 22 |
updateLinkHrefAttr(originalSiteIconUrl); |
| 23 |
} |
| 24 |
}, [originalSiteIconUrl]); |
| 25 |
|
| 26 |
const confirmed = useRef(false); |
| 27 |
useEffect(() => { |
| 28 |
if (!originalSiteIconUrl) return; |
| 29 |
return () => { |
| 30 |
if (!confirmed.current) undoSiteIconChange(); |
| 31 |
}; |
| 32 |
}, [originalSiteIconUrl]); |
| 33 |
|
| 34 |
useEffect(() => { |
| 35 |
// Put modal above the Agent |
| 36 |
const style = document.createElement('style'); |
| 37 |
style.textContent = `.media-modal { |
| 38 |
z-index: 999999 !important; |
| 39 |
}`; |
| 40 |
document.head.appendChild(style); |
| 41 |
return () => style.remove(); |
| 42 |
}, []); |
| 43 |
|
| 44 |
const handleConfirm = async ({ imageId }) => { |
| 45 |
confirmed.current = true; |
| 46 |
await onConfirm({ |
| 47 |
data: { imageId }, |
| 48 |
shouldRefreshPage: true, |
| 49 |
}); |
| 50 |
}; |
| 51 |
|
| 52 |
const handleSelect = (image) => { |
| 53 |
updateLinkHrefAttr(image.url); |
| 54 |
}; |
| 55 |
|
| 56 |
return ( |
| 57 |
<Wrapper> |
| 58 |
<div className="relative p-3"> |
| 59 |
<ImageUploader |
| 60 |
type="site_icon" |
| 61 |
title={__('Site icon', 'extendify-local')} |
| 62 |
actionLabel={__('Set site icon', 'extendify-local')} |
| 63 |
onSave={handleConfirm} |
| 64 |
onCancel={onCancel} |
| 65 |
onSelect={handleSelect} |
| 66 |
/> |
| 67 |
</div> |
| 68 |
</Wrapper> |
| 69 |
); |
| 70 |
}; |
| 71 |
|
| 72 |
const Wrapper = ({ children }) => ( |
| 73 |
<div className="mb-4 ml-10 mr-2 flex flex-col rounded-lg border border-gray-300 bg-gray-50 rtl:ml-2 rtl:mr-10"> |
| 74 |
{children} |
| 75 |
</div> |
| 76 |
); |
| 77 |
|