index.jsx 13.2 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 19
class DataSource {
  constructor(config) {
dqaria's avatar
dqaria 已提交
20
    this.url = config.url || '';
21 22 23 24 25 26 27 28
    this.resolve = config.resolve || defaultResolve;
    this.getParams = config.getParams || noop;
    this.getPagination = config.getPagination || noop;
    this.fetch = noop;
  }
}

var AntTable = React.createClass({
Y
yiminghe 已提交
29
  getInitialState() {
A
afc163 已提交
30
    return {
Y
yiminghe 已提交
31
      // 减少状态
A
afc163 已提交
32
      selectedRowKeys: [],
Y
yiminghe 已提交
33 34 35 36 37 38 39 40 41 42
      // only for remote
      data: [],
      filters: {},
      loading: !this.isLocalDataSource(),
      sortColumn: '',
      sortOrder: '',
      sorter: null,
      pagination: this.hasPagination() ? objectAssign({
        pageSize: 10
      }, this.props.pagination) : {}
A
afc163 已提交
43 44
    };
  },
Y
yiminghe 已提交
45

A
afc163 已提交
46 47
  getDefaultProps() {
    return {
A
afc163 已提交
48
      prefixCls: 'ant-table',
A
afc163 已提交
49
      useFixedHeader: false,
A
afc163 已提交
50 51
      rowSelection: null,
      size: 'normal'
A
afc163 已提交
52 53
    };
  },
Y
yiminghe 已提交
54

A
afc163 已提交
55
  componentWillReceiveProps(nextProps) {
Y
yiminghe 已提交
56
    if (('pagination' in nextProps) && nextProps.pagination !== false) {
A
afc163 已提交
57
      this.setState({
Y
yiminghe 已提交
58
        pagination: objectAssign({}, this.state.pagination, nextProps.pagination)
A
afc163 已提交
59 60
      });
    }
Y
yiminghe 已提交
61 62 63 64 65 66 67 68 69
    if (!this.isLocalDataSource()) {
      if (!equals(nextProps, this.props)) {
        this.setState({
          selectedRowKeys: [],
          loading: true
        }, this.fetch);
      }
    }
    if (nextProps.columns !== this.props.columns) {
A
afc163 已提交
70
      this.setState({
Y
yiminghe 已提交
71
        filters: {}
A
afc163 已提交
72 73 74
      });
    }
  },
A
afc163 已提交
75 76

  hasPagination(pagination) {
Y
yiminghe 已提交
77 78
    if (pagination === undefined) {
      pagination = this.props.pagination;
A
afc163 已提交
79
    }
Y
yiminghe 已提交
80 81
    return pagination !== false;
  },
A
afc163 已提交
82 83

  isLocalDataSource() {
Y
yiminghe 已提交
84
    return Array.isArray(this.props.dataSource);
A
afc163 已提交
85
  },
A
afc163 已提交
86 87

  getRemoteDataSource() {
88 89 90 91 92 93 94 95 96 97 98 99 100
    // 判断传入DataSource类型
    var dataSource = this.props.dataSource;
    if ( dataSource.constructor === DataSource ) {
      // 当传入 dataSource Instance 时,对外部DataSource暴露fetch接口
      dataSource.fetch = this.fetch;
      return dataSource;
    } else {
      return objectAssign({
        resolve: defaultResolve,
        getParams: noop,
        getPagination: noop
      }, this.props.dataSource);
    }
A
afc163 已提交
101
  },
A
afc163 已提交
102

A
afc163 已提交
103
  toggleSortOrder(order, column) {
104 105
    let sortColumn = this.state.sortColumn;
    let sortOrder = this.state.sortOrder;
J
jljsj 已提交
106
    let sorter;
107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122
    // 同时允许一列进行排序,否则会导致排序顺序的逻辑问题
    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 已提交
123
    }
Y
yiminghe 已提交
124 125
    if (this.isLocalDataSource()) {
      sorter = function () {
126
        let result = column.sorter.apply(this, arguments);
127
        if (sortOrder === 'ascend') {
128
          return result;
129
        } else if (sortOrder === 'descend') {
130 131 132
          return -result;
        }
      };
A
afc163 已提交
133
    }
Y
yiminghe 已提交
134
    this.fetch({
A
afc163 已提交
135
      sortOrder: sortOrder,
J
jljsj 已提交
136 137
      sortColumn: sortColumn,
      sorter: sorter
Y
yiminghe 已提交
138
    });
A
afc163 已提交
139
  },
A
afc163 已提交
140

Y
yiminghe 已提交
141 142 143 144 145 146 147 148
  handleFilter(column, filters) {
    filters = objectAssign({}, this.state.filters, {
      [this.getColumnKey(column)]: filters
    });
    this.fetch({
      selectedRowKeys: [],
      filters: filters
    });
A
afc163 已提交
149
  },
A
afc163 已提交
150

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

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

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

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

  getRecordKey(record, index) {
Y
yiminghe 已提交
212
    return record.key || index;
213
  },
A
afc163 已提交
214

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

A
afc163 已提交
246
  getCurrentPageData() {
Y
yiminghe 已提交
247 248 249
    return this.isLocalDataSource() ? this.getLocalDataPaging() : this.state.data;
  },

A
afc163 已提交
250
  getColumnKey(column) {
Y
yiminghe 已提交
251 252 253 254 255 256
    return column.key || column.dataIndex;
  },

  renderColumnsDropdown(columns) {
    return columns.map((column) => {
      let key = this.getColumnKey(column);
A
afc163 已提交
257
      let filterDropdown, menus, sortButton;
258
      if (column.filters && column.filters.length > 0) {
Y
yiminghe 已提交
259 260 261 262
        let colFilters = this.state.filters[key] || [];
        menus = <FilterMenu column={column}
                            selectedFilters={colFilters}
                            confirmFilter={this.handleFilter}/>;
A
afc163 已提交
263
        let dropdownSelectedClass = '';
Y
yiminghe 已提交
264
        if (colFilters.length > 0) {
A
afc163 已提交
265 266 267
          dropdownSelectedClass = 'ant-table-filter-selected';
        }
        filterDropdown = <Dropdown trigger="click"
Y
yiminghe 已提交
268 269
                                   closeOnSelect={false}
                                   overlay={menus}>
A
afc163 已提交
270
          <i title="筛选" className={'anticon anticon-bars ' + dropdownSelectedClass}></i>
A
afc163 已提交
271 272 273
        </Dropdown>;
      }
      if (column.sorter) {
274
        let isSortColumn = (this.state.sortColumn === column);
A
afc163 已提交
275 276
        sortButton = <div className="ant-table-column-sorter">
          <span className={'ant-table-column-sorter-up ' +
277
                           ((isSortColumn && this.state.sortOrder === 'ascend') ? 'on' : 'off')}
Y
yiminghe 已提交
278 279
                title="升序排序"
                onClick={this.toggleSortOrder.bind(this, 'ascend', column)}>
A
afc163 已提交
280 281 282
            <i className="anticon anticon-caret-up"></i>
          </span>
          <span className={'ant-table-column-sorter-down ' +
283
                           ((isSortColumn && this.state.sortOrder === 'descend') ? 'on' : 'off')}
Y
yiminghe 已提交
284 285
                title="降序排序"
                onClick={this.toggleSortOrder.bind(this, 'descend', column)}>
A
afc163 已提交
286 287 288 289
            <i className="anticon anticon-caret-down"></i>
          </span>
        </div>;
      }
A
afc163 已提交
290 291 292
      if (!column.originalTitle) {
        column.originalTitle = column.title;
      }
A
afc163 已提交
293
      column.title = [
A
afc163 已提交
294
        column.originalTitle,
A
afc163 已提交
295 296 297
        sortButton,
        filterDropdown
      ];
A
afc163 已提交
298
      return column;
A
afc163 已提交
299 300
    });
  },
A
afc163 已提交
301

302 303
  renderPagination() {
    // 强制不需要分页
Y
yiminghe 已提交
304 305
    if (!this.hasPagination()) {
      return null;
A
afc163 已提交
306
    }
A
afc163 已提交
307 308 309 310
    let classString = 'ant-table-pagination';
    if (this.props.size === 'small') {
      classString += ' mini';
    }
Y
yiminghe 已提交
311 312 313 314
    let total;
    if (this.isLocalDataSource()) {
      total = this.getLocalData().length;
    }
A
afc163 已提交
315
    return <Pagination className={classString}
Y
yiminghe 已提交
316 317 318
                       onChange={this.handlePageChange}
                       total={total}
                       pageSize={10}
319
      {...this.state.pagination} />;
A
afc163 已提交
320
  },
A
afc163 已提交
321

Y
yiminghe 已提交
322
  prepareParamsArguments(state) {
323 324 325
    // 准备筛选、排序、分页的参数
    let pagination;
    let filters = {};
A
afc163 已提交
326
    let sorter = {};
Y
yiminghe 已提交
327 328 329 330 331
    pagination = state.pagination;
    this.props.columns.forEach((column) => {
      let colFilters = state.filters[this.getColumnKey(column)] || [];
      if (colFilters.length > 0) {
        filters[this.getColumnKey(column)] = colFilters;
332 333
      }
    });
Y
yiminghe 已提交
334 335 336 337 338
    if (state.sortColumn &&
      state.sortOrder &&
      state.sortColumn.dataIndex) {
      sorter.field = state.sortColumn.dataIndex;
      sorter.order = state.sortOrder;
A
afc163 已提交
339 340
    }
    return [pagination, filters, sorter];
341
  },
Y
yiminghe 已提交
342 343 344 345 346 347 348 349 350 351 352 353 354

  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 已提交
355
      // remote 模式使用 this.dataSource
Y
yiminghe 已提交
356
      let dataSource = this.getRemoteDataSource();
A
afc163 已提交
357
      jQuery.ajax({
358
        url: dataSource.url,
Y
yiminghe 已提交
359
        data: dataSource.getParams.apply(this, this.prepareParamsArguments(state)) || {},
A
afc163 已提交
360 361
        headers: dataSource.headers,
        dataType: 'json',
A
afc163 已提交
362 363
        success: (result) => {
          if (this.isMounted()) {
A
afc163 已提交
364
            let pagination = objectAssign(
Y
yiminghe 已提交
365
              state.pagination,
A
afc163 已提交
366 367
              dataSource.getPagination.call(this, result)
            );
A
afc163 已提交
368
            this.setState({
Y
yiminghe 已提交
369
              loading: false,
370
              data: dataSource.resolve.call(this, result),
Y
yiminghe 已提交
371
              pagination: pagination
A
afc163 已提交
372 373 374
            });
          }
        },
A
afc163 已提交
375
        error: () => {
A
afc163 已提交
376
          this.setState({
Y
yiminghe 已提交
377 378
            loading: false,
            data: []
A
afc163 已提交
379 380 381
          });
        }
      });
Y
yiminghe 已提交
382 383 384
    }
  },

