index.jsx 10.5 KB
Newer Older
A
afc163 已提交
1
import React from 'react';
A
afc163 已提交
2
import jQuery from 'jquery';
A
afc163 已提交
3
import Table from 'rc-table';
A
afc163 已提交
4
import Dropdown from '../dropdown';
A
afc163 已提交
5
import Checkbox from '../checkbox';
A
afc163 已提交
6
import FilterMenu from './filterMenu';
7
import Pagination from '../pagination';
A
afc163 已提交
8
import objectAssign from 'object-assign';
A
afc163 已提交
9

U
ustccjw 已提交
10
export default React.createClass({
A
afc163 已提交
11
  getInitialState() {
12 13 14 15 16 17 18
    // 支持两种模式
    if (Array.isArray(this.props.dataSource)) {
      this.mode = 'local';
      // 保留原来的数据
      this.originDataSource = this.props.dataSource.slice(0);
    } else {
      this.mode = 'remote';
A
afc163 已提交
19
      this.dataSource = objectAssign({
A
afc163 已提交
20
        resolve: function(data) {
21
          return data || [];
A
afc163 已提交
22 23 24 25
        },
        getParams: function() {},
        getPagination: function() {}
      }, this.props.dataSource);
26
    }
27 28 29 30 31 32 33

    let noPagination = (this.props.pagination === false);
    let pagination = objectAssign({
      pageSize: 10,
      total: this.props.dataSource.length
    }, this.props.pagination);

A
afc163 已提交
34
    return {
A
afc163 已提交
35 36
      selectedRowKeys: [],
      loading: false,
37
      pagination: pagination,
38
      noPagination: noPagination,
A
afc163 已提交
39
      data: []
A
afc163 已提交
40 41
    };
  },
A
afc163 已提交
42 43
  getDefaultProps() {
    return {
A
afc163 已提交
44
      prefixCls: 'ant-table',
A
afc163 已提交
45
      useFixedHeader: false,
A
afc163 已提交
46 47
      rowSelection: null,
      size: 'normal'
A
afc163 已提交
48 49
    };
  },
A
afc163 已提交
50
  toggleSortOrder(order, column) {
51 52
    let sortColumn = this.state.sortColumn;
    let sortOrder = this.state.sortOrder;
J
jljsj 已提交
53
    let sorter;
54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69
    // 同时允许一列进行排序,否则会导致排序顺序的逻辑问题
    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 已提交
70
    }
71
    if (this.mode === 'local') {
J
jljsj 已提交
72
      sorter = function() {
73
        let result = column.sorter.apply(this, arguments);
74
        if (sortOrder === 'ascend') {
75
          return result;
76
        } else if (sortOrder === 'descend') {
77 78 79
          return -result;
        }
      };
A
afc163 已提交
80
    }
A
afc163 已提交
81 82
    this.setState({
      sortOrder: sortOrder,
J
jljsj 已提交
83 84
      sortColumn: sortColumn,
      sorter: sorter
A
afc163 已提交
85
    }, this.fetch);
A
afc163 已提交
86
  },
A
afc163 已提交
87
  handleFilter(column) {
J
jljsj 已提交
88 89
    let columnIndex = this.props.columns.indexOf(column);
    let filterFns = [];
90
    if (this.mode === 'local') {
J
jljsj 已提交
91
      filterFns[columnIndex] = function(record) {
92 93 94 95 96 97
        if (column.selectedFilters.length === 0) {
          return true;
        }
        return column.selectedFilters.some(function(value) {
          return column.onFilter.call(this, value, record);
        });
J
jljsj 已提交
98
      };
99
    }
J
jljsj 已提交
100 101 102
    this.setState({
      filterFns: filterFns
    }, this.fetch);
A
afc163 已提交
103
  },
A
afc163 已提交
104 105
  handleSelect(rowIndex, e) {
    let checked = e.target.checked;
106
    if (checked) {
A
afc163 已提交
107
      this.state.selectedRowKeys.push(rowIndex);
108
    } else {
A
afc163 已提交
109
      this.state.selectedRowKeys = this.state.selectedRowKeys.filter(function(i) {
A
afc163 已提交
110
        return rowIndex !== i;
111 112 113 114 115 116
      });
    }
    this.setState({
      selectedRowKeys: this.state.selectedRowKeys
    });
    if (this.props.rowSelection.onSelect) {
A
afc163 已提交
117 118 119 120 121
      let currentRow = this.state.data[rowIndex - 1];
      let selectedRows = this.state.data.filter((row, i) => {
        return this.state.selectedRowKeys.indexOf(i + 1) >= 0;
      });
      this.props.rowSelection.onSelect(currentRow, checked, selectedRows);
122 123
    }
  },
A
afc163 已提交
124 125 126
  handleSelectAllRow(e) {
    let checked = e.target.checked;
    let selectedRowKeys = checked ? this.state.data.map(function(item, i) {
127
        return i + 1;
A
afc163 已提交
128 129 130
      }) : [];
    this.setState({
      selectedRowKeys: selectedRowKeys
131 132
    });
    if (this.props.rowSelection.onSelectAll) {
A
afc163 已提交
133 134 135 136
      let selectedRows = this.state.data.filter((row, i) => {
        return selectedRowKeys.indexOf(i + 1) >= 0;
      });
      this.props.rowSelection.onSelectAll(checked, selectedRows);
A
afc163 已提交
137
    }
A
afc163 已提交
138
  },
139
  handlePageChange(current) {
A
afc163 已提交
140
    let pagination = this.state.pagination || {};
141 142 143 144 145
    if (current) {
      pagination.current = current;
    } else {
      pagination.current = pagination.current || 1;
    }
A
afc163 已提交
146 147 148
    this.setState({
      pagination: pagination
    }, this.fetch);
149 150
  },
  renderSelectionCheckBox(value, record, index) {
A
afc163 已提交
151 152
    let rowIndex = index + 1; // 从 1 开始
    let checked = this.state.selectedRowKeys.indexOf(rowIndex) >= 0;
A
afc163 已提交
153
    return <Checkbox checked={checked} onChange={this.handleSelect.bind(this, rowIndex)} />;
154 155 156 157 158 159 160
  },
  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 已提交
161
      let checkboxAll = <Checkbox checked={checked} onChange={this.handleSelectAllRow} />;
162 163 164 165
      let selectionColumn = {
        key: 'selection-column',
        title: checkboxAll,
        width: 60,
A
afc163 已提交
166 167
        render: this.renderSelectionCheckBox,
        className: 'ant-table-selection-column'
168 169 170 171 172 173 174 175 176 177
      };
      if (columns[0] &&
          columns[0].key === 'selection-column') {
        columns[0] = selectionColumn;
      } else {
        columns.unshift(selectionColumn);
      }
    }
    return columns;
  },
