67 lines
2.5 KiB
JavaScript
67 lines
2.5 KiB
JavaScript
import { useState, useEffect } from 'react';
|
|
import { __ } from '@wordpress/i18n';
|
|
import { SelectControl } from '@wordpress/components';
|
|
|
|
export function IconSelectControl(props) {
|
|
const { iconSvgId, onIconChange } = props;
|
|
|
|
const [iconData, setIconData] = useState([]);
|
|
|
|
useEffect(() => {
|
|
const fetchIconData = async () => {
|
|
try {
|
|
const response = await fetch('/wp-content/themes/local-content-pro/assets/json/icons.json');
|
|
const data = await response.json();
|
|
if (data && data.length > 0) {
|
|
setIconData(data[0].svgs); // Assuming the structure is correct
|
|
}
|
|
} catch (error) {
|
|
console.error('Error fetching icons:', error);
|
|
}
|
|
};
|
|
|
|
fetchIconData();
|
|
}, []);
|
|
|
|
const handleIconChange = (selectedIconId) => {
|
|
const selectedIcon = iconData.find(icon => icon.id === selectedIconId);
|
|
if (selectedIcon && onIconChange) {
|
|
// Send both icon ID and path (SVG) to the parent component
|
|
onIconChange({
|
|
iconSvgId: selectedIcon.id, // Pass icon ID to parent
|
|
iconSvgPath: selectedIcon.path // Pass icon path (SVG) to parent
|
|
});
|
|
console.log("Selected Icon ID:", selectedIcon.id); // Debugging output
|
|
console.log("Selected Icon Path:", selectedIcon.path); // Debugging output
|
|
}
|
|
};
|
|
|
|
if (iconData.length === 0) {
|
|
return <p>{__('Loading icons...', 'lcp')}</p>; // Loading state
|
|
}
|
|
|
|
const iconOptions = iconData.map((icon) => ({
|
|
value: icon.id, // Use icon ID as value for the SelectControl
|
|
label: (
|
|
<div style={{ display: 'flex', alignItems: 'center' }}>
|
|
<svg
|
|
xmlns="http://www.w3.org/2000/svg"
|
|
viewBox={icon.viewBox || "0 0 512 512"} // Default viewBox if not present
|
|
style={{ width: '20px', height: '20px' }} // Control icon size
|
|
dangerouslySetInnerHTML={{ __html: icon.path }} // Insert SVG path
|
|
/>
|
|
<span style={{ marginLeft: '8px' }}>{icon.name}</span> {/* Show icon name */}
|
|
</div>
|
|
),
|
|
}));
|
|
|
|
return (
|
|
<SelectControl
|
|
label={__('Select Icon', 'lcp')}
|
|
value={iconSvgId} // Current selected icon ID
|
|
options={iconOptions}
|
|
onChange={handleIconChange} // Handle icon change
|
|
/>
|
|
);
|
|
}
|