Padding visualizer shows stale padding when block opts to handle application of style
Description
I have hit a wall trying to figure out how to fix this for a project of mine. The idea is that a block opts to supports > spacing > padding to let users control the padding, but block author also needs to handle style updates internally within the block, which __experimentalSkipSerialization property was introduced for (I guess).
Applying the padding is not much of a problem, however, when the user interacts with the padding controls, the visual feedback ("padding visualizer") that the editor provides when the user interacts with the padding controls is from the previous state rather then the actual padding.
Step-by-step reproduction instructions
To illustrate, I have created a Padding Test Block repo. Please look within and test at your will.
Screenshots, screen recording, code snippet
Screenshot:
Environment info
Tested on: WP 6.5.2 Twenty Twenty-Three Plugins: Padding Test Block
Please confirm that you have searched existing issues in the repo.
Yes
Please confirm that you have tested with all plugins deactivated except Gutenberg.
Yes
Seems that my method of doing style updates was not good enough. By utilizing useMemo, the padding visualizer now behaves correctly.
const paddingStyle = style?.spacing?.padding
const [blockElementStyle, setBlockElementStyle] = useState({
outline: "1px dashed red",
})
const blockPadding = useMemo(() => {
console.log("paddingStyle", paddingStyle)
if (typeof paddingStyle !== "object") {
return { padding: getBlockStyle(style, "padding") }
} else {
return {
...(paddingStyle?.top && { paddingTop: getBlockStyle(style, "paddingTop") }),
...(paddingStyle?.right && { paddingRight: getBlockStyle(style, "paddingRight") }),
...(paddingStyle?.bottom && { paddingBottom: getBlockStyle(style, "paddingBottom") }),
...(paddingStyle?.left && { paddingLeft: getBlockStyle(style, "paddingLeft") }),
}
}
}, [paddingStyle])
const blockProps = useBlockProps({
style: {
...blockElementStyle,
...blockPadding,
},
})