@betarena/ad-engine
Version:
Betarena ad-engine widget
161 lines (148 loc) • 4.8 kB
text/typescript
// ╭──────────────────────────────────────────────────────────────────────────────────╮
// │ 📌 High Order Component Overview │
// ┣──────────────────────────────────────────────────────────────────────────────────┫
// │ ➤ Internal Svelte Code Format :|: V.8.0 │
// │ ➤ Status :|: 🔒 LOCKED │
// │ ➤ Author(s) :|: @migbash │
// ┣──────────────────────────────────────────────────────────────────────────────────┫
// │ 📝 Description │
// ┣──────────────────────────────────────────────────────────────────────────────────┫
// │ Main Scores Color Thief Logic │
// ╰──────────────────────────────────────────────────────────────────────────────────╯
// #region ➤ 📦 Package Imports
// @ts-expect-error :: 📌 Importing the colorthief package for Types Is missing.
import ColorThief from 'colorthief/dist/color-thief.mjs';
// #endregion ➤ 📦 Package Imports
const colorThief = new ColorThief();
/**
* @author
* @migbash
* @summary
* 🟦 HELPER
* @description
* 📝 Convert RGB to Hexidecimal
* @param { number } r
* ❗️ **REQUIRED** : Red Value
* @param { number } g
* ❗️ **REQUIRED** : Green Value
* @param { number } b
* ❗️ **REQUIRED** : Blue Value
* @return { string }
* 📤 Hexidecimal Value for target RGB input.
*/
export const rgbToHex = (
r: number,
g: number,
b: number
): string =>
{
return '#' + [r, g, b]
.map
(
(
x
) =>
{
const
/**
* @description
* 📝 Convert the number to HEX
*/
hex = x.toString(16)
;
return hex.length === 1
? `0${hex}`
: hex
;
}
)
.join('')
;
}
/**
* @author
* @migbash
* @summary
* 🟦 HELPER
* @description
* 📝 Get the image background color
* @param { string } strImageUrl
* ❗️ **REQUIRED** : The image URL
* @param { string } strImageColorVariable
* ❗️ **REQUIRED** : The image variable
* @return { void }
*/
export function getImageBgColor
(
strImageUrl: string,
strImageColorVariable: string
): void
{
if (!strImageUrl) return;
try
{
const
/**
* @description
* 📝 Create a new image instance
*/
img = new Image()
;
// ╭─────
// │ NOTE:
// │ |: Listen, event to wait for the image to load
// ╰─────
img.addEventListener
(
'load',
() =>
{
const
/**
* @description
* 📝 Get the color values from the image
*/
colorValues
= colorThief.getColor(img) as [number, number, number],
/**
* @description
* 📝 Convert the color values to HEX
*/
hexColor
= rgbToHex
(
colorValues[0],
colorValues[1],
colorValues[2]
),
/**
* @description
* 📝 Pass this values as a `CSS :root` variable, accessible to all the website,
*/
doc = document.documentElement
;
doc.style.setProperty
(
strImageColorVariable,
hexColor
);
}
);
const
// [ℹ] declaring the image paramaters & CORS by-pass
imageURL = 'https://corsproxy.io/?' + encodeURIComponent(strImageUrl)
;
img.crossOrigin = 'anonymous';
img.src = imageURL;
}
catch (e)
{
// eslint-disable-next-line no-console
console.error
(
'-- getImageBgColor() ERR --',
e
);
}
return;
}