typestyle / csx

Utility functions for TypeStyle
https://typestyle.github.io
MIT License
102 stars 14 forks source link

Shorthand method for color function strings #31

Closed ajcrites closed 7 years ago

ajcrites commented 7 years ago

Currently rgba and other such color methods return a ColorHelper rather than a string. This means that you can't use them in Typestyle as:

color: rgba(10, 20, 30),

which would be nice / cleaner / provide type safety, etc. in my opinion.

You can do .toString(), or ${rgba(...)} for example, but that is verbose and doesn't end up saving you much over just 'rgba(...)'.

It would make more sense to me to have these functions return a string and if you wanted a color helper you could do color(rgba(...)). I think the string use case would be more common, but the contributors and community are free to disagree.

In lieu of updating the interface, there could be convenience methods like srgb() (string-rgb) that wrap the corresponding function and toString it.

notoriousb1t commented 7 years ago

Originally, TypeStyle treated ColorHelper specially and called toString() on it internally. That behavior was changed to make the API less surprising, and to make the CSX part of TypeStyle work well with any CSS-in-JS library.

At this point, it would be difficult to change this to return a string without breaking a lot of code for a lot of people. It also would be expensive to have it return a string and be capable of using sass-like color functions. For instance, if the following code had to parse the colors every time...

const primaryColor = rgb(0, 0, 255) // a string

// 2x parse color channels from string, created arrays, then stringified
const primaryHoverColor = saturate(darken(primaryColor, 0.2), 0.2) 

the code would end up spending a lot of unnecessary time parsing colors and creating arrays.

I typically end up namespacing my colors and keeping them in a separate file rather than writing out colors inline in the style definitions. Generally, I think colors end up getting a lot of reuse, and using that pattern keeps the code cleaner:

// ./shared/colors.ts
import { rgb } from 'csx'

export namespace colors {
     const primaryBase = rgb(0, 0, 255)

     export const primary = primaryBase.toHexString()
     export const primaryHover = primaryBase.darken(.2).saturate(.2).toHexString() 
}
// ./shared/index.ts
export * from './colors'
// ./components/something
import { style } from 'typestyle'
import { colors } from '../shared'

const componentClass = style({
    color: colors.primary,
    $nest: {
        '&:hover': {
              color: colors.primaryHover
         }
    }
})