react-twc
Version:
Create reusable Tailwind CSS components with React.
76 lines (75 loc) • 2.63 kB
JavaScript
// src/index.tsx
import * as React from "react";
import { clsx } from "clsx";
import { Slot } from "@radix-ui/react-slot";
import { jsx } from "react/jsx-runtime";
function filterProps(props, shouldForwardProp) {
const filteredProps = {};
const keys = Object.keys(props);
for (let i = 0; i < keys.length; i++) {
const prop = keys[i];
if (shouldForwardProp(prop)) {
filteredProps[prop] = props[prop];
}
}
return filteredProps;
}
var createTwc = (config = {}) => {
const compose = config.compose || clsx;
const defaultShouldForwardProp = config.shouldForwardProp || ((prop) => prop[0] !== "$");
const wrap = (Component) => {
const createTemplate = (attrs, shouldForwardProp = defaultShouldForwardProp) => {
const template = (stringsOrFn, ...values) => {
const isClassFn = typeof stringsOrFn === "function";
const tplClassName = !isClassFn && String.raw({ raw: stringsOrFn }, ...values);
return React.forwardRef((p, ref) => {
const { className: classNameProp, asChild, ...rest } = p;
const rp = typeof attrs === "function" ? attrs(p) : attrs ? attrs : {};
const fp = filterProps({ ...rp, ...rest }, shouldForwardProp);
const forwardAsChild = config.forwardAsChild && typeof Component !== "string";
const Comp = !forwardAsChild && asChild ? Slot : Component;
const resClassName = isClassFn ? stringsOrFn(p) : tplClassName;
return /* @__PURE__ */ jsx(
Comp,
{
ref,
className: typeof resClassName === "function" ? (renderProps) => compose(
resClassName(renderProps),
typeof classNameProp === "function" ? classNameProp(renderProps) : classNameProp
) : compose(resClassName, classNameProp),
...forwardAsChild ? { asChild } : {},
...fp
}
);
});
};
template.transientProps = (fnOrArray) => {
const shouldForwardProp2 = typeof fnOrArray === "function" ? (prop) => !fnOrArray(prop) : (prop) => !fnOrArray.includes(prop);
return createTemplate(attrs, shouldForwardProp2);
};
if (attrs === void 0) {
template.attrs = (attrs2) => {
return createTemplate(attrs2, shouldForwardProp);
};
}
return template;
};
return createTemplate();
};
return new Proxy(
(component) => {
return wrap(component);
},
{
get(_, name) {
return wrap(name);
}
}
);
};
var twc = createTwc();
export {
createTwc,
clsx as cx,
twc
};