diff --git a/index.d.ts b/index.d.ts new file mode 100644 index 0000000..edae489 --- /dev/null +++ b/index.d.ts @@ -0,0 +1 @@ +export { default } from "./src/cssHexColorToRGBA.js"; diff --git a/index.js b/index.js index cc9d02f..1d155b3 100644 --- a/index.js +++ b/index.js @@ -1,2 +1,2 @@ -export { default } from "./src/cssHexColorToRGB.js"; +export { default } from "./src/cssHexColorToRGBA.js"; diff --git a/src/cssHexColorToRGB.js b/src/cssHexColorToRGB.js deleted file mode 100644 index 869b6b9..0000000 --- a/src/cssHexColorToRGB.js +++ /dev/null @@ -1,17 +0,0 @@ -import isCSSHexColor from "@chriscodesthings/is-css-hex-color"; -import expandCSSHexColor from "@chriscodesthings/expand-css-hex-color"; - -function hexToDec(h) { - return parseInt(h, 16); -} - -export default function (col) { - if (!isCSSHexColor(col)) { - return; - } - - const hex = (expandCSSHexColor(col) + "ff").slice(1, 9); - const [r, g, b, a] = [hex.slice(0, 2), hex.slice(2, 4), hex.slice(4, 6), hex.slice(6, 8)]; - - return [hexToDec(r), hexToDec(g), hexToDec(b), Math.round((hexToDec(a) / 255) * 100) / 100]; -} diff --git a/src/cssHexColorToRGBA.d.ts b/src/cssHexColorToRGBA.d.ts new file mode 100644 index 0000000..de61f9e --- /dev/null +++ b/src/cssHexColorToRGBA.d.ts @@ -0,0 +1,6 @@ +/** + * Converts a colour from a CSS hex colour code to an RGBA array + * @param {string} col CSS hex colour code + * @returns {[number, number, number, number]} + */ +export default function _default(col: string): [number, number, number, number]; diff --git a/src/cssHexColorToRGBA.js b/src/cssHexColorToRGBA.js new file mode 100644 index 0000000..30b39be --- /dev/null +++ b/src/cssHexColorToRGBA.js @@ -0,0 +1,19 @@ +// @ts-check + +import expandCSSHexColor from "@chriscodesthings/expand-css-hex-color"; +import { roundToPrecision } from "more-rounding"; + +/** + * Converts a colour from a CSS hex colour code to an RGBA array + * @param {string} col CSS hex colour code + * @returns {[number, number, number, number]} + */ +export default function (col) { + const hex = expandCSSHexColor(col).slice(1); + const r = parseInt(hex.slice(0, 2), 16); + const g = parseInt(hex.slice(2, 4), 16); + const b = parseInt(hex.slice(4, 6), 16); + const a = roundToPrecision(parseInt(hex.slice(6, 8), 16) / 255, 2); + + return [r, g, b, a]; +}