All files / src/_util create-rocket.ts

100% Statements 16/16
100% Branches 4/4
100% Functions 5/5
100% Lines 15/15

Press n or j to go to the next uncovered block, b, p or k for the previous block.

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62                                    42x       311x       96x 96x       96x             311x 84x 84x 84x         84x 4x 4x               84x   311x 311x    
import React, { forwardRef, Ref, ReactNode } from "react";
import { StyledProps } from "../_type";
import { useConfig } from "./config-context";
 
export interface RocketProps extends StyledProps {
  /**
   * 组件内容
   */
  children?: ReactNode;
}
 
/**
 * 快速创建 DOM 容器组件
 * @param displayName 组件名称
 * @param paths 组件的容器路径,如 div.tea-card__body
 *
 * tea 类名前缀请使用 `@{prefix}` 代替
 */
export const createRocket = <P extends RocketProps = RocketProps>(
  displayName: string,
  ...paths: string[]
) => {
  const parentOf = (classPrefix: string) => (
    children: React.ReactNode,
    path: string
  ) => {
    const [tag, ...classNames] = path.split(".");
    return React.createElement(
      tag,
      {
        className: classNames
          .map(c => c.replace(/^(@{prefix}-)/, `${classPrefix}-`))
          .join(" "),
      },
      children
    );
  };
 
  const Rocket = forwardRef((props: P, ref: Ref<HTMLElement>) => {
    const { children, className, style } = props;
    const { classPrefix } = useConfig();
    let element = paths.reduceRight<JSX.Element>(
      parentOf(classPrefix),
      children as any
    );
 
    if (className || style) {
      const { props: elementProps } = element;
      element = React.cloneElement(element, {
        ref,
        className: [elementProps.className, className]
          .filter(Boolean)
          .join(" "),
        style,
      });
    }
    return element;
  });
  Rocket.displayName = displayName;
  return Rocket;
};