A
afc163 已提交
178
  renderColumnsDropdown() {
179
    return this.props.columns.map((column) => {
A
afc163 已提交
180 181 182 183
      if (!column.originTitle) {
        column.originTitle = column.title;
      }
      let filterDropdown, menus, sortButton;
184
      if (column.filters && column.filters.length > 0) {
185
        column.selectedFilters = column.selectedFilters || [];
A
afc163 已提交
186
        menus = <FilterMenu column={column} confirmFilter={this.handleFilter.bind(this, column)} />;
A
afc163 已提交
187
        let dropdownSelectedClass = '';
188
        if (column.selectedFilters && column.selectedFilters.length > 0) {
A
afc163 已提交
189 190 191 192 193 194
          dropdownSelectedClass = 'ant-table-filter-selected';
        }
        filterDropdown = <Dropdown trigger="click"
          closeOnSelect={false}
          overlay={menus}>
          <i title="筛选" className={'anticon anticon-bars ' + dropdownSelectedClass}></i>
A
afc163 已提交
195 196 197
        </Dropdown>;
      }
      if (column.sorter) {
198
        let isSortColumn = (this.state.sortColumn === column);
A
afc163 已提交
199 200
        sortButton = <div className="ant-table-column-sorter">
          <span className={'ant-table-column-sorter-up ' +
201
                           ((isSortColumn && this.state.sortOrder === 'ascend') ? 'on' : 'off')}
A
afc163 已提交
202 203 204 205 206
            title="升序排序"
            onClick={this.toggleSortOrder.bind(this, 'ascend', column)}>
            <i className="anticon anticon-caret-up"></i>
          </span>
          <span className={'ant-table-column-sorter-down ' +
207
                           ((isSortColumn && this.state.sortOrder === 'descend') ? 'on' : 'off')}
A
afc163 已提交
208 209 210 211 212 213 214 215 216 217 218
            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 已提交
219
      return column;
A
afc163 已提交
220 221
    });
  },
222 223
  renderPagination() {
    // 强制不需要分页
224
    if (this.state.noPagination) {
225
      return '';
A
afc163 已提交
226
    }
A
afc163 已提交
227 228 229 230 231
    let classString = 'ant-table-pagination';
    if (this.props.size === 'small') {
      classString += ' mini';
    }
    return <Pagination className={classString}
232 233
      onChange={this.handlePageChange}
      {...this.state.pagination} />;
A
afc163 已提交
234
  },
235 236 237 238
  prepareParamsArguments() {
    // 准备筛选、排序、分页的参数
    let pagination;
    let filters = {};
A
afc163 已提交
239
    let sorter = {};
240 241 242 243 244 245 246
    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 已提交
247 248 249 250 251 252
    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];
253
  },
