2020-08-22 07:20:08 -04:00
|
|
|
interface colorScheme {
|
2020-08-29 05:43:00 -04:00
|
|
|
hash: string, /// Regenerate color scheme when the image hash is changed
|
2020-08-22 07:20:08 -04:00
|
|
|
DarkMuted: {
|
|
|
|
hex: string,
|
|
|
|
rgb: Number[],
|
|
|
|
bodyTextColor: string
|
|
|
|
},
|
|
|
|
Vibrant: {
|
|
|
|
hex: string,
|
|
|
|
rgb: Number[],
|
|
|
|
bodyTextColor: string
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
let colorsCache: { [key: string]: colorScheme } = {};
|
|
|
|
|
2020-08-28 06:11:02 -04:00
|
|
|
if (localStorage.hasOwnProperty('StackColorsCache')) {
|
2020-08-22 07:20:08 -04:00
|
|
|
try {
|
2020-08-28 06:11:02 -04:00
|
|
|
colorsCache = JSON.parse(localStorage.getItem('StackColorsCache'));
|
2020-08-22 07:20:08 -04:00
|
|
|
}
|
|
|
|
catch (e) {
|
|
|
|
colorsCache = {};
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
2020-08-29 05:43:00 -04:00
|
|
|
async function getColor(key: string, hash: string, imageURL: string) {
|
|
|
|
if (!key) {
|
|
|
|
/**
|
|
|
|
* If no key is provided, do not cache the result
|
|
|
|
*/
|
|
|
|
return await Vibrant.from(imageURL).getPalette();
|
|
|
|
}
|
|
|
|
|
|
|
|
if (!colorsCache.hasOwnProperty(key) || colorsCache[key].hash !== hash) {
|
|
|
|
/**
|
|
|
|
* If key is provided, but not found in cache, or the hash mismatches => Regenerate color scheme
|
|
|
|
*/
|
2020-08-22 07:20:08 -04:00
|
|
|
const palette = await Vibrant.from(imageURL).getPalette();
|
|
|
|
|
2020-08-29 05:43:00 -04:00
|
|
|
colorsCache[key] = {
|
|
|
|
hash: hash,
|
2020-08-22 07:20:08 -04:00
|
|
|
Vibrant: {
|
|
|
|
hex: palette.Vibrant.hex,
|
|
|
|
rgb: palette.Vibrant.rgb,
|
|
|
|
bodyTextColor: palette.Vibrant.bodyTextColor
|
|
|
|
},
|
|
|
|
DarkMuted: {
|
|
|
|
hex: palette.DarkMuted.hex,
|
|
|
|
rgb: palette.DarkMuted.rgb,
|
|
|
|
bodyTextColor: palette.DarkMuted.bodyTextColor
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
2020-08-29 05:43:00 -04:00
|
|
|
/* Save the result in localStorage */
|
2020-08-28 06:11:02 -04:00
|
|
|
localStorage.setItem('StackColorsCache', JSON.stringify(colorsCache));
|
2020-08-22 07:20:08 -04:00
|
|
|
}
|
2020-08-28 06:11:02 -04:00
|
|
|
|
2020-08-29 05:43:00 -04:00
|
|
|
return colorsCache[key];
|
2020-08-22 07:20:08 -04:00
|
|
|
}
|
|
|
|
|
|
|
|
export {
|
|
|
|
getColor
|
|
|
|
}
|