-
Notifications
You must be signed in to change notification settings - Fork 3.4k
Expand file tree
/
Copy pathbem.tsx
More file actions
242 lines (194 loc) · 6.03 KB
/
bem.tsx
File metadata and controls
242 lines (194 loc) · 6.03 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
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
import {
ComponentClass,
Context,
createContext,
createElement,
CSSProperties,
FC,
forwardRef,
FunctionComponent,
ReactHTML,
ReactSVG,
useContext
} from 'react';
interface CNMod {
[key: string]: unknown;
}
interface CN {
block: (name: string) => CN;
elem: (name: string) => CN;
mod: (mods?: CNMod) => CN;
mix: (...mix: CNMix[] | undefined[]) => CN;
select: (root: Document | Element) => Element | null;
selectAll: (root: Document | Element) => NodeList | null;
closest: (target: Element) => Element | null;
toString: () => string;
toClassName: () => string;
toCSSSelector: () => string;
}
type CNMix = string | CN | undefined
interface CNOptions {
elem?: string;
mod?: Record<string, unknown>;
mix?: CNMix | CNMix[] | undefined | undefined;
}
type ComponentType = FC<any> | ComponentClass<unknown, unknown> | FunctionComponent<unknown>
type TagNameType = keyof ReactHTML | keyof ReactSVG | string
type TagNames = keyof JSX.IntrinsicElements;
type TagAttrs<T extends keyof JSX.IntrinsicElements> = JSX.IntrinsicElements[T];
export type CNTagName = ComponentType | TagNameType;
type WrappedComponentProps<CN extends FC<any>, TN extends TagNames> = {
component?: CN,
tag?: TN | CN | string,
} & {
name: string,
block?: string,
mod?: CNMod,
mix?: CNMix | CNMix[],
className?: string,
style?: CSSProperties,
component?: FC | CNTagName,
} & ({
[key in keyof TagAttrs<TN>]: TagAttrs<TN>[key]
} & {
[key in keyof Parameters<CN>[0]]: Parameters<CN>[0][key]
})
const CSS_PREFIX = process.env.CSS_PREFIX ?? 'dm-';
const assembleClass = (block: string, elem?: string, mix?: CNMix | CNMix[], mod?: CNMod) => {
const rootName = block;
const elemName = elem ? `${rootName}__${elem}` : null;
const stateName = Object.entries(mod ?? {}).reduce((res, [key, value]) => {
const stateClass = [elemName ?? rootName];
if (value === null || value === undefined) return res;
if (value !== false) {
stateClass.push(key);
if (value !== true) stateClass.push(value as string);
res.push(stateClass.join('_'));
}
return res;
}, [] as string[]);
const finalClass: string[] = [];
finalClass.push(elemName ?? rootName);
finalClass.push(...stateName);
if (mix) {
const mixes = Array.isArray(mix) ? mix : [mix];
const mixMap = ([] as CNMix[])
.concat(...mixes)
.filter(m => {
if (typeof m === 'string') {
return m.trim() !== '';
} else {
return m !== undefined && m !== null;
}
})
.map(m => {
if (typeof m === 'string') {
return m;
} else {
return m?.toClassName?.();
}
})
.reduce((res, cls) => [...res, ...cls!.split(/\s+/)], [] as string[]);
finalClass.push(...Array.from(new Set(mixMap)));
}
const attachNamespace = (cls: string) => {
if (typeof cls !== 'string') console.error('Non-string classname: ', cls);
return String(cls).startsWith(CSS_PREFIX) ? cls : `${CSS_PREFIX}${cls}`;
};
return finalClass.map(attachNamespace).join(" ");
};
const BlockContext = createContext<CN | null>(null);
export const cn = (block: string, options: CNOptions = {}): CN => {
const { elem, mix, mod } = options ?? {};
const blockName = block;
const classNameBuilder: CN = {
block(name) {
return cn(name, { elem, mix, mod });
},
elem(name) {
return cn(block, { elem: name, mix, mod });
},
mod(newMod = {}) {
const stateOverride = Object.assign({}, mod ?? {}, newMod);
return cn(block ?? blockName, { elem, mix, mod: stateOverride });
},
mix(...mix) {
return cn(block, { elem, mix, mod });
},
select(root = document) {
return root.querySelector(this.toCSSSelector());
},
selectAll(root = document) {
return root.querySelectorAll(this.toCSSSelector());
},
closest(root) {
return root.closest(this.toCSSSelector());
},
toString() {
return assembleClass(
block,
elem,
mix,
mod,
);
},
toClassName() {
return this.toString();
},
toCSSSelector() {
return `.${this.toClassName().replace(/(\s+)/g, '.')}`;
},
};
Object.defineProperty(classNameBuilder, 'Block', { value: Block });
Object.defineProperty(classNameBuilder, 'Elem', { value: Elem });
Object.defineProperty(classNameBuilder, '__class', { value: {
block,
elem,
mix,
mod,
} });
return classNameBuilder;
};
export const BemWithSpecifiContext = (context?: Context<CN | null>) => {
const Context = context ?? createContext<CN|null>(null);
const Block = forwardRef(<T extends FC<any>, D extends TagNames>({
tag = 'div',
name,
mod,
mix,
...rest
}: WrappedComponentProps<T, D>, ref: any) => {
const rootClass = cn(name);
const finalMix = ([] as [ CNMix? ]).concat(mix).filter(cn => !!cn);
const className = rootClass.mod(mod).mix(...(finalMix as CNMix[]), rest.className).toClassName();
const finalProps = (tag.toString() === 'Symbol(react.fragment)') ? { ...rest, ref } : { ...rest, ref, className } as any;
return createElement(Context.Provider, {
value: rootClass,
}, createElement(tag, finalProps));
});
const Elem = forwardRef(<T extends FC<any>, D extends TagNames>({
tag = "div",
component,
block,
name,
mod,
mix,
...rest
}: WrappedComponentProps<T, D>, ref: any) => {
const blockCtx = useContext(Context);
const finalMix = ([] as [ CNMix? ]).concat(mix).filter(cn => !!cn);
const className = (block ? cn(block) : blockCtx)!
.elem(name)
.mod(mod)
.mix(...(finalMix as CNMix[]), rest.className)
.toClassName();
const finalProps: any = { ...rest, ref, className };
if (typeof tag !== 'string') finalProps.block = blockCtx;
if (component) finalProps.tag = tag;
return createElement(component ?? tag, finalProps);
});
Block.displayName = 'Block';
Elem.displayName = 'Elem';
return { Block, Elem, Context };
};
export const { Block, Elem } = BemWithSpecifiContext(BlockContext);