index.jsx 12.6 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';
Y
yiminghe 已提交
9
import equals from 'is-equal-shallow';
A
afc163 已提交
10

Y
yiminghe 已提交
11 12
function noop() {
}
13

Y
yiminghe 已提交
14 15 16
function defaultResolve(data) {
  return data || [];
}
17

Y
yiminghe 已提交
18 19
export default React.createClass({
  getInitialState() {
A
afc163 已提交
20
    return {
Y
yiminghe 已提交
21
      // 减少状态
A
afc163 已提交
22
      selectedRowKeys: [],
Y
yiminghe 已提交
23 24 25 26 27 28 29 30 31 32
      // only for remote
      data: [],
      filters: {},
      loading: !this.isLocalDataSource(),
      sortColumn: '',
      sortOrder: '',
      sorter: null,
      pagination: this.hasPagination() ? objectAssign({
        pageSize: 10
      }, this.props.pagination) : {}
A
afc163 已提交
33 34
    };
  },
Y
yiminghe 已提交
35

A
afc163 已提交
36 37
  getDefaultProps() {
    return {
A
afc163 已提交
38
      prefixCls: 'ant-table',
A
afc163 已提交
39
      useFixedHeader: false,
A
afc163 已提交
40 41
      rowSelection: null,
      size: 'normal'
A
afc163 已提交
42 43
    };
  },
Y
yiminghe 已提交
44

A
afc163 已提交
45
  componentWillReceiveProps(nextProps) {
Y
yiminghe 已提交
46
    if (('pagination' in nextProps) && nextProps.pagination !== false) {
A
afc163 已提交
47
      this.setState({
Y
yiminghe 已提交
48
        pagination: objectAssign({}, this.state.pagination, nextProps.pagination)
A
afc163 已提交
49 50
      });
    }
Y
yiminghe 已提交
51 52 53 54 55 56 57 58 59
    if (!this.isLocalDataSource()) {
      if (!equals(nextProps, this.props)) {
        this.setState({
          selectedRowKeys: [],
          loading: true
        }, this.fetch);
      }
    }
    if (nextProps.columns !== this.props.columns) {
A
afc163 已提交
60
      this.setState({
Y
yiminghe 已提交
61
        filters: {}
A
afc163 已提交
62 63 64
      });
    }
  },
A
afc163 已提交
65 66

  hasPagination(pagination) {
Y
yiminghe 已提交
67 68
    if (pagination === undefined) {
      pagination = this.props.pagination;
A
afc163 已提交
69
    }
Y
yiminghe 已提交
70 71
    return pagination !== false;
  },
A
afc163 已提交
72 73

  isLocalDataSource() {
Y
yiminghe 已提交
74
    return Array.isArray(this.props.dataSource);
A
afc163 已提交
75
  },
A
afc163 已提交
76 77

  getRemoteDataSource() {
A
afc163 已提交
78
    return objectAssign({
Y
yiminghe 已提交
79 80 81 82
      resolve: defaultResolve,
      getParams: noop,
      getPagination: noop
    }, this.props.dataSource);
A
afc163 已提交
83
  },
A
afc163 已提交
84

A
afc163 已提交
85
  toggleSortOrder(order, column) {
86 87
    let sortColumn = this.state.sortColumn;
    let sortOrder = this.state.sortOrder;
J
jljsj 已提交
88
    let sorter;
89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104
    // 同时允许一列进行排序,否则会导致排序顺序的逻辑问题
    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 已提交
105
    }
Y
yiminghe 已提交
106 107
    if (this.isLocalDataSource()) {
      sorter = function () {
108
        let result = column.sorter.apply(this, arguments);
109
        if (sortOrder === 'ascend') {
110
          return result;
111
        } else if (sortOrder === 'descend') {
112 113 114
          return -result;
        }
      };
A
afc163 已提交
115
    }
Y
yiminghe 已提交
116
    this.fetch({
A
afc163 已提交
117
      sortOrder: sortOrder,
J
jljsj 已提交
118 119
      sortColumn: sortColumn,
      sorter: sorter
Y
yiminghe 已提交
120
    });
A
afc163 已提交
121
  },
A
afc163 已提交
122

Y
yiminghe 已提交
123 124 125 126 127 128 129 130
  handleFilter(column, filters) {
    filters = objectAssign({}, this.state.filters, {
      [this.getColumnKey(column)]: filters
    });
    this.fetch({
      selectedRowKeys: [],
      filters: filters
    });
A
afc163 已提交
131
  },
A
afc163 已提交
132

Y
yiminghe 已提交
133
  handleSelect(record, rowIndex, e) {
A
afc163 已提交
134
    let checked = e.target.checked;
Y
yiminghe 已提交
135 136
    let selectedRowKeys = this.state.selectedRowKeys.concat();
    let key = this.getRecordKey(record, rowIndex);
137
    if (checked) {
Y
yiminghe 已提交
138
      selectedRowKeys.push(this.getRecordKey(record, rowIndex));
139
    } else {
Y
yiminghe 已提交
140 141
      selectedRowKeys = selectedRowKeys.filter((i) => {
        return key !== i;
142 143 144
      });
    }
    this.setState({
Y
yiminghe 已提交
145
      selectedRowKeys: selectedRowKeys
146 147
    });
    if (this.props.rowSelection.onSelect) {
Y
yiminghe 已提交
148 149 150
      let data = this.getCurrentPageData();
      let selectedRows = data.filter((row, i) => {
        return selectedRowKeys.indexOf(this.getRecordKey(row, i)) >= 0;
A
afc163 已提交
151
      });
Y
yiminghe 已提交
152
      this.props.rowSelection.onSelect(record, checked, selectedRows);
153 154
    }
  },
A
afc163 已提交
155

A
afc163 已提交
156 157
  handleSelectAllRow(e) {
    let checked = e.target.checked;
Y
yiminghe 已提交
158 159 160 161
    let data = this.getCurrentPageData();
    let selectedRowKeys = checked ? data.map((item, i) => {
      return this.getRecordKey(item, i);
    }) : [];
A
afc163 已提交
162 163
    this.setState({
      selectedRowKeys: selectedRowKeys
164 165
    });
    if (this.props.rowSelection.onSelectAll) {
Y
yiminghe 已提交
166 167
      let selectedRows = data.filter((row, i) => {
        return selectedRowKeys.indexOf(this.getRecordKey(row, i)) >= 0;
A
afc163 已提交
168 169
      });
      this.props.rowSelection.onSelectAll(checked, selectedRows);
A
afc163 已提交
170
    }
A
afc163 已提交
171
  },
A
afc163 已提交
172

173
  handlePageChange(current) {
Y
yiminghe 已提交
174
    let pagination = objectAssign({}, this.state.pagination);
175 176 177 178 179
    if (current) {
      pagination.current = current;
    } else {
      pagination.current = pagination.current || 1;
    }
Y
yiminghe 已提交
180 181 182
    this.fetch({
      // 防止内存泄漏,只维持当页
      selectedRowKeys: [],
A
afc163 已提交
183
      pagination: pagination
Y
yiminghe 已提交
184
    });
185
  },
A
afc163 已提交
186

187
  renderSelectionCheckBox(value, record, index) {
Y
yiminghe 已提交
188
    let rowIndex = this.getRecordKey(record, index); // 从 1 开始
A
afc163 已提交
189
    let checked = this.state.selectedRowKeys.indexOf(rowIndex) >= 0;
Y
yiminghe 已提交
190 191
    return <Checkbox checked={checked} onChange={this.handleSelect.bind(this, record, rowIndex)}/>;
  },
A
afc163 已提交
192 193

  getRecordKey(record, index) {
Y
yiminghe 已提交
194
    return record.key || index;
195
  },
A
afc163 已提交
196

197
  renderRowSelection() {
Y
yiminghe 已提交
198
    let columns = this.props.columns.concat();
199
    if (this.props.rowSelection) {
Y
yiminghe 已提交
200 201 202 203 204 205 206 207 208 209 210
      let data = this.getCurrentPageData();
      let checked;
      if (!data.length) {
        checked = false;
      } else {
        checked = data.every((item, i) => {
          let key = this.getRecordKey(item, i);
          return this.state.selectedRowKeys.indexOf(key) >= 0;
        });
      }
      let checkboxAll = <Checkbox checked={checked} onChange={this.handleSelectAllRow}/>;
211 212 213 214
      let selectionColumn = {
        key: 'selection-column',
        title: checkboxAll,
        width: 60,
A
afc163 已提交
215 216
        render: this.renderSelectionCheckBox,
        className: 'ant-table-selection-column'
217 218
      };
      if (columns[0] &&
Y
yiminghe 已提交
219
        columns[0].key === 'selection-column') {
220 221 222 223 224 225 226
        columns[0] = selectionColumn;
      } else {
        columns.unshift(selectionColumn);
      }
    }
    return columns;
  },
Y
yiminghe 已提交
227

A
afc163 已提交
228
  getCurrentPageData() {
Y
yiminghe 已提交
229 230 231
    return this.isLocalDataSource() ? this.getLocalDataPaging() : this.state.data;
  },

A
afc163 已提交
232
  getColumnKey(column) {
Y
yiminghe 已提交
233 234 235 236 237 238 239
    return column.key || column.dataIndex;
  },

  renderColumnsDropdown(columns) {
    return columns.map((column) => {
      column = objectAssign({}, column);
      let key = this.getColumnKey(column);
A
afc163 已提交
240
      let filterDropdown, menus, sortButton;
241
      if (column.filters && column.filters.length > 0) {
Y
yiminghe 已提交
242 243 244 245
        let colFilters = this.state.filters[key] || [];
        menus = <FilterMenu column={column}
                            selectedFilters={colFilters}
                            confirmFilter={this.handleFilter}/>;
A
afc163 已提交
246
        let dropdownSelectedClass = '';
Y
yiminghe 已提交
247
        if (colFilters.length > 0) {
A
afc163 已提交
248 249 250
          dropdownSelectedClass = 'ant-table-filter-selected';
        }
        filterDropdown = <Dropdown trigger="click"
Y
yiminghe 已提交
251 252
                                   closeOnSelect={false}
                                   overlay={menus}>
A
afc163 已提交
253
          <i title="筛选" className={'anticon anticon-bars ' + dropdownSelectedClass}></i>
A
afc163 已提交
254 255 256
        </Dropdown>;
      }
      if (column.sorter) {
257
        let isSortColumn = (this.state.sortColumn === column);
A
afc163 已提交
258 259
        sortButton = <div className="ant-table-column-sorter">
          <span className={'ant-table-column-sorter-up ' +
260
                           ((isSortColumn && this.state.sortOrder === 'ascend') ? 'on' : 'off')}
Y
yiminghe 已提交
261 262
                title="升序排序"
                onClick={this.toggleSortOrder.bind(this, 'ascend', column)}>
A
afc163 已提交
263 264 265
            <i className="anticon anticon-caret-up"></i>
          </span>
          <span className={'ant-table-column-sorter-down ' +
266
                           ((isSortColumn && this.state.sortOrder === 'descend') ? 'on' : 'off')}
Y
yiminghe 已提交
267 268
                title="降序排序"
                onClick={this.toggleSortOrder.bind(this, 'descend', column)}>
A
afc163 已提交
269 270 271 272
            <i className="anticon anticon-caret-down"></i>
          </span>
        </div>;
      }
Y
yiminghe 已提交
273
      let originalTitle = column.title;
A
afc163 已提交
274
      column.title = [
Y
yiminghe 已提交
275
        originalTitle,
A
afc163 已提交
276 277 278
        sortButton,
        filterDropdown
      ];
A
afc163 已提交
279
      return column;
A
afc163 已提交
280 281
    });
  },
A
afc163 已提交
282

283 284
  renderPagination() {
    // 强制不需要分页
Y
yiminghe 已提交
285 286
    if (!this.hasPagination()) {
      return null;
A
afc163 已提交
287
    }
A
afc163 已提交
288 289 290 291
    let classString = 'ant-table-pagination';
    if (this.props.size === 'small') {
      classString += ' mini';
    }
Y
yiminghe 已提交
292 293 294 295
    let total;
    if (this.isLocalDataSource()) {
      total = this.getLocalData().length;
    }
A
afc163 已提交
296
    return <Pagination className={classString}
Y
yiminghe 已提交
297 298 299
                       onChange={this.handlePageChange}
                       total={total}
                       pageSize={10}
300
      {...this.state.pagination} />;
A
afc163 已提交
301
  },
A
afc163 已提交
302

Y
yiminghe 已提交
303
  prepareParamsArguments(state) {
304 305 306
    // 准备筛选、排序、分页的参数
    let pagination;
    let filters = {};
A
afc163 已提交
307
    let sorter = {};
Y
yiminghe 已提交
308 309 310 311 312
    pagination = state.pagination;
    this.props.columns.forEach((column) => {
      let colFilters = state.filters[this.getColumnKey(column)] || [];
      if (colFilters.length > 0) {
        filters[this.getColumnKey(column)] = colFilters;
313 314
      }
    });
Y
yiminghe 已提交
315 316 317 318 319
    if (state.sortColumn &&
      state.sortOrder &&
      state.sortColumn.dataIndex) {
      sorter.field = state.sortColumn.dataIndex;
      sorter.order = state.sortOrder;
A
afc163 已提交
320 321
    }
    return [pagination, filters, sorter];
322
  },
Y
yiminghe 已提交
323 324 325 326 327 328 329 330 331 332 333 334 335

  fetch(newState) {
    if (this.isLocalDataSource()) {
      if (newState) {
        this.setState(newState);
      }
    } else {
      let state = objectAssign({}, this.state, newState);
      if (newState || !this.state.loading) {
        this.setState(objectAssign({
          loading: true
        }, newState));
      }
A
afc163 已提交
336
      // remote 模式使用 this.dataSource
Y
yiminghe 已提交
337
      let dataSource = this.getRemoteDataSource();
A
afc163 已提交
338
      jQuery.ajax({
339
        url: dataSource.url,
Y
yiminghe 已提交
340
        data: dataSource.getParams.apply(this, this.prepareParamsArguments(state)) || {},
A
afc163 已提交
341 342
        headers: dataSource.headers,
        dataType: 'json',
A
afc163 已提交
343 344
        success: (result) => {
          if (this.isMounted()) {
A
afc163 已提交
345
            let pagination = objectAssign(
Y
yiminghe 已提交
346
              state.pagination,
A
afc163 已提交
347 348
              dataSource.getPagination.call(this, result)
            );
A
afc163 已提交
349
            this.setState({
Y
yiminghe 已提交
350
              loading: false,
351
              data: dataSource.resolve.call(this, result),
Y
yiminghe 已提交
352
              pagination: pagination
A
afc163 已提交
353 354 355
            });
          }
        },
A
afc163 已提交
356
        error: () => {
A
afc163 已提交
357
          this.setState({
Y
yiminghe 已提交
358 359
            loading: false,
            data: []
A
afc163 已提交
360 361 362
          });
        }
      });
Y
yiminghe 已提交
363 364 365
    }
  },

A
afc163 已提交
366
  findColumn(myKey) {
Y
yiminghe 已提交
367 368 369 370 371
    return this.props.columns.filter((c) => {
      return this.getColumnKey(c) === myKey;
    })[0];
  },

A
afc163 已提交
372
  getLocalDataPaging() {
Y
yiminghe 已提交
373 374 375 376 377 378 379
    let data = this.getLocalData();
    let current, pageSize;
    let state = this.state;
    // 如果没有分页的话,默认全部展示
    if (!this.hasPagination()) {
      pageSize = Number.MAX_VALUE;
      current = 1;
380
    } else {
Y
yiminghe 已提交
381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398
      pageSize = state.pagination.pageSize;
      current = state.pagination.current;
    }
    // 分页
    // ---
    // 当数据量少于每页数量时,直接设置数据
    // 否则进行读取分页数据
    if (data.length > pageSize || pageSize === Number.MAX_VALUE) {
      data = data.filter((item, i) => {
        if (i >= (current - 1) * pageSize &&
          i < current * pageSize) {
          return item;
        }
      });
    }
    return data;
  },

A
afc163 已提交
399
  getLocalData() {
Y
yiminghe 已提交
400 401 402 403 404 405 406 407 408 409 410 411 412 413 414
    let state = this.state;
    let data = this.props.dataSource;
    // 排序
    if (state.sortOrder && state.sorter) {
      data = data.sort(state.sorter);
    }
    // 筛选
    if (state.filters) {
      Object.keys(state.filters).forEach((columnKey) => {
        let col = this.findColumn(columnKey);
        let values = state.filters[columnKey] || [];
        data = data.filter((record) => {
          return values.some((v)=> {
            return col.onFilter(v, record);
          });
415
        });
A
afc163 已提交
416
      });
A
afc163 已提交
417
    }
Y
yiminghe 已提交
418
    return data;
A
afc163 已提交
419
  },
Y
yiminghe 已提交
420

A
afc163 已提交
421
  componentDidMount() {
Y
yiminghe 已提交
422 423 424
    if (!this.isLocalDataSource()) {
      this.fetch();
    }
A
afc163 已提交
425
  },
426

Y
yiminghe 已提交
427 428 429 430 431
  render() {
    let data = this.getCurrentPageData();
    let columns = this.renderRowSelection();
    let classString = '';
    if (this.state.loading && this.isLocalDataSource()) {
A
afc163 已提交
432 433 434 435 436
      classString += ' ant-table-loading';
    }
    if (this.props.size === 'small') {
      classString += ' ant-table-small';
    }
Y
yiminghe 已提交
437
    columns = this.renderColumnsDropdown(columns);
438
    return <div className="clearfix">
Y
yiminghe 已提交
439 440 441 442 443 444
      <Table
        {...this.props}
        data={data || []}
        columns={columns}
        className={classString}
        />
445 446
      {this.renderPagination()}
    </div>;
A
afc163 已提交
447 448
  }
});