react-tvcx
Version:
A library providing functions to help users create a reusable component system for their projects using React, Tailwind CSS, and TypeScript.
80 lines (79 loc) • 3 kB
JavaScript
// src/index.tsx
import clsx from "clsx";
import React from "react";
import { twMerge } from "tailwind-merge";
import { tv } from "tailwind-variants";
function cn(...inputs) {
return twMerge(clsx(inputs));
}
function forwardRef(render) {
return React.forwardRef(render);
}
var tvcx = (config) => {
return tv(config);
};
function createComponentFactory(tvFn) {
const Ctx = React.createContext({});
const useCtx = () => React.useContext(Ctx);
function withRoot(Component, slot, config) {
const Comp = React.forwardRef(function({ className, classNames, unstyled, ...props }, ref) {
const mergedProps = { ...config == null ? void 0 : config.defaultProps, ...props };
const variants = tvFn(mergedProps);
const _className = React.useMemo(
function() {
var _a;
return cn(
unstyled ? "" : typeof variants === "string" ? variants : (_a = variants == null ? void 0 : variants[slot != null ? slot : ""]) == null ? void 0 : _a.call(variants),
classNames == null ? void 0 : classNames[slot],
className
);
},
[variants, classNames, className, slot, unstyled]
);
return /* @__PURE__ */ React.createElement(Ctx.Provider, { value: { variants, classNames } }, /* @__PURE__ */ React.createElement(Component, { ref, className: _className, ...mergedProps }));
});
Comp.displayName = (config == null ? void 0 : config.displayName) || Component.displayName || Component.name;
return Comp;
}
function withSlot(Component, slot, config) {
const Comp = React.forwardRef(function({ className, unstyled, ...props }, ref) {
const { variants, classNames } = useCtx();
const mergedProps = { ...config == null ? void 0 : config.defaultProps, ...props };
const _className = React.useMemo(
function() {
var _a;
return cn(
slot && !unstyled ? (_a = variants == null ? void 0 : variants[slot]) == null ? void 0 : _a.call(variants) : void 0,
slot ? classNames == null ? void 0 : classNames[slot] : void 0,
className
);
},
[variants, classNames, className, slot, unstyled]
);
return /* @__PURE__ */ React.createElement(Component, { ref, className: _className, ...mergedProps });
});
Comp.displayName = (config == null ? void 0 : config.displayName) || Component.displayName || Component.name || "Component";
return Comp;
}
return {
withRoot,
withSlot
};
}
function styled(Component, tvFn) {
return forwardRef(function({ as: Comp = Component, children, className, ...props }, ref) {
return /* @__PURE__ */ React.createElement(Comp, { ref, className: cn(tvFn({ ...props, className })), ...props }, children);
});
}
function createComponentTree(Factory, nestedChildren) {
const c = Factory;
return Object.assign(c, nestedChildren);
}
export {
cn,
createComponentFactory,
createComponentTree,
forwardRef,
styled,
tvcx
};