bem.ts 1.1 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647
  1. /**
  2. * bem helper
  3. * b() // 'button'
  4. * b('text') // 'button__text'
  5. * b({ disabled }) // 'button button--disabled'
  6. * b('text', { disabled }) // 'button__text button__text--disabled'
  7. * b(['disabled', 'primary']) // 'button button--disabled button--primary'
  8. */
  9. export type Mod = string | { [key: string]: any };
  10. export type Mods = Mod | Mod[];
  11. const ELEMENT = '__';
  12. const MODS = '--';
  13. function join(name: string, el?: string, symbol?: string): string {
  14. return el ? name + symbol + el : name;
  15. }
  16. function prefix(name: string, mods: Mods): Mods {
  17. if (typeof mods === 'string') {
  18. return join(name, mods, MODS);
  19. }
  20. if (Array.isArray(mods)) {
  21. return mods.map(item => <Mod>prefix(name, item));
  22. }
  23. const ret: Mods = {};
  24. if (mods) {
  25. Object.keys(mods).forEach(key => {
  26. ret[name + MODS + key] = mods[key];
  27. });
  28. }
  29. return ret;
  30. }
  31. export const useBEM = (name: string) => (el?: Mods, mods?: Mods): Mods => {
  32. if (el && typeof el !== 'string') {
  33. mods = el;
  34. el = '';
  35. }
  36. el = join(name, el, ELEMENT);
  37. return mods ? [el, prefix(el, mods)] : el;
  38. };