UNPKG

@wordpress/block-library

Version:
84 lines (74 loc) 3.14 kB
"use strict"; Object.defineProperty(exports, "__esModule", { value: true }); exports.default = useCoverIsDark; var _fastAverageColor = require("fast-average-color"); var _colord = require("colord"); var _element = require("@wordpress/element"); /** * External dependencies */ /** * WordPress dependencies */ function retrieveFastAverageColor() { if (!retrieveFastAverageColor.fastAverageColor) { retrieveFastAverageColor.fastAverageColor = new _fastAverageColor.FastAverageColor(); } return retrieveFastAverageColor.fastAverageColor; } /** * useCoverIsDark is a hook that returns a boolean variable specifying if the cover * background is dark or not. * * @param {?string} url Url of the media background. * @param {?number} dimRatio Transparency of the overlay color. If an image and * color are set, dimRatio is used to decide what is used * for background darkness checking purposes. * @param {?string} overlayColor String containing the overlay color value if one exists. * @param {?Object} elementRef If a media background is set, elementRef should contain a reference to a * dom element that renders that media. * * @return {boolean} True if the cover background is considered "dark" and false otherwise. */ function useCoverIsDark(url) { let dimRatio = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : 50; let overlayColor = arguments.length > 2 ? arguments[2] : undefined; let elementRef = arguments.length > 3 ? arguments[3] : undefined; const [isDark, setIsDark] = (0, _element.useState)(false); (0, _element.useEffect)(() => { // If opacity is lower than 50 the dominant color is the image or video color, // so use that color for the dark mode computation. if (url && dimRatio <= 50 && elementRef.current) { retrieveFastAverageColor().getColorAsync(elementRef.current, { // Previously the default color was white, but that changed // in v6.0.0 so it has to be manually set now. defaultColor: [255, 255, 255, 255], // Errors that come up don't reject the promise, so error // logging has to be silenced with this option. silent: process.env.NODE_ENV === 'production' }).then(color => setIsDark(color.isDark)); } }, [url, url && dimRatio <= 50 && elementRef.current, setIsDark]); (0, _element.useEffect)(() => { // If opacity is greater than 50 the dominant color is the overlay color, // so use that color for the dark mode computation. if (dimRatio > 50 || !url) { if (!overlayColor) { // If no overlay color exists the overlay color is black (isDark ) setIsDark(true); return; } setIsDark((0, _colord.colord)(overlayColor).isDark()); } }, [overlayColor, dimRatio > 50 || !url, setIsDark]); (0, _element.useEffect)(() => { if (!url && !overlayColor) { // Reset isDark. setIsDark(false); } }, [!url && !overlayColor, setIsDark]); return isDark; } //# sourceMappingURL=use-cover-is-dark.js.map