| 1 |
import { getOption, updateOption } from '@launch/api/WPApi'; |
| 2 |
import { uploadMedia } from '@wordpress/media-utils'; |
| 3 |
|
| 4 |
/** |
| 5 |
* Uploads a logo to WordPress media library. |
| 6 |
* @param {string} url - The image URL (can be a blob or remote link) |
| 7 |
* @param {object} [options={}] - Additional options |
| 8 |
* @param {boolean} [options.forceReplace=false] - Replace existing logo even if one exists |
| 9 |
*/ |
| 10 |
export const uploadLogo = async (url, options = {}) => { |
| 11 |
try { |
| 12 |
const id = await getOption('site_logo'); |
| 13 |
if (!Number(id) || options.forceReplace) { |
| 14 |
// Transparent background is required — only these formats support it |
| 15 |
const allowedTypes = ['image/png', 'image/webp', 'image/avif']; |
| 16 |
|
| 17 |
const blob = await (await fetch(url)).blob(); |
| 18 |
if (!allowedTypes.includes(blob.type)) { |
| 19 |
throw new Error(`Unsupported image type: ${blob.type}`); |
| 20 |
} |
| 21 |
|
| 22 |
const fileExtension = blob.type.replace('image/', ''); |
| 23 |
const logoName = `ext-custom-logo-${Date.now()}`; |
| 24 |
|
| 25 |
await uploadMedia({ |
| 26 |
filesList: [ |
| 27 |
new File([blob], `${logoName}.${fileExtension}`, { |
| 28 |
type: blob.type, |
| 29 |
}), |
| 30 |
], |
| 31 |
onFileChange: async ([fileObj]) => { |
| 32 |
if (fileObj?.id) { |
| 33 |
await updateOption('site_logo', fileObj.id); |
| 34 |
} |
| 35 |
}, |
| 36 |
onError: console.error, |
| 37 |
}); |
| 38 |
} |
| 39 |
} catch (error) { |
| 40 |
console.error('Error uploading logo: ', error); |
| 41 |
} |
| 42 |
}; |
| 43 |
|