| 1 |
/** |
| 2 |
* WordPress dependencies |
| 3 |
*/ |
| 4 |
import React from "react"; |
| 5 |
import { useBlockEditContext } from "@wordpress/block-editor"; |
| 6 |
import { useSelect, useDispatch } from "@wordpress/data"; |
| 7 |
import { |
| 8 |
__experimentalToggleGroupControl as ToggleGroupControl, |
| 9 |
__experimentalToggleGroupControlOption as ToggleGroupControlOption, |
| 10 |
__experimentalToggleGroupControlOptionIcon as ToggleGroupControlOptionIcon, |
| 11 |
__experimentalToolsPanelItem as ToolsPanelItem, |
| 12 |
} from "@wordpress/components"; |
| 13 |
|
| 14 |
/** |
| 15 |
* Internal dependencies |
| 16 |
*/ |
| 17 |
import { ToggleGroupControlWithToolsPanelProps } from "./types"; |
| 18 |
|
| 19 |
/** |
| 20 |
* Toggle group control component with ToolsPanel integration |
| 21 |
* Self-managed via useBlockEditContext, wrapped in ToolsPanelItem |
| 22 |
* Supports both icon and text options (consistent with CustomToggleGroupControl) |
| 23 |
*/ |
| 24 |
const ToggleGroupControlWithToolsPanel: React.FC< |
| 25 |
ToggleGroupControlWithToolsPanelProps |
| 26 |
> = ({ |
| 27 |
label, |
| 28 |
attrKey, |
| 29 |
options, |
| 30 |
defaultValue = "", |
| 31 |
isShownByDefault = true, |
| 32 |
}) => { |
| 33 |
const { clientId } = useBlockEditContext(); |
| 34 |
|
| 35 |
const attributes = useSelect((select) => |
| 36 |
select("core/block-editor").getBlockAttributes(clientId), |
| 37 |
) as Record<string, any>; |
| 38 |
|
| 39 |
const { updateBlockAttributes } = useDispatch("core/block-editor") as any; |
| 40 |
|
| 41 |
const setAttributes = (newAttributes: Record<string, any>) => { |
| 42 |
updateBlockAttributes(clientId, newAttributes); |
| 43 |
}; |
| 44 |
|
| 45 |
const value = attributes[attrKey]; |
| 46 |
|
| 47 |
return ( |
| 48 |
<ToolsPanelItem |
| 49 |
panelId={clientId} |
| 50 |
isShownByDefault={isShownByDefault} |
| 51 |
label={label} |
| 52 |
hasValue={() => value !== defaultValue} |
| 53 |
onDeselect={() => setAttributes({ [attrKey]: defaultValue })} |
| 54 |
resetAllFilter={() => setAttributes({ [attrKey]: defaultValue })} |
| 55 |
> |
| 56 |
<ToggleGroupControl |
| 57 |
label={label} |
| 58 |
isBlock |
| 59 |
value={value} |
| 60 |
onChange={(newValue: any) => { |
| 61 |
setAttributes({ [attrKey]: newValue }); |
| 62 |
}} |
| 63 |
__nextHasNoMarginBottom |
| 64 |
__next40pxDefaultSize |
| 65 |
> |
| 66 |
{options.map( |
| 67 |
({ value: optionValue, icon = null, label: optionLabel }) => |
| 68 |
icon ? ( |
| 69 |
<ToggleGroupControlOptionIcon |
| 70 |
key={optionValue} |
| 71 |
value={optionValue} |
| 72 |
icon={icon} |
| 73 |
label={optionLabel} |
| 74 |
/> |
| 75 |
) : ( |
| 76 |
<ToggleGroupControlOption |
| 77 |
key={optionValue} |
| 78 |
value={optionValue} |
| 79 |
label={optionLabel} |
| 80 |
/> |
| 81 |
), |
| 82 |
)} |
| 83 |
</ToggleGroupControl> |
| 84 |
</ToolsPanelItem> |
| 85 |
); |
| 86 |
}; |
| 87 |
|
| 88 |
export default ToggleGroupControlWithToolsPanel; |
| 89 |
|