Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

refactor(table): define when dataSource update, pagination behaviour #295

Merged
merged 1 commit into from
Oct 12, 2020
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
13 changes: 7 additions & 6 deletions packages/components/src/components/table/Table.tsx
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
/* eslint-disable no-param-reassign */
import React, { useContext, useEffect, useMemo } from 'react';
import React, { useContext, useMemo } from 'react';
import RcTable from 'rc-table';
import classNames from 'classnames';
import { cloneDeep, isUndefined, get, has, join } from 'lodash';
Expand Down Expand Up @@ -58,16 +58,17 @@ const Table = <RecordType,>(props: TableProps<RecordType>): React.ReactElement =
resetPagination,
] = usePagination(filtedData, pagination, showIndex);

useEffect(() => {
resetPagination();
}, [dataSource]);

const [transformSelectionPipeline] = useSelection(paginationedData, rowSelection, {
rowKey,
});
const [transformEllipsisTooltipPipeline] = useEllipsisTooltip();

const onTriggerStateUpdate = () => onChange?.(activePaginationedState, activeSorterStates, activeFilterStates);
const onTriggerStateUpdate = (reset: boolean = false) => {
if (reset) {
resetPagination();
}
onChange?.(activePaginationedState, activeSorterStates, activeFilterStates);
};

