Skip to content

Commit

Permalink
feat: add tailwind class function
Browse files Browse the repository at this point in the history
  • Loading branch information
Arcath committed May 5, 2023
1 parent 6c0e2e5 commit 79acb19
Show file tree
Hide file tree
Showing 2 changed files with 74 additions and 0 deletions.
24 changes: 24 additions & 0 deletions src/functions/tailwind.spec.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,24 @@
import {twClassNameFn} from './tailwind'

describe('Tailwind', () => {
it('should create a class function', () => {
const inputClasses = twClassNameFn(['bg-white', 'text-green', 'm-auto'])

expect(inputClasses()).toBe('bg-white text-green m-auto')
expect(inputClasses(['bg-yellow'])).toBe('text-green m-auto bg-yellow')
expect(inputClasses(['border'])).toBe('bg-white text-green m-auto border')
})

it('should override correctly', () => {
const inputClasses = twClassNameFn(
'w-full border border-gray-300 rounded p-2 xl:p-4 mt-2 mb-4 shadow'
)

expect(inputClasses()).toBe(
'w-full border border-gray-300 rounded p-2 xl:p-4 mt-2 mb-4 shadow'
)
expect(inputClasses('shadow-xl p-4')).toBe(
'w-full border border-gray-300 rounded xl:p-4 mt-2 mb-4 shadow-xl p-4'
)
})
})
50 changes: 50 additions & 0 deletions src/functions/tailwind.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,50 @@
/**
* Provides a function for building Tailwind Class Strings. Define default classes that are then modified when the function is called.
*
* Example:
*
* ```
* const buttonClasses = twClassNameFn(['rounded', 'shadow'])
*
* buttonClasses() // 'rounded shadow'
* buttonClasses('shadow-xl bg-green') // 'rounded shadow-xl bg-green'
* ```
*
* @param twClasses A string or array of tailwind classes.
* @returns A function to add/replace classes in the class string.
*/
export const twClassNameFn = (twClasses: string[] | string) => {
const defaultClasses =
typeof twClasses === 'string' ? twClasses.split(' ') : twClasses

/**
* Add/Replace tailwind classes.
*
* @param classNames A string or array of tailwind classes.
* @returns A string of tailwind classes.
*/
return (classNames: string[] | string = []) => {
const classes =
typeof classNames === 'string' ? classNames.split(' ') : classNames

let classesToApply = defaultClasses.map(className => {
const [prefix, value] = className.split('-')

return {prefix, value, className}
})

classes.forEach(className => {
const [prefix, value] = className.split('-')

classesToApply = classesToApply.filter(applicable => {
return applicable.prefix !== prefix
})

classesToApply.push({prefix, value, className})
})

return classesToApply.map(({className}) => className).join(' ')
}
}

// {twClassNameFn}

0 comments on commit 79acb19

Please sign in to comment.