UNPKG

@wordpress/block-editor

Version:
68 lines (67 loc) 2.2 kB
// packages/block-editor/src/hooks/contrast-checker.js import { useLayoutEffect, useReducer } from "@wordpress/element"; import ContrastChecker from "../components/contrast-checker"; import { useBlockElement } from "../components/block-list/use-block-props/use-block-refs"; import { jsx } from "react/jsx-runtime"; function getComputedValue(node, property) { return node.ownerDocument.defaultView.getComputedStyle(node).getPropertyValue(property); } function getBlockElementColors(blockEl) { if (!blockEl) { return {}; } const firstLinkElement = blockEl.querySelector("a"); const linkColor = !!firstLinkElement?.innerText ? getComputedValue(firstLinkElement, "color") : void 0; const textColor = getComputedValue(blockEl, "color"); let backgroundColorNode = blockEl; let backgroundColor = getComputedValue( backgroundColorNode, "background-color" ); while (backgroundColor === "rgba(0, 0, 0, 0)" && backgroundColorNode.parentNode && backgroundColorNode.parentNode.nodeType === backgroundColorNode.parentNode.ELEMENT_NODE) { backgroundColorNode = backgroundColorNode.parentNode; backgroundColor = getComputedValue( backgroundColorNode, "background-color" ); } return { textColor, backgroundColor, linkColor }; } function reducer(prevColors, newColors) { const hasChanged = Object.keys(newColors).some( (key) => prevColors[key] !== newColors[key] ); return hasChanged ? newColors : prevColors; } function BlockColorContrastChecker({ clientId }) { const blockEl = useBlockElement(clientId); const [colors, setColors] = useReducer(reducer, {}); useLayoutEffect(() => { if (!blockEl) { return; } function updateColors() { setColors(getBlockElementColors(blockEl)); } window.requestAnimationFrame( () => window.requestAnimationFrame(updateColors) ); }); return /* @__PURE__ */ jsx( ContrastChecker, { backgroundColor: colors.backgroundColor, textColor: colors.textColor, linkColor: colors.linkColor, enableAlphaChecker: true } ); } export { BlockColorContrastChecker as default }; //# sourceMappingURL=contrast-checker.js.map