bem.ts 1.3 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152
  1. import { prefixCls } from '/@/settings/designSetting';
  2. type Mod = string | { [key: string]: any };
  3. type Mods = Mod | Mod[];
  4. export type BEM = ReturnType<typeof createBEM>;
  5. function genBem(name: string, mods?: Mods): string {
  6. if (!mods) {
  7. return '';
  8. }
  9. if (typeof mods === 'string') {
  10. return ` ${name}--${mods}`;
  11. }
  12. if (Array.isArray(mods)) {
  13. return mods.reduce<string>((ret, item) => ret + genBem(name, item), '');
  14. }
  15. return Object.keys(mods).reduce((ret, key) => ret + (mods[key] ? genBem(name, key) : ''), '');
  16. }
  17. /**
  18. * bem helper
  19. * b() // 'button'
  20. * b('text') // 'button__text'
  21. * b({ disabled }) // 'button button--disabled'
  22. * b('text', { disabled }) // 'button__text button__text--disabled'
  23. * b(['disabled', 'primary']) // 'button button--disabled button--primary'
  24. */
  25. export function buildBEM(name: string) {
  26. return (el?: Mods, mods?: Mods): Mods => {
  27. if (el && typeof el !== 'string') {
  28. mods = el;
  29. el = '';
  30. }
  31. el = el ? `${name}__${el}` : name;
  32. return `${el}${genBem(el, mods)}`;
  33. };
  34. }
  35. export function createBEM(name: string) {
  36. return [buildBEM(`${prefixCls}-${name}`)];
  37. }
  38. export function createNamespace(name: string) {
  39. const prefixedName = `${prefixCls}-${name}`;
  40. return [prefixedName, buildBEM(prefixedName)] as const;
  41. }