// packages/block-library/src/cover/edit/color-utils.js
import { colord, extend } from "colord";
import namesPlugin from "colord/plugins/names";
import { FastAverageColor } from "fast-average-color";
import memoize from "memize";
import { applyFilters } from "@wordpress/hooks";
extend([namesPlugin]);
var DEFAULT_BACKGROUND_COLOR = "#FFF";
var DEFAULT_OVERLAY_COLOR = "#000";
function compositeSourceOver(source, dest) {
  return {
    r: source.r * source.a + dest.r * dest.a * (1 - source.a),
    g: source.g * source.a + dest.g * dest.a * (1 - source.a),
    b: source.b * source.a + dest.b * dest.a * (1 - source.a),
    a: source.a + dest.a * (1 - source.a)
  };
}
function retrieveFastAverageColor() {
  if (!retrieveFastAverageColor.fastAverageColor) {
    retrieveFastAverageColor.fastAverageColor = new FastAverageColor();
  }
  return retrieveFastAverageColor.fastAverageColor;
}
var getMediaColor = memoize(async (url) => {
  if (!url) {
    return DEFAULT_BACKGROUND_COLOR;
  }
  const { r, g, b, a } = colord(DEFAULT_BACKGROUND_COLOR).toRgb();
  try {
    const imgCrossOrigin = applyFilters(
      "media.crossOrigin",
      void 0,
      url
    );
    const color = await retrieveFastAverageColor().getColorAsync(url, {
      // The default color is white, which is the color
      // that is returned if there's an error.
      // colord returns alpga 0-1, FAC needs 0-255
      defaultColor: [r, g, b, a * 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",
      crossOrigin: imgCrossOrigin
    });
    return color.hex;
  } catch (error) {
    return DEFAULT_BACKGROUND_COLOR;
  }
});
function compositeIsDark(dimRatio, overlayColor, backgroundColor) {
  if (overlayColor === backgroundColor || dimRatio === 100) {
    return colord(overlayColor).isDark();
  }
  const overlay = colord(overlayColor).alpha(dimRatio / 100).toRgb();
  const background = colord(backgroundColor).toRgb();
  const composite = compositeSourceOver(overlay, background);
  return colord(composite).isDark();
}
export {
  DEFAULT_BACKGROUND_COLOR,
  DEFAULT_OVERLAY_COLOR,
  compositeIsDark,
  compositeSourceOver,
  getMediaColor,
  retrieveFastAverageColor
};
//# sourceMappingURL=color-utils.js.map
