forked from Creditra/Creditra-Frontend
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathclassnames.ts
More file actions
42 lines (39 loc) · 977 Bytes
/
Copy pathclassnames.ts
File metadata and controls
42 lines (39 loc) · 977 Bytes
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
/**
* A minimal `classnames`-style helper.
*
* Accepts strings, arrays, and objects whose keys are class names mapped
* to a truthy/falsy flag. Falsy values are skipped, the result is a
* single space-separated string.
*
* @example
* cx('btn', isActive && 'btn--active', { 'btn--lg': size === 'lg' })
*/
export type ClassValue =
| string
| number
| null
| undefined
| false
| Record<string, unknown>
| ClassValue[];
export function cx(...values: ClassValue[]): string {
const out: string[] = [];
const push = (value: ClassValue) => {
if (!value) return;
if (typeof value === 'string' || typeof value === 'number') {
out.push(String(value));
return;
}
if (Array.isArray(value)) {
value.forEach(push);
return;
}
if (typeof value === 'object') {
for (const key of Object.keys(value)) {
if (value[key]) out.push(key);
}
}
};
values.forEach(push);
return out.join(' ');
}