forked from youzan/vant
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathbem.ts
More file actions
51 lines (41 loc) · 1.14 KB
/
bem.ts
File metadata and controls
51 lines (41 loc) · 1.14 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
/**
* 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[];
const ELEMENT = '__';
const MODS = '--';
function join(name: string, el?: string, symbol?: string): string {
return el ? name + symbol + el : name;
}
function prefix(name: string, mods: Mods): Mods {
if (typeof mods === 'string') {
return join(name, mods, MODS);
}
if (Array.isArray(mods)) {
return mods.map(item => <Mod>prefix(name, item));
}
const ret: Mods = {};
if (mods) {
Object.keys(mods).forEach(key => {
ret[name + MODS + key] = mods[key];
});
}
return ret;
}
export function createBEM(name: string) {
return function(el?: Mods, mods?: Mods): Mods {
if (el && typeof el !== 'string') {
mods = el;
el = '';
}
el = join(name, el, ELEMENT);
return mods ? [el, prefix(el, mods)] : el;
};
}
export type BEM = ReturnType<typeof createBEM>;