Skip to content

Commit 027290d

Browse files
committed
Add fr.cx
1 parent 5720ce3 commit 027290d

File tree

2 files changed

+58
-1
lines changed

2 files changed

+58
-1
lines changed

src/lib/cx.ts

Lines changed: 54 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,54 @@
1+
import { assert } from "tsafe/assert";
2+
import { typeGuard } from "tsafe/typeGuard";
3+
import type { FrClassName } from "./generatedFromCss/classNames";
4+
5+
export type FrCxArg =
6+
| undefined
7+
| null
8+
| FrClassName
9+
| boolean
10+
| Partial<Record<FrClassName, boolean | null | undefined>>
11+
| readonly FrCxArg[];
12+
13+
/** Copy pasted from
14+
* https://github.com/emotion-js/emotion/blob/23f43ab9f24d44219b0b007a00f4ac681fe8712e/packages/react/src/class-names.js#L17-L63
15+
**/
16+
export const cx = (args: FrCxArg[]): string => {
17+
const len = args.length;
18+
let i = 0;
19+
let cls = "";
20+
for (; i < len; i++) {
21+
const arg = args[i];
22+
if (arg == null) continue;
23+
24+
let toAdd;
25+
switch (typeof arg) {
26+
case "boolean":
27+
break;
28+
case "object": {
29+
if (Array.isArray(arg)) {
30+
toAdd = cx(arg);
31+
} else {
32+
assert(!typeGuard<{ length: number }>(arg, false));
33+
34+
toAdd = "";
35+
for (const k in arg) {
36+
if (arg[k as FrClassName] && k) {
37+
toAdd && (toAdd += " ");
38+
toAdd += k;
39+
}
40+
}
41+
}
42+
break;
43+
}
44+
default: {
45+
toAdd = arg;
46+
}
47+
}
48+
if (toAdd) {
49+
cls && (cls += " ");
50+
cls += toAdd;
51+
}
52+
}
53+
return cls;
54+
};

src/lib/index.ts

Lines changed: 4 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -5,8 +5,11 @@ export type { BreakpointKeys } from "./breakpoints";
55
import { breakpoints } from "./breakpoints";
66
import { spacing } from "./spacing";
77
export type { SpacingToken } from "./spacing";
8+
import { cx } from "./cx";
9+
export type { FrCxArg } from "./cx";
810

911
export const fr = {
1012
breakpoints,
11-
spacing
13+
spacing,
14+
cx
1215
};

0 commit comments

Comments
 (0)