All files / src/table/addons removeable.tsx

72.22% Statements 13/18
72.73% Branches 8/11
50% Functions 4/8
76.47% Lines 13/17

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 87 88 89 90 91 92 93                                                              3x   3x             1x   1x   1x                 1x   2x               3x 2x     1x               1x     1x                   1x        
import React from "react";
import { TableAddon, TableProps, RowRenderContext } from "../TableProps";
import { Icon } from "../../icon";
import { Button } from "../../button";
 
/**
 * `removeable` 插件用于支持表格可删除行的样式及操作。
 */
export interface RemoveableOptions<Record = any> {
  /**
   * 删除操作回调
   */
  onRemove?: (
    rowKey: string,
    context: { event: React.SyntheticEvent; record: Record }
  ) => void;
 
  /**
   * 列宽度,可以指定 CSS 属性或数字 (单位:px)
   * @default 46
   */
  width?: string | number;
 
  /**
   * 参考 Icon 组件[图标类型](/component/icon)
   *
   * @default "dismiss"
   */
  icon?: string;
}
 
const fallbackColumnKey = "__removeable_addon__";
 
let rowDisabled: TableProps["rowDisabled"] = null;
 
export function removeable({
  onRemove = () => null,
  width = 46,
  icon = "dismiss",
}: RemoveableOptions): TableAddon {
  return {
    onInjectProps: props => {
      rowDisabled = props.rowDisabled || (() => false);
 
      const columns = [
        ...props.columns,
        {
          key: fallbackColumnKey,
          header: "",
          width,
          render: () => null,
        },
      ];
      return { ...props, columns };
    },
    onInjectColumn: previous => (
      record,
      rowKey,
      recordIndex,
      column,
      columnIndex
    ) => {
      // 不是目标列
      if (column.key !== fallbackColumnKey) {
        return previous(record, rowKey, recordIndex, column, columnIndex);
      }
 
      const { children: preChildren, props, ...result } = previous(
        record,
        rowKey,
        recordIndex,
        column,
        columnIndex
      );
 
      let children = preChildren;
 
      // 非表头
      Iif (recordIndex !== -1 && !rowDisabled(record)) {
        children = (
          <Button
            type="icon"
            icon={icon}
            htmlType="button"
            onClick={event => onRemove(rowKey, { event, record })}
          />
        );
      }
      return { ...result, props, children };
    },
  };
}