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

useForm should handle this automatically. remove this when its fixed from antd u... #90

Open
abdelrahman-essawy opened this issue Jun 10, 2024 · 0 comments
Labels

Comments

@abdelrahman-essawy
Copy link
Member

// TODO: useForm should handle this automatically. remove this when its fixed from antd useForm.

import React, { useState } from 'react';

import { List, useTable } from '@refinedev/antd';
import { getDefaultFilter, HttpError } from '@refinedev/core';

import {
  AppstoreOutlined,
  SearchOutlined,
  UnorderedListOutlined,
} from '@ant-design/icons';
import { Form, Grid, Input, Radio, Space, Spin, Table } from 'antd';
import debounce from 'lodash/debounce';

import { ListTitleButton } from '@/components';
import { SerializedProductDto } from '@frontend/api-sdk';

type Props = React.PropsWithChildren;
type View = 'card' | 'table';

export const ProductsListPage: React.FC<Props> = ({ children }) => {
  const [view, setView] = useState<View>('table');
  const screens = Grid.useBreakpoint();

  const {
    tableProps,
    searchFormProps,
    setCurrent,
    setPageSize,
    filters,
    sorters,
    setFilters,
    tableQueryResult,
  } = useTable<SerializedProductDto, HttpError, { name: string }>({
    pagination: {
      pageSize: 12,
    },
    meta: {},
    sorters: {
      initial: [
        {
          field: 'createdAt',
          order: 'desc',
        },
      ],
    },
    // filters: {
    //   initial: [
    //     {
    //       field: 'name',
    //       value: undefined,
    //       operator: 'contains',
    //     },
    //     {
    //       field: 'email',
    //       value: undefined,
    //       operator: 'contains',
    //     },
    //     {
    //       field: 'company.id',
    //       value: undefined,
    //       operator: 'eq',
    //     },
    //     {
    //       field: 'jobTitle',
    //       value: undefined,
    //       operator: 'contains',
    //     },
    //     {
    //       field: 'status',
    //       value: undefined,
    //       operator: 'in',
    //     },
    //   ],
    // },
    onSearch: (values) => {
      return [
        {
          field: 'name',
          operator: 'contains',
          value: values.name,
        },
      ];
    },
  });

  const onViewChange = (value: View) => {
    setView(value);
    setFilters([], 'replace');
    // TODO: useForm should handle this automatically. remove this when its fixed from antd useForm.
    searchFormProps.form?.resetFields();
  };

  const onSearch = (e: React.ChangeEvent<HTMLInputElement>) => {
    searchFormProps?.onFinish?.({
      name: e.target.value,
    });
  };
  const debouncedOnChange = debounce(onSearch, 500);

  return (
    <div className="page-container">
      <List
        breadcrumb={false}
        headerButtons={() => {
          return (
            <Space
              style={{
                marginTop: screens.xs ? '1.6rem' : undefined,
              }}
            >
              <Form
                {...searchFormProps}
                initialValues={{
                  name: getDefaultFilter('name', filters, 'contains'),
                }}
                layout="inline"
              >
                <Form.Item name="name" noStyle>
                  <Input
                    size="large"
                    // @ts-expect-error Ant Design Icon's v5.0.1 has an issue with @types/react@^18.2.66
                    prefix={<SearchOutlined className="anticon tertiary" />}
                    suffix={
                      <Spin
                        size="small"
                        spinning={tableQueryResult.isFetching}
                      />
                    }
                    placeholder="Search by name"
                    onChange={debouncedOnChange}
                  />
                </Form.Item>
              </Form>
              {!screens.xs ? (
                <Radio.Group
                  size="large"
                  value={view}
                  onChange={(e) => onViewChange(e.target.value)}
                >
                  <Radio.Button value="table">
                    {/* @ts-expect-error Ant Design Icon's v5.0.1 has an issue with @types/react@^18.2.66 */}
                    <UnorderedListOutlined />
                  </Radio.Button>
                  <Radio.Button value="card">
                    {/* @ts-expect-error Ant Design Icon's v5.0.1 has an issue with @types/react@^18.2.66 */}
                    <AppstoreOutlined />
                  </Radio.Button>
                </Radio.Group>
              ) : null}
            </Space>
          );
        }}
        contentProps={{
          style: {
            marginTop: '28px',
          },
        }}
        title={
          <ListTitleButton toPath="contacts" buttonText="Add new contact" />
        }
      >
        {/*{screens.xs || view === 'card' ? (*/}
        {/*  <CardView*/}
        {/*    tableProps={tableProps}*/}
        {/*    setPageSize={setPageSize}*/}
        {/*    setCurrent={setCurrent}*/}
        {/*  />*/}
        {/*) : (*/}
        <Table
          {...tableProps}
          rowKey="_id"
          columns={[
            {
              // image
              title: 'logo',
              dataIndex: 'logo',
              render: (_, value) => {
                const defaultSrc =
                  'https://www.brandi.com.ar/wp-content/uploads/2020/08/a-no-foto.png';
                const firstImage = value.productPictures[0];
                const src = firstImage
                  ? `https://devapi.point24h.com/api/thumbs/${firstImage}/[email protected]`
                  : defaultSrc;
                return (
                  <img
                    src={src}
                    alt="logo"
                    style={{ width: '50px', height: '50px' }}
                  />
                );
              },
            },
            {
              title: 'UPC',
              dataIndex: 'upc',
              sorter: true,
            },
            {
              title: 'Price',
              dataIndex: 'price',
              sorter: true,
            },
            {
              title: 'Name',
              dataIndex: ['name', 'en'],
              sorter: true,
              render: (_, record) => record.name.en ?? 'N/A',
            },
            {
              title: 'Supplier',
              dataIndex: ['supplier', 'name'],
              sorter: true,
              render: (_, record) => record.description.en ?? 'N/A',
            },
            {
              title: 'Category',
              dataIndex: ['category', 'name'],
              sorter: true,
              render: (_, record) => record.category ?? 'N/A',
            },
            {
              title: 'Brand',
              dataIndex: ['brand', 'name'],
              sorter: true,
              render: (_, record) => record.brand ?? 'N/A',
            },
          ]}
          scroll={{ x: true }}
          sticky
          pagination={{
            ...tableProps.pagination,
            showSizeChanger: true,
            showTotal: (total) => `Total ${total} items`,
          }}
        />

        {/*)}*/}
        {children}
      </List>
    </div>
  );
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
Projects
None yet
Development

No branches or pull requests

1 participant