bem.js 988 B

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748
  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. var ELEMENT = '__';
  10. var MODS = '--';
  11. function join(name, el, symbol) {
  12. return el ? name + symbol + el : name;
  13. }
  14. function prefix(name, mods) {
  15. if (typeof mods === 'string') {
  16. return join(name, mods, MODS);
  17. }
  18. if (Array.isArray(mods)) {
  19. return mods.map(function (item) {
  20. return prefix(name, item);
  21. });
  22. }
  23. var ret = {};
  24. if (mods) {
  25. Object.keys(mods).forEach(function (key) {
  26. ret[name + MODS + key] = mods[key];
  27. });
  28. }
  29. return ret;
  30. }
  31. export var useBEM = function useBEM(name) {
  32. return function (el, mods) {
  33. if (el && typeof el !== 'string') {
  34. mods = el;
  35. el = '';
  36. }
  37. el = join(name, el, ELEMENT);
  38. return mods ? [el, prefix(el, mods)] : el;
  39. };
  40. };