const renderTitle = (_columns: ColumnsType<RecordType>) =>
_columns.map((column) => {
Expand Down
19 changes: 9 additions & 10 deletions packages/components/src/components/table/Title.tsx
Original file line number Diff line number Diff line change
@@ -1,17 +1,16 @@
import React from 'react';
import classNames from 'classnames';
import {
UpFilled, DownFilled, FilterFilled, QuestionCircleOutlined,
} from '@gio-design/icons';
import { UpFilled, DownFilled, FilterFilled, QuestionCircleOutlined } from '@gio-design/icons';
import { isUndefined } from 'lodash';
import Button from '../button';
import Tooltip from '../tooltip';
import FilterPopover from './FilterPopover';
import { SortOrder, TitleProps } from './interface';

const getNextSortDirection = (sortDirections: SortOrder[], current: SortOrder): SortOrder => (current === null ? sortDirections[0] : sortDirections[sortDirections.indexOf(current) + 1]);
const getNextSortDirection = (sortDirections: SortOrder[], current: SortOrder): SortOrder =>
current === null ? sortDirections[0] : sortDirections[sortDirections.indexOf(current) + 1];

const Title = <RecordType, >(props: TitleProps<RecordType>) => {
const Title = <RecordType,>(props: TitleProps<RecordType>) => {
const { prefixCls, column, onTriggerStateUpdate } = props;

const renderSorter = () => {
Expand All @@ -36,7 +35,7 @@ const Title = <RecordType, >(props: TitleProps<RecordType>) => {
prefixCls={`${prefixCls}`}
className={`${prefixCls}-column-sorter-inner-btn`}
type="text"
icon={(
icon={
<>
<UpFilled
className={classNames(`${prefixCls}-column-sorter-up`, {
Expand All @@ -49,7 +48,7 @@ const Title = <RecordType, >(props: TitleProps<RecordType>) => {
})}
/>
</>
)}
}
onClick={handleSorterChange}
/>
</span>
Expand All @@ -65,7 +64,7 @@ const Title = <RecordType, >(props: TitleProps<RecordType>) => {
const { filteredKeys, filters } = filterState;
const handleFilterPopoverClick = (newFilteredKeys: string[]) => {
updateFilterStates({ ...filterState, filteredKeys: newFilteredKeys });
onTriggerStateUpdate();
onTriggerStateUpdate(true);
};

return (
Expand All @@ -75,12 +74,12 @@ const Title = <RecordType, >(props: TitleProps<RecordType>) => {
<Button
type="assist"
className={`${prefixCls}-column-filter-inner-btn`}
icon={(
icon={
<FilterFilled
size="16px"
className={classNames(`${prefixCls}-column-filter-icon`, { active: filteredKeys.length > 0 })}
/>
)}
}
/>
</FilterPopover>
</span>
Expand Down
37 changes: 36 additions & 1 deletion packages/components/src/components/table/__test__/Table.test.js
Original file line number Diff line number Diff line change
Expand Up @@ -81,7 +81,7 @@ const columns = [
},
];

describe('Testing Tabs', () => {
describe('Testing Table', () => {
const getTable = () => <Table title="列表标题" dataSource={dataSource} columns={columns} pagination={false} />;

it('should be stable', () => {
Expand Down Expand Up @@ -124,4 +124,39 @@ describe('Testing Tabs', () => {
expect(wrapper.exists('.gio-table-column-filter')).toBe(true);
expect(wrapper.exists('.gio-table-column-sorter')).toBe(true);
});

test('when dataSource update and page count less than current, pagination reset', () => {
const data10 = Array.from({ length: 10 }, (_, key) => ({ a: key, key }));
const data20 = Array.from({ length: 20 }, (_, key) => ({ a: key, key }));

const wrapper = mount(
<Table
title="列表标题"
dataSource={data20}
columns={[
{
title: 'a',
dataIndex: 'a',
},
]}
pagination={{
pageSize: 5,
}}
/>
);
// update
wrapper.find('.gio-pagination-item').at(3).simulate('click');
wrapper.setProps({ dataSource: data10 });
expect(() => {
expect(wrapper.find('.gio-pagination-item').first().text()).toBe('1');
expect(wrapper.find('.gio-pagination-total-text').first().text()).toBe(`总共 ${Number(10).toLocaleString()} 条`);
});
// not update
wrapper.find('.gio-pagination-item').at(1).simulate('click');
wrapper.setProps({ dataSource: data20 });
expect(() => {
expect(wrapper.find('.gio-pagination-item-active').first().text()).toBe('2');
expect(wrapper.find('.gio-pagination-total-text').first().text()).toBe(`总共 ${Number(20).toLocaleString()} 条`);
});
});
});
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
// Jest Snapshot v1, https://goo.gl/fbAQLP

exports[`Testing Tabs should be stable 1`] = `
exports[`Testing Table should be stable 1`] = `
initialize {
"0": Object {
"attribs": Object {
Expand Down
13 changes: 9 additions & 4 deletions packages/components/src/components/table/hook/usePagination.tsx
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
/* eslint-disable react-hooks/exhaustive-deps */
import React, { useMemo, useCallback } from 'react';
import React, { useMemo, useCallback, useEffect } from 'react';
import { isUndefined } from 'lodash';
import Pagination, { PaginationProps } from '../../pagination';
import { ColumnType, ColumnsType, PaginationState } from '../interface';
Expand All @@ -18,18 +18,23 @@ const usePagination = <RecordType,>(
] => {
const { current, pageSize, total, ...rest } = pagination || {};
const [localCurrent, setLocalCurrent] = useControlledState<number>(current, 1);
const [localPageSize, setLocalPageSize] = useControlledState<number>(pageSize, 10);
const [localPageSize] = useControlledState<number>(pageSize, 10);
const [controlledTotal, setControlledTotal] = useControlledState<number>(total, data.length);

// when dataSource update && unControlled, Pagination update.
const resetPagination = () => {
if (isUndefined(total)) {
setControlledTotal(data.length, true);
setLocalCurrent(1, true);
setLocalPageSize(10, true);
if (Math.ceil(data.length / localPageSize) < localCurrent) {
setLocalCurrent(1, true);
}
}
};

useEffect(() => {
resetPagination();
}, [data.length]);

// 通过total字段是否受控判断是否后端分页。
const paginationData = useMemo(
() => (isUndefined(total) ? data.slice((localCurrent - 1) * localPageSize, localCurrent * localPageSize) : data),
Expand Down
2 changes: 1 addition & 1 deletion packages/components/src/components/table/interface.ts
Original file line number Diff line number Diff line change
Expand Up @@ -74,7 +74,7 @@ export interface TitleProps<RecordType> {
column: ColumnType<RecordType>;
updateSorterStates: (sortState: SortState<RecordType>) => void;
updateFilterStates: (filterState: FilterState<RecordType>) => void;
onTriggerStateUpdate: () => void;
onTriggerStateUpdate: (reset?: boolean) => void;
}

export interface RowSelection<RecordType> {
Expand Down