Writing an Elm UI Framework — Part 2: Colors
This is part 2 in a series of posts about our experience from developing a UI Framework in Elm at Special-Elektronik. If you haven’t read the introduction, I encourage you to read it here.
Colors and color management is one of the first things you come across when you read the documentation on a CSS framework. I was pretty satisfied with the API of the Color module, so it felt natural to begin this series with how the Colour module is built.
How to represent color on the web
Browsers can represent colors in a few different ways. Keywords, HEX, RGB(A) and HSL(A). HEX seems to be the most popular choice, perhaps due to the lack of browser support in older browsers and the fact that Photoshop defaults to HEX. But HSL(A) is supported in all major browsers, and I see no reason not to use it. Sara Soueidans's article On Switching from HEX & RGB to HSL was a great inspiration, it’s well worth a read.
Lighten and darken
Most CSS Framework has methods to increase or decrease the lightness of a color. Usually through SASS functions not available in pure CSS. It’s really helpful when you want to apply a certain :hover transformation for buttons and other clickable elements. With HSL(A) we do not need a custom function since the L in HSL(A) is a simple number, increase and the color will be lighter, decrease and you get the opposite effect.
HSL(A) in Elm
We use Elm CSS as the basis for our UI framework and it has its own set of functions for HSL(A) support. Unfortunately, the Color Type is opaque which means we can’t alter it once it has been set. Enter our own intermediate HSL(A) type!
Our Colors.elm module define several types with very specific responsibilities.
Mapping over colors
Every internal value (Hue, Saturation, Lightness, Alpha) has its own mapping function. The mapping function takes a transformation function that determines how to modify the value and the HSLA value.
These helper functions create a very streamlined and easy-to-read code in my opinion.
Invert
The invert function is inspired by Bulma's findColorInvert
function. It takes a color and inverts it, very useful to set the text color of a dark background. And together with the hover function, it produces some neat effects when the background changes from light to dark. Thanks to HSLA, the function is significantly simpler than the Bulma counterpart.
For those of you who are more experienced with Elm, you probably recognize this pattern as the withStar / Builder pattern which is the next part of this series (coming soon).
How do you handle colors in your Elm project?