@ffsm/html-factory
Version:
A lightweight utility for creating React HTML factory components with TypeScript support, ref forwarding, and className merging.
60 lines (59 loc) • 2.69 kB
JavaScript
var __assign = (this && this.__assign) || function () {
__assign = Object.assign || function(t) {
for (var s, i = 1, n = arguments.length; i < n; i++) {
s = arguments[i];
for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p))
t[p] = s[p];
}
return t;
};
return __assign.apply(this, arguments);
};
var __rest = (this && this.__rest) || function (s, e) {
var t = {};
for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p) && e.indexOf(p) < 0)
t[p] = s[p];
if (s != null && typeof Object.getOwnPropertySymbols === "function")
for (var i = 0, p = Object.getOwnPropertySymbols(s); i < p.length; i++) {
if (e.indexOf(p[i]) < 0 && Object.prototype.propertyIsEnumerable.call(s, p[i]))
t[p[i]] = s[p[i]];
}
return t;
};
import { jsx as _jsx } from "react/jsx-runtime";
import { forwardRef, } from 'react';
import { clsx } from './clsx';
/**
* Processes and merges HTML props with special handling for className
* @template El The HTML element type
* @param {HTMLElementProps<El>} overideProps - Props to override initial props with
* @param {Ref<El>} [ref] - Optional ref to forward
* @param {HTMLElementProps<El>} [initialProps] - Optional initial props
* @returns {HTMLElementProps<El>} Merged props with className handling
*/
export function propsHTML(overideProps, ref, initialProps) {
var restClass = overideProps.className, rest = __rest(overideProps, ["className"]);
return __assign(__assign(__assign({}, initialProps), rest), { ref: ref, className: clsx(initialProps === null || initialProps === void 0 ? void 0 : initialProps.className, restClass) });
}
/**
* Creates a factory component for the specified HTML tag
* @template El The HTML element type that extends keyof JSX.IntrinsicElements
* @param {El} tag - The HTML tag to create a factory for
* @param {string} displayName - The display name for the component
* @param {HTMlFactoryProps<El>} [initialProps] - Optional initial props for the component
* @returns {ForwardRefExoticComponent<PropsWithoutRef<HTMlFactoryProps<El>> & RefAttributes<El>>} A React component
*
* @example
* // Create a custom paragraph component
* const P = factory('p', 'Paragraph', { className: 'text-base' });
*
* // Use in your component
* <P className="text-red-500">This will have both classes</P>
*/
export function factory(Tag, displayName, initialProps) {
var Component = forwardRef(function (props, ref) {
return _jsx(Tag, __assign({}, propsHTML(props, ref, initialProps)));
});
Component.displayName = displayName;
return Component;
}