| 1 |
import getColor from "./getColor.js"; |
| 2 |
// import defaults from "./defaults.js"; |
| 3 |
import { isString } from "./util.js"; |
| 4 |
import * as contrastAlgorithms from "./contrast/index.js"; |
| 5 |
|
| 6 |
/** @import { ColorTypes } from "./types.js" */ |
| 7 |
|
| 8 |
// Type re-exports |
| 9 |
/** @typedef {import("./types.js").Algorithms} Algorithms */ |
| 10 |
|
| 11 |
/** |
| 12 |
* |
| 13 |
* @param {ColorTypes} background |
| 14 |
* @param {ColorTypes} foreground |
| 15 |
* @param {Algorithms | ({ algorithm: Algorithms } & Record<string, any>)} o |
| 16 |
* Algorithm to use as well as any other options to pass to the contrast function |
| 17 |
* @returns {number} |
| 18 |
* @throws {TypeError} Unknown or unspecified algorithm |
| 19 |
*/ |
| 20 |
export default function contrast (background, foreground, o) { |
| 21 |
if (isString(o)) { |
| 22 |
o = { algorithm: o }; |
| 23 |
} |
| 24 |
|
| 25 |
let { algorithm, ...rest } = o || {}; |
| 26 |
|
| 27 |
if (!algorithm) { |
| 28 |
let algorithms = Object.keys(contrastAlgorithms) |
| 29 |
.map(a => a.replace(/^contrast/, "")) |
| 30 |
.join(", "); |
| 31 |
throw new TypeError( |
| 32 |
`contrast() function needs a contrast algorithm. Please specify one of: ${algorithms}`, |
| 33 |
); |
| 34 |
} |
| 35 |
|
| 36 |
background = getColor(background); |
| 37 |
foreground = getColor(foreground); |
| 38 |
|
| 39 |
for (let a in contrastAlgorithms) { |
| 40 |
if ("contrast" + algorithm.toLowerCase() === a.toLowerCase()) { |
| 41 |
return contrastAlgorithms[a](background, foreground, rest); |
| 42 |
} |
| 43 |
} |
| 44 |
|
| 45 |
throw new TypeError(`Unknown contrast algorithm: ${algorithm}`); |
| 46 |
} |