Skip to content

Instantly share code, notes, and snippets.

@jimmed
Created August 8, 2016 10:27
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save jimmed/5fbff40f54357ee7ed1ee873b0a70d1d to your computer and use it in GitHub Desktop.
Save jimmed/5fbff40f54357ee7ed1ee873b0a70d1d to your computer and use it in GitHub Desktop.
It's `suitcx`. Like `cx`, but wearing a suit.
import cx from 'classnames'
import capitalize from './capitalize'
/**
* It's `suitcx`. Like `cx`, but for suitCSS
*
* @param {string} parent - The main suitCSS class, i.e. `ChatItem` or `ChatItem-message`.
* @param {Object} [modifiers] - The suitCSS modifiers to apply, where each key is the name of the modifier applied. For each key/value pair of the object; if a value is a string, the modifier name will be the value appended to the key (in camel-case); otherwise, the modifier will only be added if the value is truthy.
* @param {Object} [state] - The suitCSS state to apply, where each key is the name of the state to be applied, and the value used to determine whether to apply the state.
*
* @returns {string} A className string suitable fit for the most stylish of elements.
*
* @example
* // returns 'ChatItem ChatItem--alignLeft ChatItem--deleted is-hovered'
* suitcx('ChatItem', { align: 'left', deleted: true }, { hovered: true })
**/
export default function suitcx (parent, modifiers = {}, state = {}) {
return cx([
parent,
...Object.keys(modifiers).reduce((classes, key) => {
const fullKey = `${parent}--${key}`
const value = modifiers[key]
if (typeof value === 'string') {
classes.push(`${fullKey}${capitalize(value)}`)
} else if (value) {
classes.push(`${fullKey}`)
}
return classes
}, []),
...Object.keys(state).reduce((classes, key) => {
if (state[key]) {
const fullKey = `is-${key}`
classes.push(fullKey)
}
return classes
}, [])
])
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment