Created
February 24, 2022 07:21
-
-
Save Mitscherlich/251799a0248d5534391c7c128a7bdec3 to your computer and use it in GitHub Desktop.
createBEM helper
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
/** | |
* bem helper | |
* b() // 'button' | |
* b('text') // 'button__text' | |
* b({ disabled }) // 'button button--disabled' | |
* b('text', { disabled }) // 'button__text button__text--disabled' | |
* b(['disabled', 'primary']) // 'button button--disabled button--primary' | |
*/ | |
export type Mod = string | { [key: string]: any } | |
export type Mods = Mod | Mod[] | |
function gen(name: string, mods?: Mods): string { | |
if (!mods) { | |
return '' | |
} | |
if (typeof mods === 'string') { | |
return ` ${name}--${mods}` | |
} | |
if (Array.isArray(mods)) { | |
return mods.reduce<string>((ret, item) => ret + gen(name, item), '') | |
} | |
return Object.keys(mods).reduce( | |
(ret, key) => ret + (mods[key] ? gen(name, key) : ''), | |
'', | |
) | |
} | |
export function createBEM(name: string) { | |
return (el?: Mods, mods?: Mods): Mods => { | |
if (el && typeof el !== 'string') { | |
mods = el | |
el = '' | |
} | |
el = el ? `${name}__${el}` : name | |
return `${el}${gen(el, mods)}` | |
} | |
} | |
export type BEM = ReturnType<typeof createBEM> |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment