index.jsx 13.7 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

18
class DataSource {
Y
yiminghe 已提交
19 20
  init(config) {
    this.config = config;
dqaria's avatar
dqaria 已提交
21
    this.url = config.url || '';
22 23 24
    this.resolve = config.resolve || defaultResolve;
    this.getParams = config.getParams || noop;
    this.getPagination = config.getPagination || noop;
A
afc163 已提交
25
    this.headers = config.headers || {};
A
afc163 已提交
26
    this.data = config.data || {};
Y
yiminghe 已提交
27 28 29 30 31 32 33 34
  }

  constructor(config) {
    if (config) {
      this.init(config);
    }
  }

A
afc163 已提交
35 36 37 38 39 40
  clone(config) {
    if (config) {
      return new DataSource(objectAssign(config, this.config));
    } else {
      return this;
    }
41 42 43 44
  }
}

var AntTable = React.createClass({
Y
yiminghe 已提交
45
  getInitialState() {
A
afc163 已提交
46
    return {
Y
yiminghe 已提交
47
      // 减少状态
A
afc163 已提交
48
      selectedRowKeys: [],
Y
yiminghe 已提交
49 50 51 52 53 54 55 56 57 58
      // only for remote
      data: [],
      filters: {},
      loading: !this.isLocalDataSource(),
      sortColumn: '',
      sortOrder: '',
      sorter: null,
      pagination: this.hasPagination() ? objectAssign({
        pageSize: 10
      }, this.props.pagination) : {}
A
afc163 已提交
59 60
    };
  },
Y
yiminghe 已提交
61

A
afc163 已提交
62 63
  getDefaultProps() {
    return {
A
afc163 已提交
64
      prefixCls: 'ant-table',
A
afc163 已提交
65
      useFixedHeader: false,
A
afc163 已提交
66
      rowSelection: null,
A
afc163 已提交
67 68
      size: 'normal',
      bordered: false
A
afc163 已提交
69 70
    };
  },
Y
yiminghe 已提交
71

A
afc163 已提交
72
  propTypes: {
A
afc163 已提交
73
    dataSource: React.PropTypes.oneOfType([React.PropTypes.array, React.PropTypes.instanceOf(DataSource)])
A
afc163 已提交
74 75
  },

A
afc163 已提交
76
  componentWillReceiveProps(nextProps) {
Y
yiminghe 已提交
77
    if (('pagination' in nextProps) && nextProps.pagination !== false) {
A
afc163 已提交
78
      this.setState({
Y
yiminghe 已提交
79
        pagination: objectAssign({}, this.state.pagination, nextProps.pagination)
A
afc163 已提交
80 81
      });
    }
Y
yiminghe 已提交
82 83 84 85 86 87 88 89 90
    if (!this.isLocalDataSource()) {
      if (!equals(nextProps, this.props)) {
        this.setState({
          selectedRowKeys: [],
          loading: true
        }, this.fetch);
      }
    }
    if (nextProps.columns !== this.props.columns) {
A
afc163 已提交
91
      this.setState({
Y
yiminghe 已提交
92
        filters: {}
A
afc163 已提交
93 94 95
      });
    }
  },
A
afc163 已提交
96 97

  hasPagination(pagination) {
Y
yiminghe 已提交
98 99
    if (pagination === undefined) {
      pagination = this.props.pagination;
A
afc163 已提交
100
    }
Y
yiminghe 已提交
101 102
    return pagination !== false;
  },
A
afc163 已提交
103 104

  isLocalDataSource() {
Y
yiminghe 已提交
105
    return Array.isArray(this.props.dataSource);
A
afc163 已提交
106
  },
A
afc163 已提交
107 108

  getRemoteDataSource() {
Y
yiminghe 已提交
109
    return this.props.dataSource;
A
afc163 已提交
110
  },
A
afc163 已提交
111

A
afc163 已提交
112
  toggleSortOrder(order, column) {
113 114
    let sortColumn = this.state.sortColumn;
    let sortOrder = this.state.sortOrder;
J
jljsj 已提交
115
    let sorter;
A
afc163 已提交
116 117 118 119 120 121 122 123 124 125 126 127 128
    // 只同时允许一列进行排序,否则会导致排序顺序的逻辑问题
    let isSortColumn = this.isSortColumn(column);
    if (!isSortColumn) {  // 当前列未排序
      sortOrder = order;
      sortColumn = column;
    } else {                      // 当前列已排序
      if (sortOrder === order) {  // 切换为未排序状态
        sortOrder = '';
        sortColumn = null;
      } else {                    // 切换为排序状态
        sortOrder = order;
      }
    }
Y
yiminghe 已提交
129 130
    if (this.isLocalDataSource()) {
      sorter = function () {
131
        let result = column.sorter.apply(this, arguments);
132
        if (sortOrder === 'ascend') {
133
          return result;
134
        } else if (sortOrder === 'descend') {
135 136 137
          return -result;
        }
      };
A
afc163 已提交
138
    }
Y
yiminghe 已提交
139
    this.fetch({
A
afc163 已提交
140
      sortOrder: sortOrder,
J
jljsj 已提交
141 142
      sortColumn: sortColumn,
      sorter: sorter
Y
yiminghe 已提交
143
    });
A
afc163 已提交
144
  },
A
afc163 已提交
145

Y
yiminghe 已提交
146 147 148 149 150 151 152 153
  handleFilter(column, filters) {
    filters = objectAssign({}, this.state.filters, {
      [this.getColumnKey(column)]: filters
    });
    this.fetch({
      selectedRowKeys: [],
      filters: filters
    });
A
afc163 已提交
154
  },
A
afc163 已提交
155

Y
yiminghe 已提交
156
  handleSelect(record, rowIndex, e) {
A
afc163 已提交
157
    let checked = e.target.checked;
Y
yiminghe 已提交
158 159
    let selectedRowKeys = this.state.selectedRowKeys.concat();
    let key = this.getRecordKey(record, rowIndex);
160
    if (checked) {
Y
yiminghe 已提交
161
      selectedRowKeys.push(this.getRecordKey(record, rowIndex));
162
    } else {
Y
yiminghe 已提交
163 164
      selectedRowKeys = selectedRowKeys.filter((i) => {
        return key !== i;
165 166 167
      });
    }
    this.setState({
Y
yiminghe 已提交
168
      selectedRowKeys: selectedRowKeys
169 170
    });
    if (this.props.rowSelection.onSelect) {
Y
yiminghe 已提交
171 172 173
      let data = this.getCurrentPageData();
      let selectedRows = data.filter((row, i) => {
        return selectedRowKeys.indexOf(this.getRecordKey(row, i)) >= 0;
A
afc163 已提交
174
      });
Y
yiminghe 已提交
175
      this.props.rowSelection.onSelect(record, checked, selectedRows);
176 177
    }
  },
A
afc163 已提交
178

A
afc163 已提交
179 180
  handleSelectAllRow(e) {
    let checked = e.target.checked;
Y
yiminghe 已提交
181 182 183 184
    let data = this.getCurrentPageData();
    let selectedRowKeys = checked ? data.map((item, i) => {
      return this.getRecordKey(item, i);
    }) : [];
A
afc163 已提交
185 186
    this.setState({
      selectedRowKeys: selectedRowKeys
187 188
    });
    if (this.props.rowSelection.onSelectAll) {
Y
yiminghe 已提交
189 190
      let selectedRows = data.filter((row, i) => {
        return selectedRowKeys.indexOf(this.getRecordKey(row, i)) >= 0;
A
afc163 已提交
191 192
      });
      this.props.rowSelection.onSelectAll(checked, selectedRows);
A
afc163 已提交
193
    }
A
afc163 已提交
194
  },
A
afc163 已提交
195

196
  handlePageChange(current) {
Y
yiminghe 已提交
197
    let pagination = objectAssign({}, this.state.pagination);
198 199 200 201 202
    if (current) {
      pagination.current = current;
    } else {
      pagination.current = pagination.current || 1;
    }
Y
yiminghe 已提交
203 204 205
    this.fetch({
      // 防止内存泄漏,只维持当页
      selectedRowKeys: [],
A
afc163 已提交
206
      pagination: pagination
Y
yiminghe 已提交
207
    });
208
  },
A
afc163 已提交
209

210
  renderSelectionCheckBox(value, record, index) {
Y
yiminghe 已提交
211
    let rowIndex = this.getRecordKey(record, index); // 从 1 开始
A
afc163 已提交
212
    let checked = this.state.selectedRowKeys.indexOf(rowIndex) >= 0;
Y
yiminghe 已提交
213 214
    return <Checkbox checked={checked} onChange={this.handleSelect.bind(this, record, rowIndex)}/>;
  },
A
afc163 已提交
215 216

  getRecordKey(record, index) {
Y
yiminghe 已提交
217
    return record.key || index;
218
  },
A
afc163 已提交
219

220
  renderRowSelection() {
Y
yiminghe 已提交
221
    let columns = this.props.columns.concat();
222
    if (this.props.rowSelection) {
Y
yiminghe 已提交
223 224 225 226 227 228 229 230 231 232 233
      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}/>;
234 235 236 237
      let selectionColumn = {
        key: 'selection-column',
        title: checkboxAll,
        width: 60,
A
afc163 已提交
238 239
        render: this.renderSelectionCheckBox,
        className: 'ant-table-selection-column'
240 241
      };
      if (columns[0] &&
Y
yiminghe 已提交
242
        columns[0].key === 'selection-column') {
243 244 245 246 247 248 249
        columns[0] = selectionColumn;
      } else {
        columns.unshift(selectionColumn);
      }
    }
    return columns;
  },
Y
yiminghe 已提交
250

A
afc163 已提交
251
  getCurrentPageData() {
Y
yiminghe 已提交
252 253 254
    return this.isLocalDataSource() ? this.getLocalDataPaging() : this.state.data;
  },

A
afc163 已提交
255 256 257 258 259 260 261 262 263 264 265
  getColumnKey(column, index) {
    return column.key || column.dataIndex || index;
  },

  isSortColumn(column) {
    if (!column || !this.state.sortColumn) {
      return false;
    }
    let colKey = this.getColumnKey(column);
    let isSortColumn = (this.getColumnKey(this.state.sortColumn) === colKey);
    return isSortColumn;
Y
yiminghe 已提交
266 267 268
  },

  renderColumnsDropdown(columns) {
Y
yiminghe 已提交
269
    return columns.map((column, i) => {
Y
yiminghe 已提交
270
      column = objectAssign({}, column);
A
afc163 已提交
271
      let key = this.getColumnKey(column, i);
A
afc163 已提交
272
      let filterDropdown, menus, sortButton;
273
      if (column.filters && column.filters.length > 0) {
Y
yiminghe 已提交
274 275
        let colFilters = this.state.filters[key] || [];
        menus = <FilterMenu column={column}
Y
yiminghe 已提交
276
                            selectedKeys={colFilters}
Y
yiminghe 已提交
277
                            confirmFilter={this.handleFilter}/>;
A
afc163 已提交
278
        let dropdownSelectedClass = '';
Y
yiminghe 已提交
279
        if (colFilters.length > 0) {
A
afc163 已提交
280 281 282
          dropdownSelectedClass = 'ant-table-filter-selected';
        }
        filterDropdown = <Dropdown trigger="click"
Y
yiminghe 已提交
283
                                   overlay={menus}>
A
afc163 已提交
284
          <i title="筛选" className={'anticon anticon-bars ' + dropdownSelectedClass}></i>
A
afc163 已提交
285 286 287
        </Dropdown>;
      }
      if (column.sorter) {
A
afc163 已提交
288
        let isSortColumn = this.isSortColumn(column);
Y
yiminghe 已提交
289 290
        if (isSortColumn) {
          column.className = column.className || '';
A
afc163 已提交
291 292 293
          if (this.state.sortOrder) {
            column.className += ' ant-table-column-sort';
          }
Y
yiminghe 已提交
294
        }
A
afc163 已提交
295 296
        sortButton = <div className="ant-table-column-sorter">
          <span className={'ant-table-column-sorter-up ' +
297
                           ((isSortColumn && this.state.sortOrder === 'ascend') ? 'on' : 'off')}
Y
yiminghe 已提交
298 299
                title="升序排序"
                onClick={this.toggleSortOrder.bind(this, 'ascend', column)}>
A
afc163 已提交
300 301 302
            <i className="anticon anticon-caret-up"></i>
          </span>
          <span className={'ant-table-column-sorter-down ' +
303
                           ((isSortColumn && this.state.sortOrder === 'descend') ? 'on' : 'off')}
Y
yiminghe 已提交
304 305
                title="降序排序"
                onClick={this.toggleSortOrder.bind(this, 'descend', column)}>
A
afc163 已提交
306 307 308 309 310
            <i className="anticon anticon-caret-down"></i>
          </span>
        </div>;
      }
      column.title = [
Y
yiminghe 已提交
311
        column.title,
A
afc163 已提交
312 313 314
        sortButton,
        filterDropdown
      ];
A
afc163 已提交
315
      return column;
A
afc163 已提交
316 317
    });
  },
A
afc163 已提交
318

319 320
  renderPagination() {
    // 强制不需要分页
Y
yiminghe 已提交
321 322
    if (!this.hasPagination()) {
      return null;
A
afc163 已提交
323
    }
A
afc163 已提交
324 325 326 327
    let classString = 'ant-table-pagination';
    if (this.props.size === 'small') {
      classString += ' mini';
    }
Y
yiminghe 已提交
328 329 330 331
    let total;
    if (this.isLocalDataSource()) {
      total = this.getLocalData().length;
    }
A
afc163 已提交
332
    return <Pagination className={classString}
Y
yiminghe 已提交
333 334 335
                       onChange={this.handlePageChange}
                       total={total}
                       pageSize={10}
336
      {...this.state.pagination} />;
A
afc163 已提交
337
  },
A
afc163 已提交
338

Y
yiminghe 已提交
339
  prepareParamsArguments(state) {
340 341 342
    // 准备筛选、排序、分页的参数
    let pagination;
    let filters = {};
A
afc163 已提交
343
    let sorter = {};
Y
yiminghe 已提交
344 345 346 347 348
    pagination = state.pagination;
    this.props.columns.forEach((column) => {
      let colFilters = state.filters[this.getColumnKey(column)] || [];
      if (colFilters.length > 0) {
        filters[this.getColumnKey(column)] = colFilters;
349 350
      }
    });
Y
yiminghe 已提交
351 352 353 354 355
    if (state.sortColumn &&
      state.sortOrder &&
      state.sortColumn.dataIndex) {
      sorter.field = state.sortColumn.dataIndex;
      sorter.order = state.sortOrder;
A
afc163 已提交
356 357
    }
    return [pagination, filters, sorter];
358
  },
Y
yiminghe 已提交
359 360 361 362 363 364 365 366 367 368 369 370 371

  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 已提交
372
      // remote 模式使用 this.dataSource
Y
yiminghe 已提交
373
      let dataSource = this.getRemoteDataSource();
A
afc163 已提交
374
      let buildInParams = dataSource.getParams.apply(this, this.prepareParamsArguments(state)) || {};
A
afc163 已提交
375
      return jQuery.ajax({
376
        url: dataSource.url,
A
afc163 已提交
377
        data: objectAssign(buildInParams, dataSource.data),
A
afc163 已提交
378 379
        headers: dataSource.headers,
        dataType: 'json',
A
afc163 已提交
380 381
        success: (result) => {
          if (this.isMounted()) {
A
afc163 已提交
382
            let pagination = objectAssign(
Y
yiminghe 已提交
383
              state.pagination,
A
afc163 已提交
384 385
              dataSource.getPagination.call(this, result)
            );
A
afc163 已提交
386
            this.setState({
Y
yiminghe 已提交
387
              loading: false,
388
              data: dataSource.resolve.call(this, result),
Y
yiminghe 已提交
389
              pagination: pagination
A
afc163 已提交
390 391 392
            });
          }
        },
A
afc163 已提交
393
        error: () => {
A
afc163 已提交
394
          this.setState({
Y
yiminghe 已提交
395 396
            loading: false,
            data: []
A
afc163 已提交
397 398 399
          });
        }
      });
Y
yiminghe 已提交
400 401 402
    }
  },

A
afc163 已提交
403
  findColumn(myKey) {
Y
yiminghe 已提交
404 405 406 407 408
    return this.props.columns.filter((c) => {
      return this.getColumnKey(c) === myKey;
    })[0];
  },

A
afc163 已提交
409
  getLocalDataPaging() {
Y
yiminghe 已提交
410 411 412 413 414 415 416
    let data = this.getLocalData();
    let current, pageSize;
    let state = this.state;
    // 如果没有分页的话,默认全部展示
    if (!this.hasPagination()) {
      pageSize = Number.MAX_VALUE;
      current = 1;
417
    } else {
Y
yiminghe 已提交
418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435
      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 已提交
436
  getLocalData() {
Y
yiminghe 已提交
437 438 439 440 441 442 443 444 445 446 447
    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] || [];
A
afc163 已提交
448 449 450
        if (values.length === 0) {
          return;
        }
Y
yiminghe 已提交
451 452 453 454
        data = data.filter((record) => {
          return values.some((v)=> {
            return col.onFilter(v, record);
          });
455
        });
A
afc163 已提交
456
      });
A
afc163 已提交
457
    }
Y
yiminghe 已提交
458
    return data;
A
afc163 已提交
459
  },
Y
yiminghe 已提交
460

A
afc163 已提交
461
  componentDidMount() {
Y
yiminghe 已提交
462 463 464
    if (!this.isLocalDataSource()) {
      this.fetch();
    }
A
afc163 已提交
465
  },
466

Y
yiminghe 已提交
467 468 469 470 471
  render() {
    let data = this.getCurrentPageData();
    let columns = this.renderRowSelection();
    let classString = '';
    if (this.state.loading && this.isLocalDataSource()) {
A
afc163 已提交
472 473 474 475 476
      classString += ' ant-table-loading';
    }
    if (this.props.size === 'small') {
      classString += ' ant-table-small';
    }
A
afc163 已提交
477 478 479
    if (this.props.bordered) {
      classString += ' ant-table-bordered';
    }
Y
yiminghe 已提交
480
    columns = this.renderColumnsDropdown(columns);
481
    return <div className="clearfix">
Y
yiminghe 已提交
482 483 484 485 486 487
      <Table
        {...this.props}
        data={data || []}
        columns={columns}
        className={classString}
        />
488 489
      {this.renderPagination()}
    </div>;
A
afc163 已提交
490 491
  }
});
492 493 494

AntTable.DataSource = DataSource;

dqaria's avatar
dqaria 已提交
495
export default AntTable;