import { type ComponentRef, forwardRef, type ComponentPropsWithoutRef, type MouseEventHandler, } from "react"; import { Primitive } from "./Primitive"; import { composeEventHandlers } from "@radix-ui/primitive"; type ActionButtonCallback = ( props: TProps, ) => MouseEventHandler | null; type PrimitiveButtonProps = ComponentPropsWithoutRef; export type ActionButtonProps = PrimitiveButtonProps & (THook extends (props: infer TProps) => unknown ? TProps : never); export type ActionButtonElement = ComponentRef; export const createActionButton = ( displayName: string, useActionButton: ActionButtonCallback, forwardProps: (keyof NonNullable)[] = [], ) => { const ActionButton = forwardRef< ActionButtonElement, PrimitiveButtonProps & TProps >((props, forwardedRef) => { const forwardedProps = {} as TProps; const primitiveProps = {} as PrimitiveButtonProps; (Object.keys(props) as Array).forEach((key) => { if (forwardProps.includes(key as keyof TProps)) { (forwardedProps as any)[key] = props[key]; } else { (primitiveProps as any)[key] = props[key]; } }); const callback = useActionButton(forwardedProps as TProps) ?? undefined; return ( ); }); ActionButton.displayName = displayName; return ActionButton; };