Welcome to mirror list, hosted at ThFree Co, Russian Federation.

color.ts « ts « assets - github.com/CaiJimmy/hugo-theme-stack.git - Unnamed repository; edit this file 'description' to name the repository.
summaryrefslogtreecommitdiff
blob: 50581d104500786de1b0abfb91853367aed327fc (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
interface colorScheme {
    hash: string,                        /// Regenerate color scheme when the image hash is changed
    DarkMuted: {
        hex: string,
        rgb: Number[],
        bodyTextColor: string
    },
    Vibrant: {
        hex: string,
        rgb: Number[],
        bodyTextColor: string
    }
}

let colorsCache: { [key: string]: colorScheme } = {};

if (localStorage.hasOwnProperty('StackColorsCache')) {
    try {
        colorsCache = JSON.parse(localStorage.getItem('StackColorsCache'));
    }
    catch (e) {
        colorsCache = {};
    }
}

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
         */
        const palette = await Vibrant.from(imageURL).getPalette();

        colorsCache[key] = {
            hash: hash,
            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
            }
        }

        /* Save the result in localStorage */
        localStorage.setItem('StackColorsCache', JSON.stringify(colorsCache));
    }

    return colorsCache[key];
}

export {
    getColor
}