All files / src/table/addons injectable.ts

35.71% Statements 5/14
50% Branches 4/8
33.33% Functions 3/9
35.71% Lines 5/14

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                                                                                                  1x     1x 8x 8x         8x                                                  
import React from "react";
import { TableAddon } from "../TableProps";
 
/**
 * `injectable` 插件用于支持表格注入自定义 Props。
 *
 * 其中函数参数中将返回现有 `props`,用于需要属性合并的情况。
 */
export interface InjectableOptions<Record = any> {
  /**
   * 设置行 Props
   */
  row?: (
    props: React.HTMLAttributes<HTMLTableRowElement>,
    context: {
      record: Record;
      rowKey: string;
      recordIndex: number;
    }
  ) => React.HTMLAttributes<HTMLTableRowElement>;
 
  /**
   * 设置内容 Props
   */
  body?: (
    props: React.HTMLAttributes<HTMLDivElement>
  ) => React.HTMLAttributes<HTMLDivElement>;
 
  /**
   * 设置表头 Props
   */
  head?: (
    props: React.HTMLAttributes<HTMLDivElement>
  ) => React.HTMLAttributes<HTMLDivElement>;
 
  /**
   * 设置表格 Props
   */
  table?: (
    props: React.HTMLAttributes<HTMLDivElement>
  ) => React.HTMLAttributes<HTMLDivElement>;
}
 
export function injectable({
  row,
  body,
  head,
  table,
}: InjectableOptions): TableAddon {
  return {
    onInjectRow: !row
      ? undefined
      : render => (record, rowKey, recordIndex, ...args) => {
          const result = render(record, rowKey, recordIndex, ...args);
          const props = row(result.row.props, {
            record,
            rowKey,
            recordIndex,
          });
          return {
            ...result,
            row: React.cloneElement(result.row, props),
          };
        },
    onInjectBody: !body
      ? undefined
      : render => (...args) => {
          const element = render(...args);
          return React.cloneElement(element, body(element.props));
        },
    onInjectHead: !head
      ? undefined
      : render => (...args) => {
          const element = render(...args);
          return React.cloneElement(element, head(element.props));
        },
    onInjectTable: !table
      ? undefined
      : render => (...args) => {
          const element = render(...args);
          return React.cloneElement(element, table(element.props));
        },
  };
}