| 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 |
ToggleControl, |
| 9 |
__experimentalToolsPanelItem as ToolsPanelItem, |
| 10 |
} from "@wordpress/components"; |
| 11 |
|
| 12 |
/** |
| 13 |
* Internal dependencies |
| 14 |
*/ |
| 15 |
import { ToggleControlWithToolsPanelProps } from "./types"; |
| 16 |
|
| 17 |
/** |
| 18 |
* Toggle control component with ToolsPanel integration |
| 19 |
* Self-managed via useBlockEditContext, wrapped in ToolsPanelItem |
| 20 |
*/ |
| 21 |
const ToggleControlWithToolsPanel: React.FC< |
| 22 |
ToggleControlWithToolsPanelProps |
| 23 |
> = ({ |
| 24 |
label, |
| 25 |
attrKey, |
| 26 |
defaultValue = false, |
| 27 |
isShownByDefault = true, |
| 28 |
help = "", |
| 29 |
}) => { |
| 30 |
const { clientId } = useBlockEditContext(); |
| 31 |
|
| 32 |
const attributes = useSelect((select) => |
| 33 |
select("core/block-editor").getBlockAttributes(clientId), |
| 34 |
) as Record<string, any>; |
| 35 |
|
| 36 |
const { updateBlockAttributes } = useDispatch("core/block-editor") as any; |
| 37 |
|
| 38 |
const setAttributes = (newAttributes: Record<string, any>) => { |
| 39 |
updateBlockAttributes(clientId, newAttributes); |
| 40 |
}; |
| 41 |
|
| 42 |
const checked = attributes[attrKey]; |
| 43 |
|
| 44 |
return ( |
| 45 |
<ToolsPanelItem |
| 46 |
panelId={clientId} |
| 47 |
isShownByDefault={isShownByDefault} |
| 48 |
label={label} |
| 49 |
hasValue={() => checked !== defaultValue} |
| 50 |
onDeselect={() => setAttributes({ [attrKey]: defaultValue })} |
| 51 |
resetAllFilter={() => setAttributes({ [attrKey]: defaultValue })} |
| 52 |
> |
| 53 |
<ToggleControl |
| 54 |
label={label} |
| 55 |
checked={checked} |
| 56 |
onChange={(newValue: boolean) => { |
| 57 |
setAttributes({ [attrKey]: newValue }); |
| 58 |
}} |
| 59 |
help={help} |
| 60 |
__nextHasNoMarginBottom |
| 61 |
/> |
| 62 |
</ToolsPanelItem> |
| 63 |
); |
| 64 |
}; |
| 65 |
|
| 66 |
export default ToggleControlWithToolsPanel; |
| 67 |
|