Skip to content

Commit 7b5aada

Browse files
author
nafees nazik
committed
feat: add styled function
1 parent 4fe75ef commit 7b5aada

File tree

2 files changed

+53
-3
lines changed

2 files changed

+53
-3
lines changed

src/index.ts

Lines changed: 52 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1 +1,52 @@
1-
export const foo = 'foo'
1+
import * as React from "react"
2+
import { cva, cx } from "class-variance-authority"
3+
import type {
4+
VariantProps,
5+
ClassValue,
6+
ClassProp,
7+
VariantsSchema,
8+
VariantsConfig,
9+
} from "class-variance-authority"
10+
11+
export type IntrinsicElementsKeys = keyof JSX.IntrinsicElements
12+
13+
export function styled<T extends IntrinsicElementsKeys>(
14+
Tag: T,
15+
forwardRef?: boolean,
16+
) {
17+
return function wrapper<Variants extends VariantsSchema>(
18+
base?: ClassValue,
19+
config?:
20+
| (Variants extends VariantsSchema
21+
? {
22+
variants?: Variants | undefined
23+
defaultVariants?: VariantsConfig<Variants> | undefined
24+
compoundVariants?:
25+
| (Variants extends VariantsSchema
26+
? VariantsConfig<Variants> & ClassProp
27+
: ClassProp)[]
28+
| undefined
29+
}
30+
: never)
31+
| undefined,
32+
) {
33+
const classes = cva(base, config)
34+
35+
function StyledWrapper(
36+
props: JSX.IntrinsicElements[typeof Tag] &
37+
Omit<VariantProps<typeof classes>, "class">,
38+
ref: any,
39+
) {
40+
// Grab a shallow copy of the props
41+
let _props = Object.assign({}, props)
42+
props.className = cx(classes(), props.className)
43+
_props.ref = ref
44+
45+
let _as = Tag
46+
47+
return React.createElement(_as, _props)
48+
}
49+
50+
return forwardRef ? React.forwardRef(StyledWrapper) : StyledWrapper
51+
}
52+
}

test/index.test.ts

Lines changed: 1 addition & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,5 @@
11
import { test, assert } from "vitest"
2-
import { foo } from "../src"
32

43
test("simple", () => {
5-
assert.equal(foo, "foo")
4+
assert.equal("foo", "foo")
65
})

0 commit comments

Comments
 (0)