A
afc163 已提交
385
  findColumn(myKey) {
Y
yiminghe 已提交
386 387 388 389 390
    return this.props.columns.filter((c) => {
      return this.getColumnKey(c) === myKey;
    })[0];
  },

A
afc163 已提交
391
  getLocalDataPaging() {
Y
yiminghe 已提交
392 393 394 395 396 397 398
    let data = this.getLocalData();
    let current, pageSize;
    let state = this.state;
    // 如果没有分页的话,默认全部展示
    if (!this.hasPagination()) {
      pageSize = Number.MAX_VALUE;
      current = 1;
399
    } else {
Y
yiminghe 已提交
400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417
      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 已提交
418
  getLocalData() {
Y
yiminghe 已提交
419 420 421 422 423 424 425 426 427 428 429
    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 已提交
430 431 432
        if (values.length === 0) {
          return;
        }
Y
yiminghe 已提交
433 434 435 436
        data = data.filter((record) => {
          return values.some((v)=> {
            return col.onFilter(v, record);
          });
437
        });
A
afc163 已提交
438
      });
A
afc163 已提交
439
    }
Y
yiminghe 已提交
440
    return data;
A
afc163 已提交
441
  },
Y
yiminghe 已提交
442

A
afc163 已提交
443
  componentDidMount() {
Y
yiminghe 已提交
444 445 446
    if (!this.isLocalDataSource()) {
      this.fetch();
    }
A
afc163 已提交
447
  },
448

Y
yiminghe 已提交
449 450 451 452 453
  render() {
    let data = this.getCurrentPageData();
    let columns = this.renderRowSelection();
    let classString = '';
    if (this.state.loading && this.isLocalDataSource()) {
A
afc163 已提交
454 455 456 457 458
      classString += ' ant-table-loading';
    }
    if (this.props.size === 'small') {
      classString += ' ant-table-small';
    }
Y
yiminghe 已提交
459
    columns = this.renderColumnsDropdown(columns);
460
    return <div className="clearfix">
Y
yiminghe 已提交
461 462 463 464 465 466
      <Table
        {...this.props}
        data={data || []}
        columns={columns}
        className={classString}
        />
467 468
      {this.renderPagination()}
    </div>;
A
afc163 已提交
469 470
  }
});
471 472 473

AntTable.DataSource = DataSource;

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