All files / src/form Form.tsx

100% Statements 11/11
100% Branches 6/6
100% Functions 1/1
100% Lines 11/11

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 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86                                                                                                    15x   15x                       15x                 19x 19x 19x         19x 19x 19x 19x 19x  
import React from "react";
import classNames from "classnames";
import { StyledProps } from "../_type";
import { FormItem } from "./FormItem";
import { FormControl } from "./FormControl";
import { createRocket } from "../_util/create-rocket";
import { FormContext } from "./FormContext";
import { useConfig } from "../_util/config-context";
 
export interface FormProps extends StyledProps {
  /**
   * 表单布局方式
   *
   * - `default` 默认布局
   * - `fixed` 固定标签栏宽度,可用于对齐多个表单
   * - `vertical` 标签和控件垂直排列
   * - `inline` 表单内容行内流水排列
   * - `inline-vertical` 表单内容行内流水排列,且标签和控件垂直排列
   * @default "default"
   */
  layout?: "default" | "fixed" | "vertical" | "inline" | "inline-vertical";
 
  /**
   * 是否为纯展示表单(样式更加紧凑)
   *
   * @default false
   */
  readonly?: boolean;
 
  /**
   * 不展示表单 Label 部分
   *
   * @default false
   */
  hideLabel?: boolean;
 
  /**
   * 表单内容
   */
  children?: React.ReactNode;
}
 
export function Form({
  style,
  className,
  children,
  layout,
  readonly,
  hideLabel,
}: FormProps) {
  const { classPrefix } = useConfig();
  // readonly 只和 fixed 共存
  const formClassName = classNames(
    `${classPrefix}-form`,
    {
      [`${classPrefix}-form--fixed-layout`]: layout === "fixed",
      [`${classPrefix}-form--vertical`]:
        !readonly && (layout === "vertical" || layout === "inline-vertical"),
      [`${classPrefix}-form--inline`]:
        !readonly && (layout === "inline" || layout === "inline-vertical"),
      [`${classPrefix}-form--readonly`]: readonly,
    },
    className
  );
  return (
    <div className={formClassName} style={style}>
      <FormContext.Provider value={{ hideLabel }}>
        {children}
      </FormContext.Provider>
    </div>
  );
}
 
export const FormText = createRocket("Form.Text", "div.@{prefix}-form__text");
export const FormTitle = createRocket("Form.Title", "h3.@{prefix}-form-title");
export const FormAction = createRocket(
  "Form.Action",
  "div.@{prefix}-form-operate"
);
 
Form.Item = FormItem;
Form.Title = FormTitle;
Form.Action = FormAction;
Form.Control = FormControl;
Form.Text = FormText;