|
| 1 | +import type { Arrayable } from 'type-fest' |
| 2 | + |
| 3 | +export type BemModifiers = Record<string, boolean | undefined | null> |
| 4 | + |
| 5 | +export interface BEM { |
| 6 | + namespace: string |
| 7 | + |
| 8 | + b: ( |
| 9 | + modifiers?: BemModifiers | Arrayable<string>, |
| 10 | + customClass?: Arrayable<string>, |
| 11 | + ) => any[] |
| 12 | + e: ( |
| 13 | + element: string, |
| 14 | + modifiers?: BemModifiers | Arrayable<string>, |
| 15 | + customClass?: Arrayable<string>, |
| 16 | + ) => any[] |
| 17 | + m: (modifier: string) => string |
| 18 | + em: (element: string, modifier: string) => string |
| 19 | + is: (state: string) => string |
| 20 | +} |
| 21 | + |
| 22 | +const baseNamespace = 'kit' |
| 23 | + |
| 24 | +/** |
| 25 | + * 创建 BEM 工具函数集合 |
| 26 | + * @param block 块名 |
| 27 | + */ |
| 28 | +export function createBEM(block: string): BEM { |
| 29 | + const namespace = `${baseNamespace}-${block}` |
| 30 | + |
| 31 | + return { |
| 32 | + namespace, |
| 33 | + |
| 34 | + b(modifiers, customClass) { |
| 35 | + const classes: any[] = [namespace] |
| 36 | + |
| 37 | + if ( |
| 38 | + modifiers && |
| 39 | + typeof modifiers === 'object' && |
| 40 | + !Array.isArray(modifiers) |
| 41 | + ) { |
| 42 | + // 处理修饰符 |
| 43 | + Object.entries(modifiers).forEach(([key, value]) => { |
| 44 | + if (value) { |
| 45 | + classes.push(`${namespace}--${key}`) |
| 46 | + } |
| 47 | + }) |
| 48 | + |
| 49 | + // 处理自定义类名 |
| 50 | + if (customClass) { |
| 51 | + classes.push(customClass) |
| 52 | + } |
| 53 | + } |
| 54 | + else if (modifiers) { |
| 55 | + // 直接传入自定义类名 |
| 56 | + classes.push(modifiers) |
| 57 | + } |
| 58 | + |
| 59 | + return classes |
| 60 | + }, |
| 61 | + |
| 62 | + e(element, modifiers, customClass) { |
| 63 | + const elementClass = `${namespace}__${element}` |
| 64 | + const classes: any[] = [elementClass] |
| 65 | + |
| 66 | + if ( |
| 67 | + modifiers && |
| 68 | + typeof modifiers === 'object' && |
| 69 | + !Array.isArray(modifiers) |
| 70 | + ) { |
| 71 | + // 处理修饰符 |
| 72 | + Object.entries(modifiers).forEach(([key, value]) => { |
| 73 | + if (value) { |
| 74 | + classes.push(`${elementClass}--${key}`) |
| 75 | + } |
| 76 | + }) |
| 77 | + |
| 78 | + // 处理自定义类名 |
| 79 | + if (customClass) { |
| 80 | + classes.push(customClass) |
| 81 | + } |
| 82 | + } |
| 83 | + else if (modifiers) { |
| 84 | + // 直接传入自定义类名 |
| 85 | + classes.push(modifiers) |
| 86 | + } |
| 87 | + |
| 88 | + return classes |
| 89 | + }, |
| 90 | + |
| 91 | + m(modifier) { |
| 92 | + return `${namespace}--${modifier}` |
| 93 | + }, |
| 94 | + |
| 95 | + em(element, modifier) { |
| 96 | + return `${namespace}__${element}--${modifier}` |
| 97 | + }, |
| 98 | + |
| 99 | + is(state) { |
| 100 | + return `is-${state}` |
| 101 | + }, |
| 102 | + } |
| 103 | +} |
0 commit comments