From b3dbc0f4179ff097696f2619d8d14d0234f170d2 Mon Sep 17 00:00:00 2001 From: "D. Berge" Date: Wed, 8 Nov 2023 18:05:50 +0100 Subject: [PATCH] Add utility function to create HSL colours --- lib/www/client/source/src/lib/hsl.js | 47 ++++++++++++++++++++++++++++ 1 file changed, 47 insertions(+) create mode 100644 lib/www/client/source/src/lib/hsl.js diff --git a/lib/www/client/source/src/lib/hsl.js b/lib/www/client/source/src/lib/hsl.js new file mode 100644 index 0000000..a3e342f --- /dev/null +++ b/lib/www/client/source/src/lib/hsl.js @@ -0,0 +1,47 @@ +/** Return an HSL colour as a function of an input value + * `str`. + * + * Consider using as getHSL.bind(this) in Vue components + * in order to get access to the Vuetify theme configuration. + */ +function getHSL (str, saturation = 1, lightness = 0.25, offset = 0) { + + function getHash (v) { + if (typeof (v??false)[Symbol.iterator] != "function") { + // Not an iterable, make it one + v = String(v); + } + + return Math.abs([...v, ..." "].reduce( (acc, cur) => String(cur).charCodeAt(0) + ((acc << 5) - acc), 0 )); + } + + const h = (getHash(str) + offset) % 360; + const s = saturation * 100; + const l = this?.$vuetify?.theme?.isDark + ? (1-lightness) * 100 + : lightness * 100; + + return {h, s, l}; + +} + +/** Return a CSS hsl() or hsla() colour + * representation as a function of an input value. + * + * Consider using as getHSLColourFor.bind(this) – See + * note for getHSL() above. + */ +function getHSLColourFor (str, opacity = 1, saturation, lightness, offset) { + const _getHSL = getHSL.bind(this); + const {h, s, l} = _getHSL(str, saturation, lightness, offset); + if (opacity == 1) { + return `hsl(${h},${s}%,${l}%)`; + } else { + return `hsla(${h},${s}%,${l}%, ${opacity})`; + } +} + +export { + getHSL, + getHSLColourFor +}