@wordpress/block-editor
Version:
75 lines (69 loc) • 2.69 kB
JavaScript
var _interopRequireDefault = require("@babel/runtime/helpers/interopRequireDefault");
Object.defineProperty(exports, "__esModule", {
value: true
});
exports.default = BlockColorContrastChecker;
var _element = require("@wordpress/element");
var _contrastChecker = _interopRequireDefault(require("../components/contrast-checker"));
var _useBlockRefs = require("../components/block-list/use-block-props/use-block-refs");
var _jsxRuntime = require("react/jsx-runtime");
/**
* WordPress dependencies
*/
/**
* Internal dependencies
*/
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') : undefined;
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]);
// Do not re-render if the colors have not changed.
return hasChanged ? newColors : prevColors;
}
function BlockColorContrastChecker({
clientId
}) {
const blockEl = (0, _useBlockRefs.useBlockElement)(clientId);
const [colors, setColors] = (0, _element.useReducer)(reducer, {});
// There are so many things that can change the color of a block
// So we perform this check on every render.
(0, _element.useLayoutEffect)(() => {
if (!blockEl) {
return;
}
function updateColors() {
setColors(getBlockElementColors(blockEl));
}
// Combine `useLayoutEffect` and two rAF calls to ensure that values are read
// after the current paint but before the next paint.
window.requestAnimationFrame(() => window.requestAnimationFrame(updateColors));
});
return /*#__PURE__*/(0, _jsxRuntime.jsx)(_contrastChecker.default, {
backgroundColor: colors.backgroundColor,
textColor: colors.textColor,
linkColor: colors.linkColor,
enableAlphaChecker: true
});
}
//# sourceMappingURL=contrast-checker.js.map
;