| 1 |
/** |
| 2 |
* WordPress dependencies |
| 3 |
*/ |
| 4 |
import React from "react"; |
| 5 |
import { useDispatch, useSelect } from "@wordpress/data"; |
| 6 |
import { useBlockEditContext } from "@wordpress/block-editor"; |
| 7 |
import { |
| 8 |
__experimentalToggleGroupControl as ToggleGroupControl, |
| 9 |
__experimentalToggleGroupControlOptionIcon as ToggleGroupControlOptionIcon, |
| 10 |
__experimentalToggleGroupControlOption as ToggleGroupControlOption, |
| 11 |
} from "@wordpress/components"; |
| 12 |
|
| 13 |
/** |
| 14 |
* Internal dependencies |
| 15 |
*/ |
| 16 |
import { ToggleGroupControlProps } from "./types"; |
| 17 |
|
| 18 |
/** |
| 19 |
* Toggle group control component |
| 20 |
* Provides a toggle group with optional icons |
| 21 |
*/ |
| 22 |
const CustomToggleGroupControl: React.FC<ToggleGroupControlProps> = ({ |
| 23 |
label, |
| 24 |
options, |
| 25 |
attributeKey, |
| 26 |
isBlock = false, |
| 27 |
isAdaptiveWidth = false, |
| 28 |
}) => { |
| 29 |
const { clientId } = useBlockEditContext(); |
| 30 |
const { updateBlockAttributes } = useDispatch("core/block-editor") as any; |
| 31 |
|
| 32 |
const attributes = useSelect((select) => { |
| 33 |
return select("core/block-editor").getBlockAttributes(clientId); |
| 34 |
}) as Record<string, any>; |
| 35 |
|
| 36 |
const setAttributes = (newAttributes: Record<string, any>) => |
| 37 |
updateBlockAttributes(clientId, newAttributes); |
| 38 |
|
| 39 |
return ( |
| 40 |
<ToggleGroupControl |
| 41 |
label={label} |
| 42 |
isBlock={isBlock} |
| 43 |
isAdaptiveWidth={isAdaptiveWidth} |
| 44 |
__next40pxDefaultSize |
| 45 |
__nextHasNoMarginBottom |
| 46 |
value={attributes[attributeKey]} |
| 47 |
onChange={(newValue: any) => { |
| 48 |
setAttributes({ |
| 49 |
[attributeKey]: newValue, |
| 50 |
}); |
| 51 |
}} |
| 52 |
> |
| 53 |
{options.map(({ value, icon = null, label: optionLabel }) => { |
| 54 |
return icon ? ( |
| 55 |
<ToggleGroupControlOptionIcon |
| 56 |
key={value} |
| 57 |
value={value} |
| 58 |
icon={icon} |
| 59 |
label={optionLabel} |
| 60 |
/> |
| 61 |
) : ( |
| 62 |
<ToggleGroupControlOption |
| 63 |
key={value} |
| 64 |
value={value} |
| 65 |
label={optionLabel} |
| 66 |
/> |
| 67 |
); |
| 68 |
})} |
| 69 |
</ToggleGroupControl> |
| 70 |
); |
| 71 |
}; |
| 72 |
|
| 73 |
export default CustomToggleGroupControl; |
| 74 |
|