index.jsx 9.7 KB
Newer Older
A
afc163 已提交
1 2
'use strict';

A
afc163 已提交
3
import React from 'react';
A
afc163 已提交
4
import jQuery from 'jquery';
A
afc163 已提交
5
import Table from 'rc-table';
A
afc163 已提交
6
import Dropdown from '../dropdown';
A
afc163 已提交
7
import Checkbox from '../checkbox';
A
afc163 已提交
8
import FilterMenu from './filterMenu';
9
import Pagination from '../pagination';
A
afc163 已提交
10
import objectAssign from 'object-assign';
A
afc163 已提交
11 12

let AntTable = React.createClass({
A
afc163 已提交
13
  getInitialState() {
14 15 16 17 18 19 20
    // 支持两种模式
    if (Array.isArray(this.props.dataSource)) {
      this.mode = 'local';
      // 保留原来的数据
      this.originDataSource = this.props.dataSource.slice(0);
    } else {
      this.mode = 'remote';
A
afc163 已提交
21 22
      this.props.dataSource = objectAssign({
        resolve: function(data) {
23
          return data || [];
A
afc163 已提交
24 25 26 27
        },
        getParams: function() {},
        getPagination: function() {}
      }, this.props.dataSource);
28 29 30 31 32
    }
    var pagination;
    if (this.props.pagination === false) {
      pagination = false;
    } else {
A
afc163 已提交
33 34 35 36
      pagination = objectAssign({
        pageSize: 10,
        total: this.props.dataSource.length
      }, this.props.pagination);
37
    }
A
afc163 已提交
38
    return {
A
afc163 已提交
39 40
      selectedRowKeys: [],
      loading: false,
41
      pagination: pagination,
A
afc163 已提交
42
      data: []
A
afc163 已提交
43 44
    };
  },
A
afc163 已提交
45 46
  getDefaultProps() {
    return {
A
afc163 已提交
47
      prefixCls: 'ant-table',
A
afc163 已提交
48
      useFixedHeader: false,
A
afc163 已提交
49 50
      rowSelection: null,
      size: 'normal'
A
afc163 已提交
51 52
    };
  },
A
afc163 已提交
53
  toggleSortOrder(order, column) {
54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71
    let sortColumn = this.state.sortColumn;
    let sortOrder = this.state.sortOrder;
    // 同时允许一列进行排序,否则会导致排序顺序的逻辑问题
    if (sortColumn) {
      sortColumn.className = '';
    }
    if (sortColumn !== column) {  // 当前列未排序
      sortOrder = order;
      sortColumn = column;
      sortColumn.className = 'ant-table-column-sort';
    } else {                      // 当前列已排序
      if (sortOrder === order) {  // 切换为未排序状态
        sortOrder = '';
        sortColumn = null;
      } else {                    // 切换为排序状态
        sortOrder = order;
        sortColumn.className = 'ant-table-column-sort';
      }
A
afc163 已提交
72
    }
73 74 75
    if (this.mode === 'local') {
      let sorter = function() {
        let result = column.sorter.apply(this, arguments);
76
        if (sortOrder === 'ascend') {
77
          return result;
78
        } else if (sortOrder === 'descend') {
79 80 81
          return -result;
        }
      };
82
      if (sortOrder) {
83 84 85 86
        this.props.dataSource = this.props.dataSource.sort(sorter);
      } else {
        this.props.dataSource = this.originDataSource.slice();
      }
A
afc163 已提交
87
    }
A
afc163 已提交
88 89 90 91
    this.setState({
      sortOrder: sortOrder,
      sortColumn: sortColumn
    }, this.fetch);
A
afc163 已提交
92
  },
A
afc163 已提交
93
  handleFilter(column) {
94 95 96 97 98 99 100 101
    if (this.mode === 'local') {
      this.props.dataSource = this.originDataSource.slice().filter(function(record) {
        if (column.selectedFilters.length === 0) {
          return true;
        }
        return column.selectedFilters.some(function(value) {
          return column.onFilter.call(this, value, record);
        });
102
      });
103
    }
104
    this.fetch();
A
afc163 已提交
105
  },
A
afc163 已提交
106
  handleSelect(rowIndex, checked) {
A
afc163 已提交
107
    let selectedRow = this.state.data[rowIndex - 1];
108
    if (checked) {
A
afc163 已提交
109
      this.state.selectedRowKeys.push(rowIndex);
110
    } else {
A
afc163 已提交
111
      this.state.selectedRowKeys = this.state.selectedRowKeys.filter(function(i) {
A
afc163 已提交
112
        return rowIndex !== i;
113 114 115 116 117 118 119 120 121
      });
    }
    this.setState({
      selectedRowKeys: this.state.selectedRowKeys
    });
    if (this.props.rowSelection.onSelect) {
      this.props.rowSelection.onSelect(selectedRow, checked);
    }
  },
A
afc163 已提交
122
  handleSelectAllRow(checked) {
123 124 125 126 127 128 129
    this.setState({
      selectedRowKeys: checked ? this.state.data.map(function(item, i) {
        return i + 1;
      }) : []
    });
    if (this.props.rowSelection.onSelectAll) {
      this.props.rowSelection.onSelectAll(checked);
A
afc163 已提交
130
    }
A
afc163 已提交
131
  },
132
  handlePageChange: function(current) {
A
afc163 已提交
133 134 135 136 137
    let pagination = this.state.pagination;
    pagination.current = current || 1;
    this.setState({
      pagination: pagination
    }, this.fetch);
138 139
  },
  renderSelectionCheckBox(value, record, index) {
A
afc163 已提交
140 141
    let rowIndex = index + 1; // 从 1 开始
    let checked = this.state.selectedRowKeys.indexOf(rowIndex) >= 0;
A
afc163 已提交
142
    return <Checkbox checked={checked} onChange={this.handleSelect.bind(this, rowIndex)} />;
143 144 145 146 147 148 149
  },
  renderRowSelection() {
    var columns = this.props.columns;
    if (this.props.rowSelection) {
      let checked = this.state.data.every(function(item, i) {
        return this.state.selectedRowKeys.indexOf(i + 1) >= 0;
      }, this);
A
afc163 已提交
150
      let checkboxAll = <Checkbox checked={checked} onChange={this.handleSelectAllRow} />;
151 152 153 154
      let selectionColumn = {
        key: 'selection-column',
        title: checkboxAll,
        width: 60,
A
afc163 已提交
155 156
        render: this.renderSelectionCheckBox,
        className: 'ant-table-selection-column'
157 158 159 160 161 162 163
      };
      if (columns[0] &&
          columns[0].key === 'selection-column') {
        columns[0] = selectionColumn;
      } else {
        columns.unshift(selectionColumn);
      }
A
afc163 已提交
164 165 166 167 168
      // 加上选中行的样式
      this.props.rowClassName = (record, i) => {
        return this.state.selectedRowKeys.indexOf(i + 1) >= 0 ?
          'ant-table-row-selected' : '';
      };
169 170 171
    }
    return columns;
  },
A
afc163 已提交
172
  renderColumnsDropdown() {
173
    return this.props.columns.map((column) => {
A
afc163 已提交
174 175 176 177
      if (!column.originTitle) {
        column.originTitle = column.title;
      }
      let filterDropdown, menus, sortButton;
178
      if (column.filters && column.filters.length > 0) {
179
        column.selectedFilters = column.selectedFilters || [];
A
afc163 已提交
180
        menus = <FilterMenu column={column} confirmFilter={this.handleFilter.bind(this, column)} />;
A
afc163 已提交
181
        let dropdownSelectedClass = '';
182
        if (column.selectedFilters && column.selectedFilters.length > 0) {
A
afc163 已提交
183 184 185 186 187 188
          dropdownSelectedClass = 'ant-table-filter-selected';
        }
        filterDropdown = <Dropdown trigger="click"
          closeOnSelect={false}
          overlay={menus}>
          <i title="筛选" className={'anticon anticon-bars ' + dropdownSelectedClass}></i>
A
afc163 已提交
189 190 191
        </Dropdown>;
      }
      if (column.sorter) {
192
        let isSortColumn = (this.state.sortColumn === column);
A
afc163 已提交
193 194
        sortButton = <div className="ant-table-column-sorter">
          <span className={'ant-table-column-sorter-up ' +
195
                           ((isSortColumn && this.state.sortOrder === 'ascend') ? 'on' : 'off')}
A
afc163 已提交
196 197 198 199 200
            title="升序排序"
            onClick={this.toggleSortOrder.bind(this, 'ascend', column)}>
            <i className="anticon anticon-caret-up"></i>
          </span>
          <span className={'ant-table-column-sorter-down ' +
201
                           ((isSortColumn && this.state.sortOrder === 'descend') ? 'on' : 'off')}
A
afc163 已提交
202 203 204 205 206 207 208 209 210 211 212
            title="降序排序"
            onClick={this.toggleSortOrder.bind(this, 'descend', column)}>
            <i className="anticon anticon-caret-down"></i>
          </span>
        </div>;
      }
      column.title = [
        column.originTitle,
        sortButton,
        filterDropdown
      ];
A
afc163 已提交
213
      return column;
A
afc163 已提交
214 215
    });
  },
216 217 218 219
  renderPagination() {
    // 强制不需要分页
    if (this.state.pagination === false) {
      return '';
A
afc163 已提交
220
    }
A
afc163 已提交
221 222 223 224 225
    let classString = 'ant-table-pagination';
    if (this.props.size === 'small') {
      classString += ' mini';
    }
    return <Pagination className={classString}
226 227
      onChange={this.handlePageChange}
      {...this.state.pagination} />;
A
afc163 已提交
228
  },
229 230 231 232
  prepareParamsArguments() {
    // 准备筛选、排序、分页的参数
    let pagination;
    let filters = {};
A
afc163 已提交
233
    let sorter = {};
234 235 236 237 238 239 240
    pagination = this.state.pagination;
    this.props.columns.forEach(function(column) {
      if (column.dataIndex && column.selectedFilters &&
          column.selectedFilters.length > 0) {
        filters[column.dataIndex] = column.selectedFilters;
      }
    });
A
afc163 已提交
241 242 243 244 245 246
    if (this.state.sortColumn && this.state.sortOrder &&
        this.state.sortColumn.dataIndex) {
      sorter.field = this.state.sortColumn.dataIndex;
      sorter.order = this.state.sortOrder;
    }
    return [pagination, filters, sorter];
247
  },
248 249 250
  fetch: function() {
    let dataSource = this.props.dataSource;
    if (this.mode === 'remote') {
A
afc163 已提交
251 252 253 254
      this.setState({
        loading: true
      });
      jQuery.ajax({
255
        url: dataSource.url,
A
afc163 已提交
256 257 258
        data: dataSource.getParams.apply(this, this.prepareParamsArguments()) || {},
        headers: dataSource.headers,
        dataType: 'json',
A
afc163 已提交
259 260
        success: (result) => {
          if (this.isMounted()) {
A
afc163 已提交
261
            let pagination = objectAssign(
A
afc163 已提交
262 263 264
              this.state.pagination,
              dataSource.getPagination.call(this, result)
            );
A
afc163 已提交
265
            this.setState({
266
              data: dataSource.resolve.call(this, result),
A
afc163 已提交
267 268
              pagination: pagination,
              loading: false
A
afc163 已提交
269 270 271
            });
          }
        },
A
afc163 已提交
272
        error: () => {
A
afc163 已提交
273 274 275 276 277
          this.setState({
            loading: false
          });
        }
      });
278
    } else {
A
afc163 已提交
279 280 281 282 283 284 285 286
      let pageSize = this.state.pagination.pageSize;
      let current = this.state.pagination.current;
      this.setState({
        data: this.props.dataSource.filter(function(item, i) {
          if (i >= (current - 1) * pageSize &&
              i < current * pageSize) {
            return item;
          }
A
afc163 已提交
287
        })
A
afc163 已提交
288
      });
A
afc163 已提交
289 290 291
    }
  },
  componentDidMount() {
A
afc163 已提交
292
    this.handlePageChange();
A
afc163 已提交
293
  },
A
afc163 已提交
294
  render() {
295 296
    this.props.columns = this.renderRowSelection();

A
afc163 已提交
297
    var classString = '';
A
afc163 已提交
298
    if (this.state.loading) {
A
afc163 已提交
299 300 301 302 303
      classString += ' ant-table-loading';
    }
    if (this.props.size === 'small') {
      classString += ' ant-table-small';
    }
304 305 306 307

    return <div className="clearfix">
      <Table data={this.state.data}
      columns={this.renderColumnsDropdown()}
A
afc163 已提交
308
      className={classString}
309 310 311
      {...this.props} />
      {this.renderPagination()}
    </div>;
A
afc163 已提交
312 313 314 315
  }
});

export default AntTable;