Skip to content

Commit

Permalink
feature to master v1.3.0 (#107)
Browse files Browse the repository at this point in the history
* feat: add useSelections

* refactor: rewrite useSelections and add test

* fix: fix test of useSelections

* refactor: useUpdateEffect (#103)

* feat: add useUpdateEffect

* feat: useSelections add setSelected and add test

* refactor: return object instead of array

* feat: add demo for useSelections

* docs: add document for useSelections

* fix: fix demo of useSelections

* feat: add usePagination

* chore: add usePagination reference

* fix: Put the function with same deps into one useMeno

* feat: useAntdTable add sorter, filters

* fix: deps error

* fix: change halfSelected -> partiallySelected

* fix: useAntdTable determine if filters are equal change to a more robust method

* feat: add usePagination (#105)

* feat: add usePagination
  • Loading branch information
brickspert authored and ttys026 committed Oct 24, 2019
1 parent d1aeeff commit 9092737
Show file tree
Hide file tree
Showing 19 changed files with 1,127 additions and 34 deletions.
2 changes: 1 addition & 1 deletion package.json
Original file line number Diff line number Diff line change
Expand Up @@ -29,7 +29,7 @@
"pub:doc": "now --prod"
},
"dependencies": {
"react-use": "^10.6.2",
"lodash.isequal": "^4.5.0",
"resize-observer-polyfill": "^1.5.1"
},
"peerDependencies": {
Expand Down
4 changes: 4 additions & 0 deletions src/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -10,6 +10,8 @@ import useVirtualList from './useVirtualList';
import { configResponsive, useResponsive } from './useResponsive';
import useSize from './useSize';
import useLocalStorageState from './useLocalStorageState';
import useUpdateEffect from './useUpdateEffect';
import usePagination from './usePagination';

const useControlledValue: typeof useControllableValue = function (...args) {
console.warn(
Expand All @@ -34,4 +36,6 @@ export {
useSize,
configResponsive,
configRequest,
useUpdateEffect,
usePagination,
};
57 changes: 57 additions & 0 deletions src/useAntdTable/SorterDemo.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,57 @@
import { Table } from 'antd';
import React from 'react';
import useAntdTable from '.';

const Demo = () => {
const getTableData = ({ current, pageSize, ...rest }) => {
console.log(current, pageSize, rest);
return fetch(`https://randomuser.me/api?results=55&page=${current}&size=${pageSize}`)
.then(res => res.json())
.then(res => ({
page: res.info.page,
total: res.info.results,
data: res.results,
}));
};

const { tableProps, filters, sorter } = useAntdTable(getTableData, [], {
defaultPageSize: 5,
});

const columns = [
{
title: 'name',
dataIndex: 'name',
key: 'name',
width: 100,
render(_, record) {
return record.name.title;
},
},
{
title: 'email',
dataIndex: 'email',
key: 'email',
sorter: true,
sortOrder: sorter.field === 'email' && sorter.order,
width: 350,
},
{
title: 'phone',
dataIndex: 'phone',
key: 'phone',
},
{
title: 'gender',
key: 'gender',
filters: [{ text: 'male', value: 'male' }, { text: 'female', value: 'female' }],
filteredValue: filters.gender,
width: 200,
dataIndex: 'gender',
},
];

return <Table columns={columns} rowKey="email" {...tableProps} />;
};

export default Demo;
35 changes: 34 additions & 1 deletion src/useAntdTable/__tests__/index.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -97,7 +97,40 @@ describe('useAntdTable', () => {
expect(hook.result.current.tableProps.pagination.pageSize).toEqual(10);
expect(hook.result.current.tableProps.pagination.total).toEqual(20);
});

it('should sorter, filters work', async () => {
queryArgs = undefined;
act(() => {
hook = setUp({
asyncFn,
});
});
await hook.waitForNextUpdate();
act(() => {
hook.result.current.tableProps.onChange({
current: 2,
pageSize: 5,
});
});
await hook.waitForNextUpdate();
expect(hook.result.current.tableProps.pagination.current).toEqual(2);
/* 改变 filter, sorter */
act(() => {
hook.result.current.tableProps.onChange(
{
current: 2,
pageSize: 5,
},
{ gender: ['male'] },
{ field: 'email', order: 'ascend' } as any,
);
});
await hook.waitForNextUpdate();
expect(queryArgs.current).toEqual(1);
expect(queryArgs.pageSize).toEqual(5);
expect(queryArgs.sorter.field).toEqual('email');
expect(queryArgs.sorter.order).toEqual('ascend');
expect(queryArgs.filters.gender[0]).toEqual('male');
});
it('should form, defaultPageSize, id work', async () => {
queryArgs = undefined;
act(() => {
Expand Down
34 changes: 25 additions & 9 deletions src/useAntdTable/index.mdx
Original file line number Diff line number Diff line change
Expand Up @@ -11,6 +11,7 @@ import { Button, Col, Form, Input, Row, Select, Table } from 'antd';
import { useState } from 'react';
import CacheDemo from './CacheDemo';
import Demo from './Demo';
import SorterDemo from './SorterDemo';
import useAntdTable from './';

# useAntdTable
Expand Down Expand Up @@ -57,7 +58,7 @@ import useAntdTable from './';
dataIndex: 'name',
key: 'name',
width: 100,
render({ }, record) {
render(_, record) {
return record.name.title;
},
},
Expand Down Expand Up @@ -100,6 +101,15 @@ import useAntdTable from './';
}
</Playground>

### 带筛选与排序的表格

<Playground>
<>
<SorterDemo />
代码见:<a target='_blank' href='https://github.com/umijs/hooks/blob/master/src/useAntdTable/SorterDemo.js'>https://github.com/umijs/hooks/blob/master/src/useAntdTable/SorterDemo.js</a>
</>
</Playground>

### 搜索表单与列表联动

<Playground>
Expand Down Expand Up @@ -133,6 +143,8 @@ const {
}
},
refresh: () => void,
sorter,
filters,
search?: {
type: 'simple' | 'advance',
changeType: () => void,
Expand All @@ -145,6 +157,8 @@ params:(
service: ({
current: number,
pageSize: number,
sorter,
filters,
[key: string]: any,
}) => Promise<Result>,
deps?: DependencyList = [],
Expand All @@ -164,27 +178,29 @@ params:(

### 结果

| 参数 | 说明 | 类型 | 默认值 |
|---------------------------|---------------------------------|-------------------------------|--------------------|
| 参数 | 说明 | 类型 | 默认值 |
|--------------------------------|---------------------------------|-------------------------------|--------------------|
| tableProps.loading | 是否正在加载 | boolean | false |
| tableProps.dataSource | table 需要使用的数据 | array | - |
| tableProps.onChange | antd Table 组件的 onChange 函数 | (e: PaginationConfig) => void | - |
| tableProps.pagination.current | 当前页数 | number | 1 |
| tableProps.pagination.pageSize | 每页数据量 | number | 10 |
| tableProps.pagination.total | 数据总量 | number | 0 |
| refresh | 刷新当前数据 | () => void | - |
| search.type | 搜索类型 | 'simple' \| 'advance' |'simple' |
| search.changeType | 触发搜索类型切换 | () => void | - |
| search.submit | 触发搜索 | () => void | - |
| search.reset | 重置搜索 | () => void | - |
| sorter | 排序数据 | antd sorter | {} |
| filters | 筛选数据 | antd filters | {} |
| refresh | 刷新当前数据 | () => void | - |
| search.type | 搜索类型 | 'simple' \ | 'advance'|'simple' |
| search.changeType | 触发搜索类型切换 | () => void | - |
| search.submit | 触发搜索 | () => void | - |
| search.reset | 重置搜索 | () => void | - |



### 参数

| 参数 | 说明 | 类型 | 默认值 |
|---------|---------------------------------------------------------------------------------------------------------------------------------------------------------------------------|--------------------|--------|
| service | 请求数据的函数,函数参数为 current, pageSize,及当前搜索表单数据,返回数据期望同 options.formatResult。当然你可以通过传过传 options.formatResult 参数,后置格式化返回结果 | (Params)=> Promise | - |
| service | 请求数据的函数,函数参数为 current, pageSize, sorter, filters,及当前搜索表单数据,返回数据期望同 options.formatResult。当然你可以通过传过传 options.formatResult 参数,后置格式化返回结果 | (Params)=> Promise | - |
| deps | 依赖数组,如果 deps 变化,会触发 reload | any[] | [] |
| options | 可选配置项,见 Options | - | - |

Expand Down
88 changes: 69 additions & 19 deletions src/useAntdTable/index.ts
Original file line number Diff line number Diff line change
@@ -1,8 +1,19 @@
import { WrappedFormUtils } from 'antd/lib/form/Form';
import { PaginationConfig } from 'antd/lib/pagination';
import { DependencyList, useEffect, useReducer, useRef, useCallback } from 'react';
import { useUpdateEffect } from 'react-use';
import { SorterResult } from 'antd/lib/table';
import {
DependencyList,
useCallback,
useEffect,
useReducer,
useRef,
useMemo,
Reducer,
} from 'react';
import useAsync from '../useAsync';
import useUpdateEffect from '../useUpdateEffect';

const isEqual = require('lodash.isequal');

interface UseAntdTableFormUtils extends WrappedFormUtils {
getFieldInstance?: (name: string) => {};
Expand All @@ -13,7 +24,11 @@ export interface ReturnValue<Item> {
table?: {
dataSource: Item[];
loading: boolean;
onChange: (e: PaginationConfig) => void;
onChange: (
pagination: PaginationConfig,
filters?: Record<keyof Item, string[]>,
sorter?: SorterResult<Item>,
) => void;
pagination: {
current: number;
pageSize: number;
Expand All @@ -23,13 +38,19 @@ export interface ReturnValue<Item> {
tableProps: {
dataSource: Item[];
loading: boolean;
onChange: (e: PaginationConfig) => void;
onChange: (
pagination: PaginationConfig,
filters?: Record<keyof Item, string[]>,
sorter?: SorterResult<Item>,
) => void;
pagination: {
current: number;
pageSize: number;
total: number;
};
};
sorter: SorterResult<Item>;
filters: Record<keyof Item, string[]>;
refresh: () => void;
search?: {
type: 'simple' | 'advance';
Expand Down Expand Up @@ -63,7 +84,7 @@ interface FormData {
[key: string]: any;
}

class UseTableInitState {
class UseTableInitState<Item> {
// 搜索类型,简单、高级
searchType: 'simple' | 'advance' = 'simple';

Expand All @@ -86,16 +107,17 @@ class UseTableInitState {
count = 0;

// 列表数据
data: any[] = [];
}
data: Item[] = [];

// 初始值
const initState = new UseTableInitState();
filters: Record<keyof Item, string[]> = {} as Record<keyof Item, string[]>;

sorter: SorterResult<Item> = {} as SorterResult<Item>;
}

// 缓存
const cacheData: { [key: string]: UseTableInitState } = {};
const cacheData: { [key: string]: any } = {};

const reducer = (state = initState, action: { type: string; payload?: {} }) => {
const reducer = <Item>(state: UseTableInitState<Item>, action: { type: string; payload?: {} }) => {
switch (action.type) {
case 'updateState':
return { ...state, ...action.payload };
Expand Down Expand Up @@ -123,13 +145,18 @@ function useAntdTable<Result, Item>(
? deps
: options || {}) as Options<Result, Item>;

const initState = useMemo(() => new UseTableInitState<Item>(), []);

const { defaultPageSize = 10, id, form, formatResult } = _options;
const [state, dispatch] = useReducer(reducer, { ...initState, pageSize: defaultPageSize });
const [state, dispatch] = useReducer<Reducer<UseTableInitState<Item>, any>>(reducer, {
...initState,
pageSize: defaultPageSize,
});

/* 临时记录切换前的表单数据 */
const tempFieldsValueRef = useRef<FormData>({});

const stateRef = useRef<UseTableInitState>(({} as unknown) as UseTableInitState);
const stateRef = useRef({} as UseTableInitState<Item>);
stateRef.current = state;
const { run, loading } = useAsync(fn, _deps, {
manual: true,
Expand Down Expand Up @@ -166,6 +193,8 @@ function useAntdTable<Result, Item>(
searchType: cache.searchType,
activeFormData: cache.activeFormData,
formData: cache.formData,
filters: cache.filters,
sorter: cache.sorter,
count: state.count + 1,
},
});
Expand Down Expand Up @@ -198,11 +227,19 @@ function useAntdTable<Result, Item>(
formattedData[key] = state.activeFormData[key];
}
});
run({

const params: any = {
current: state.current,
pageSize: state.pageSize,
...formattedData,
}).then(res => {
};
if (state.filters) {
params.filters = state.filters;
}
if (state.sorter) {
params.sorter = state.sorter;
}
run(params).then(res => {
const payload = formatResult ? formatResult(res) : res;
dispatch({
type: 'updateState',
Expand Down Expand Up @@ -303,15 +340,26 @@ function useAntdTable<Result, Item>(
});
}, [state.searchType]);

// 表格翻页
// 表格翻页 排序 筛选等
const changeTable = useCallback(
(e: PaginationConfig) => {
(
p: PaginationConfig,
f: Record<keyof Item, string[]> = {} as Record<keyof Item, string[]>,
s: SorterResult<Item> = {} as SorterResult<Item>,
) => {
/* 如果 filter,或者 sort 变化,就初始化 current */
const needReload =
!isEqual(f, state.filters) ||
s.field !== state.sorter.field ||
s.order !== state.sorter.order;
dispatch({
type: 'updateState',
payload: {
current: e.current,
pageSize: e.pageSize,
current: needReload ? 1 : p.current,
pageSize: p.pageSize,
count: state.count + 1,
filters: f,
sorter: s,
},
});
},
Expand Down Expand Up @@ -340,6 +388,8 @@ function useAntdTable<Result, Item>(
total: state.total,
},
},
sorter: state.sorter,
filters: state.filters,
refresh,
};
if (form) {
Expand Down
Loading

1 comment on commit 9092737

@vercel
Copy link

@vercel vercel bot commented on 9092737 Oct 24, 2019

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Please sign in to comment.