Created
October 24, 2023 22:45
-
-
Save yarinsa/d7ab076626723bcac94b59d3e128edde to your computer and use it in GitHub Desktop.
create-cx.ts
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import {prefix} from '@acme/design-tokens'; | |
import {ArgumentArray} from 'classnames'; | |
import classNames from 'classnames'; | |
type CXOptions = { | |
customPrefix?: string; | |
}; | |
export const createCX = ({customPrefix}: CXOptions = {}) => { | |
const prefixToUse = `${customPrefix ? `${prefix}__${customPrefix}` : `${prefix}`}__`; | |
const addPrefix = (className: string) => { | |
if (!className) return `${prefix}_${customPrefix}`; | |
return `${prefixToUse}${className}`; | |
}; | |
const cx = (...args: ArgumentArray): string => { | |
const processedArgs = args.map(arg => { | |
if (typeof arg === `string`) { | |
return addPrefix(arg); | |
} | |
if (Array.isArray(arg)) { | |
return cx(...arg); | |
} | |
if (typeof arg === `object`) { | |
const newObj: Record<string, any> = {}; | |
for (const key in arg) { | |
newObj[addPrefix(key)] = arg[key]; | |
} | |
return newObj; | |
} | |
return arg; | |
}); | |
return classNames(...processedArgs); | |
}; | |
return {cx, prefix: prefixToUse}; | |
}; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment