| 1 |
import { ImageUploader } from '@agent/components/ImageUploader'; |
| 2 |
import { useQuickEditStore } from '@quick-edit/state/store'; |
| 3 |
import { useCallback, useEffect, useRef, useState } from '@wordpress/element'; |
| 4 |
import { __ } from '@wordpress/i18n'; |
| 5 |
|
| 6 |
const updateLogoSrcAttr = (url, cssFilter) => { |
| 7 |
document.querySelectorAll('.wp-block-site-logo img')?.forEach((img) => { |
| 8 |
img.srcset = ''; |
| 9 |
img.src = url; |
| 10 |
img.style.filter = cssFilter ?? ''; |
| 11 |
}); |
| 12 |
}; |
| 13 |
|
| 14 |
export const UpdateLogoConfirm = ({ onConfirm, onCancel }) => { |
| 15 |
const block = useQuickEditStore((s) => s.agentBlock); |
| 16 |
|
| 17 |
const [originalLogoImgSrc, setOriginalLogoImgSrc] = useState(); |
| 18 |
|
| 19 |
useEffect(() => { |
| 20 |
setOriginalLogoImgSrc( |
| 21 |
document.querySelector('.wp-block-site-logo img')?.src ?? null, |
| 22 |
); |
| 23 |
}, [block]); |
| 24 |
|
| 25 |
const undoLogoChange = useCallback(() => { |
| 26 |
if (originalLogoImgSrc) { |
| 27 |
updateLogoSrcAttr(originalLogoImgSrc); |
| 28 |
} |
| 29 |
}, [originalLogoImgSrc]); |
| 30 |
|
| 31 |
const confirmed = useRef(false); |
| 32 |
useEffect(() => { |
| 33 |
if (!originalLogoImgSrc) return; |
| 34 |
return () => { |
| 35 |
if (!confirmed.current) undoLogoChange(); |
| 36 |
}; |
| 37 |
}, [originalLogoImgSrc]); |
| 38 |
|
| 39 |
useEffect(() => { |
| 40 |
// Put modal above the Agent |
| 41 |
const style = document.createElement('style'); |
| 42 |
style.textContent = `.media-modal { |
| 43 |
z-index: 999999 !important; |
| 44 |
}`; |
| 45 |
document.head.appendChild(style); |
| 46 |
return () => style.remove(); |
| 47 |
}, []); |
| 48 |
|
| 49 |
const handleConfirm = async ({ imageId }) => { |
| 50 |
confirmed.current = true; |
| 51 |
await onConfirm({ |
| 52 |
data: { imageId }, |
| 53 |
shouldRefreshPage: !window.extAgentData?.context?.adminPage, |
| 54 |
}); |
| 55 |
}; |
| 56 |
|
| 57 |
const handleSelect = (image) => { |
| 58 |
updateLogoSrcAttr(image.url, 'none'); |
| 59 |
}; |
| 60 |
|
| 61 |
return ( |
| 62 |
<Wrapper> |
| 63 |
<div className="relative p-3"> |
| 64 |
<ImageUploader |
| 65 |
type="site_logo" |
| 66 |
title={__('Site logo', 'extendify-local')} |
| 67 |
actionLabel={__('Set site logo', 'extendify-local')} |
| 68 |
onSave={handleConfirm} |
| 69 |
onCancel={onCancel} |
| 70 |
onSelect={handleSelect} |
| 71 |
/> |
| 72 |
</div> |
| 73 |
</Wrapper> |
| 74 |
); |
| 75 |
}; |
| 76 |
|
| 77 |
const Wrapper = ({ children }) => ( |
| 78 |
<div className="mb-4 ms-2 me-2 flex flex-col rounded-lg border border-gray-300 bg-gray-50"> |
| 79 |
{children} |
| 80 |
</div> |
| 81 |
); |
| 82 |
|