| 1 |
import { isString } from "./util.js"; |
| 2 |
import getColor from "./getColor.js"; |
| 3 |
|
| 4 |
/** @import { ColorTypes, PlainColorObject } from "./types.js" */ |
| 5 |
|
| 6 |
// Type re-exports |
| 7 |
/** @typedef {import("./types.js").TryColorOptions} TryColorOptions */ |
| 8 |
|
| 9 |
/** |
| 10 |
* Resolves a color reference (object or string) to a plain color object, or `null` if resolution fails. |
| 11 |
* Can resolve more complex CSS colors (e.g. relative colors, `calc()`, CSS variables, `color-mix()`, etc.) through the DOM. |
| 12 |
* |
| 13 |
* @overload |
| 14 |
* @param {ColorTypes} color |
| 15 |
* @param {TryColorOptions} [options] |
| 16 |
* @returns {PlainColorObject | null} |
| 17 |
*/ |
| 18 |
/** |
| 19 |
* @overload |
| 20 |
* @param {ColorTypes[]} color |
| 21 |
* @param {TryColorOptions} [options] |
| 22 |
* @returns {(PlainColorObject | null)[]} |
| 23 |
*/ |
| 24 |
export default function tryColor (color, options = {}) { |
| 25 |
if (Array.isArray(color)) { |
| 26 |
return color.map(c => tryColor(c, options)); |
| 27 |
} |
| 28 |
|
| 29 |
let { cssProperty = "background-color", element, ...getColorOptions } = options; |
| 30 |
let error = null; |
| 31 |
try { |
| 32 |
return getColor(color, getColorOptions); |
| 33 |
} |
| 34 |
catch (e) { |
| 35 |
error = e; |
| 36 |
} |
| 37 |
|
| 38 |
let { CSS, getComputedStyle } = globalThis; |
| 39 |
if (isString(color) && element && CSS && getComputedStyle) { |
| 40 |
// Try resolving the color using the DOM, if supported in CSS |
| 41 |
if (CSS.supports(cssProperty, color)) { |
| 42 |
let previousValue = element.style[cssProperty]; |
| 43 |
|
| 44 |
if (color !== previousValue) { |
| 45 |
element.style[cssProperty] = color; |
| 46 |
} |
| 47 |
|
| 48 |
let computedColor = getComputedStyle(element).getPropertyValue(cssProperty); |
| 49 |
|
| 50 |
if (color !== previousValue) { |
| 51 |
element.style[cssProperty] = previousValue; |
| 52 |
} |
| 53 |
|
| 54 |
if (computedColor !== color) { |
| 55 |
// getComputedStyle() changed the color, try again |
| 56 |
try { |
| 57 |
return getColor(computedColor, getColorOptions); |
| 58 |
} |
| 59 |
catch (e) { |
| 60 |
error = e; |
| 61 |
} |
| 62 |
} |
| 63 |
else { |
| 64 |
// Still not resolved |
| 65 |
error = { |
| 66 |
message: "Color value is a valid CSS color, but it could not be resolved :(", |
| 67 |
}; |
| 68 |
} |
| 69 |
} |
| 70 |
} |
| 71 |
|
| 72 |
// If we're here, we failed to resolve the color |
| 73 |
if (options.errorMeta) { |
| 74 |
options.errorMeta.error = error; |
| 75 |
} |
| 76 |
|
| 77 |
return null; |
| 78 |
} |