254
  fetch() {
255
    if (this.mode === 'remote') {
A
afc163 已提交
256 257
      // remote 模式使用 this.dataSource
      let dataSource = this.dataSource;
A
afc163 已提交
258 259 260 261
      this.setState({
        loading: true
      });
      jQuery.ajax({
262
        url: dataSource.url,
A
afc163 已提交
263 264 265
        data: dataSource.getParams.apply(this, this.prepareParamsArguments()) || {},
        headers: dataSource.headers,
        dataType: 'json',
A
afc163 已提交
266 267
        success: (result) => {
          if (this.isMounted()) {
A
afc163 已提交
268
            let pagination = objectAssign(
A
afc163 已提交
269 270 271
              this.state.pagination,
              dataSource.getPagination.call(this, result)
            );
A
afc163 已提交
272
            this.setState({
273
              data: dataSource.resolve.call(this, result),
A
afc163 已提交
274 275
              pagination: pagination,
              loading: false
A
afc163 已提交
276 277 278
            });
          }
        },
A
afc163 已提交
279
        error: () => {
A
afc163 已提交
280 281 282 283 284
          this.setState({
            loading: false
          });
        }
      });
285
    } else {
A
afc163 已提交
286
      let data = this.props.dataSource;
A
afc163 已提交
287 288
      let current, pageSize;
      // 如果没有分页的话,默认全部展示
289
      if (this.state.noPagination) {
290
        pageSize = Number.MAX_VALUE;
A
afc163 已提交
291 292 293 294 295
        current = 1;
      } else {
        pageSize = this.state.pagination.pageSize;
        current = this.state.pagination.current;
      }
J
jljsj 已提交
296 297 298 299 300 301 302 303 304 305 306
      // 排序
      if (this.state.sortOrder && this.state.sorter) {
        data = data.sort(this.state.sorter);
      } else {
        data = this.originDataSource.slice();
      }
      // 筛选
      if (this.state.filterFns) {
        this.state.filterFns.forEach(function(filterFn) {
          if (typeof filterFn === 'function') {
            data = data.filter(filterFn);
A
afc163 已提交
307
          }
J
jljsj 已提交
308 309 310 311 312 313 314 315 316 317 318 319
        });
      }
      // 分页
      data = data.filter(function(item, i) {
        if (i >= (current - 1) * pageSize &&
            i < current * pageSize) {
          return item;
        }
      });
      // 完成数据
      this.setState({
        data: data
A
afc163 已提交
320
      });
A
afc163 已提交
321 322 323
    }
  },
  componentDidMount() {
A
afc163 已提交
324
    this.handlePageChange();
A
afc163 已提交
325
  },
A
afc163 已提交
326
  render() {
327 328
    this.props.columns = this.renderRowSelection();

A
afc163 已提交
329
    var classString = '';
A
afc163 已提交
330
    if (this.state.loading) {
A
afc163 已提交
331 332 333 334 335
      classString += ' ant-table-loading';
    }
    if (this.props.size === 'small') {
      classString += ' ant-table-small';
    }
336 337 338 339

    return <div className="clearfix">
      <Table data={this.state.data}
      columns={this.renderColumnsDropdown()}
A
afc163 已提交
340
      className={classString}
341 342 343
      {...this.props} />
      {this.renderPagination()}
    </div>;
A
afc163 已提交
344 345
  }
});