File size: 12,405 Bytes
f46e223
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
import {
  BranchesOutlined, GlobalOutlined,
  HomeOutlined,
  ProfileOutlined,
  TeamOutlined
} from '@ant-design/icons'
import { Button, Col, Descriptions, Input, Layout, Menu, Modal, Row, Table, TablePaginationConfig, Typography } from 'antd'
import { FilterValue, SorterResult, TableCurrentDataSource } from 'antd/lib/table/interface'
import moment from 'moment'
import prettyBytes from 'pretty-bytes'
import QueryString from 'qs'
import React, { useEffect, useState } from 'react'
import { useThemeSwitcher } from 'react-css-theme-switcher'
import { useHistory } from 'react-router-dom'
import useSWR from 'swr'
import { fetcher } from '../../../utils/Fetcher'
import Footer from '../../components/Footer'
import Navbar from '../../components/Navbar'
import Breadcrumb from '../../dashboard/components/Breadcrumb'
import Icon from './Icon'

interface Props {
  me: any,
  data: any
}

const TableFiles: React.FC<Props> = ({ me, data }) => {
  const history = useHistory()
  const [dataChanges, setDataChanges] = useState<{
    pagination?: TablePaginationConfig,
    filters?: Record<string, FilterValue | null>,
    sorter?: SorterResult<any> | SorterResult<any>[]
  }>()
  const { currentTheme } = useThemeSwitcher()
  const [parent, setParent] = useState<Record<string, any> | null>()
  const [breadcrumbs, setBreadcrumbs] = useState<any[]>([data?.file || { id: null, name: <><HomeOutlined /></> }])
  const [scrollTop, setScrollTop] = useState<number>(0)
  const [keyword, setKeyword] = useState<string>()
  const [filesData, setFilesData] = useState<any>()
  const [params, setParams] = useState<any>()
  const [loading, setLoading] = useState<boolean>(false)
  const [showDetails, setShowDetails] = useState<any>()
  const { data: filesParts } = useSWR(showDetails ? `/files?name.like=${showDetails.name.replace(/\.part0*\d+$/, '')}&user_id=${showDetails.user_id}${me?.user.id !== showDetails.user_id ? '&shared=1' : ''}&parent_id${showDetails.parent_id ? `=${showDetails.parent_id}` : '=null'}` : null, fetcher)
  const [popup, setPopup] = useState<{ visible: boolean, x?: number, y?: number, row?: any }>()
  const { data: files, mutate: _refetch } = useSWR(data?.file.type === 'folder' && data?.file.sharing_options?.includes('*') && params ? `/files?exclude_parts=1&${QueryString.stringify(params)}` : null, fetcher, { onSuccess: files => {
    setLoading(false)
    if (files?.files) {
      let newData: any[] = []
      if (!params?.offset || !dataChanges?.pagination?.current || dataChanges?.pagination?.current === 1) {
        newData = files.files.map((file: any) => ({ ...file, key: file.id }))
      } else {
        newData = [
          ...filesData.map(row => files.files.find((file: any) => file.id === row.id) || row).map(file => ({ ...file, key: file.id })),
          ...files.files.map((file: any) => ({ ...file, key: file.id }))
        ].reduce((res, row) => [
          ...res, !res.filter(Boolean).find((r: any) => r.id === row.id) ? row : null
        ], []).filter(Boolean)
      }

      setFilesData(newData)
    }
  } })

  const PAGE_SIZE = 10

  const fetch = (pagination?: TablePaginationConfig, filters?: Record<string, FilterValue | null>, sorter?: SorterResult<any> | SorterResult<any>[], actions?: TableCurrentDataSource<any>) => {
    setLoading(true)
    setParams({
      // ...parent?.id ? { parent_id: parent.link_id || parent.id } : { 'parent_id.is': 'null' },
      parent_id: parent?.link_id || parent?.id || data?.file.id,
      ...keyword ? { 'name.ilike': `%${keyword}%` } : {},
      shared: 1,
      limit: PAGE_SIZE,
      offset: pagination?.current === 1 || actions?.action || keyword && params?.offset ? 0 : filesData?.length,
      ...Object.keys(filters || {})?.reduce((res, key: string) => {
        if (!filters) return res
        if (key === 'type' && filters[key]?.length) {
          return { ...res, [`${key}.in`]: `(${filters[key]?.map(val => `'${val}'`).join(',')})` }
        }
        return { ...res, [key]: filters[key]?.[0] }
      }, {}),
      ...(sorter as SorterResult<any>)?.order ? {
        sort: `${(sorter as SorterResult<any>).column?.dataIndex}:${(sorter as SorterResult<any>).order?.replace(/end$/gi, '')}`
      } : { sort: 'created_at:desc' },
      t: new Date().getTime()
    })
  }

  const onChange = async (pagination?: TablePaginationConfig, filters?: Record<string, FilterValue | null>, sorter?: SorterResult<any> | SorterResult<any>[], actions?: TableCurrentDataSource<any>) => {
    setDataChanges({ pagination, filters, sorter })
    fetch(pagination, filters, sorter, actions)
  }

  const onRowClick = (row: any) => {
    if (row.type === 'folder') {
      setParent(row)
      setBreadcrumbs([...breadcrumbs, row])

      const searchParams = new URLSearchParams(window.location.search)
      searchParams.set('parent', row.id)
      return history.push(`${location.pathname}?${searchParams.toString()}`)
    } else {
      return history.push(`/view/${row.id}`)
    }
  }

  useEffect(() => {
    const nextPage = () => {
      setScrollTop(document.body.scrollTop)
    }
    nextPage()
    document.body.addEventListener('scroll', nextPage)
  }, [])

  useEffect(() => {
    const footer = document.querySelector('.ant-layout-footer')
    if (scrollTop >= document.body.scrollHeight - document.body.clientHeight - (footer?.clientHeight || 0) && files?.files.length >= PAGE_SIZE) {
      onChange({ ...dataChanges?.pagination, current: (dataChanges?.pagination?.current || 1) + 1 }, dataChanges?.filters, dataChanges?.sorter)
    }
  }, [scrollTop])

  useEffect(() => {
    if (parent !== undefined || keyword !== undefined) {
      onChange({ ...dataChanges?.pagination, current: 1 }, dataChanges?.filters, dataChanges?.sorter)
      setScrollTop(0)
    }
  }, [keyword, parent])

  const ContextMenu = () => {
    const baseProps = {
      style: { margin: 0 }
    }
    if (!popup?.visible) return <></>
    if (popup?.row) {
      return <Menu style={{ zIndex: 1, position: 'absolute', left: `${popup?.x}px`, top: `${popup?.y}px`, boxShadow: '0 3px 6px -4px rgba(0, 0, 0, 0.12), 0 6px 16px 0 rgba(0, 0, 0, 0.08), 0 9px 28px 8px rgba(0, 0, 0, 0.05)' }}>
        <Menu.Item {...baseProps}
          icon={<ProfileOutlined />}
          key="details"
          onClick={() => setShowDetails(popup?.row)}>Details</Menu.Item>
      </Menu>
    }
    return <></>
  }

  return <Layout>
    <Layout.Content>
      <Navbar user={me?.user} />
      <Row style={{ minHeight: '80vh', marginBottom: '100px', padding: '20px 12px 0' }}>
        <Col lg={{ span: 18, offset: 3 }} md={{ span: 20, offset: 2 }} span={24}>
          <Typography.Paragraph style={{ float: 'left' }}>
            <Breadcrumb dataSource={[breadcrumbs, setBreadcrumbs]} dataParent={[parent, setParent]} />
          </Typography.Paragraph>
          <Typography.Paragraph style={{ textAlign: 'right' }}>
            <Input.Search style={{ width: '210px' }} className="input-search-round" placeholder="Search..." enterButton onSearch={setKeyword} allowClear />
          </Typography.Paragraph>
          <Table
            className="tableFiles"
            loading={!data || loading}
            showSorterTooltip={false}
            dataSource={filesData}
            columns={[
              {
                title: 'File',
                dataIndex: 'name',
                key: 'type',
                sorter: true,
                sortOrder: (dataChanges?.sorter as SorterResult<any>)?.column?.dataIndex === 'name' ? (dataChanges?.sorter as SorterResult<any>).order : undefined,
                filters: [
                  {
                    text: 'Folder',
                    value: 'folder'
                  },
                  {
                    text: 'Image',
                    value: 'image'
                  },
                  {
                    text: 'Video',
                    value: 'video'
                  },
                  {
                    text: 'Audio',
                    value: 'audio'
                  },
                  {
                    text: 'Document',
                    value: 'document'
                  },
                  {
                    text: 'Unknown',
                    value: 'unknown'
                  }
                ],
                ellipsis: true,
                onCell: (row: any) => ({
                  onClick: () => onRowClick(row)
                }),
                render: (_: any, row: any) => {
                  let type: any
                  if (row.sharing_options?.includes('*')) {
                    type = <GlobalOutlined />
                  } else if (row.sharing_options?.length) {
                    type = <TeamOutlined />
                  }

                  return <Button type="link" block style={{ textAlign: 'left', padding: 0, color: currentTheme === 'dark' ? '#FFFFFFD9' : '#000000D9' }}>
                    {row.link_id ? <BranchesOutlined /> : '' } {type} <Icon type={row.type} /> {row.name.replace(/\.part0*\d+$/, '')}
                  </Button>
                }
              },
              {
                title: 'Size',
                dataIndex: 'size',
                key: 'size',
                sorter: true,
                sortOrder: (dataChanges?.sorter as SorterResult<any>)?.column?.key === 'size' ? (dataChanges?.sorter as SorterResult<any>).order : undefined,
                responsive: ['md'],
                width: 100,
                align: 'center',
                render: (value: any) => {
                  if (Number(value) === 2_000_000_000) {
                    return '> 2 GB'
                  }
                  return value ? prettyBytes(Number(value)) : '-'
                }
              },
              {
                title: 'Uploaded At',
                dataIndex: 'uploaded_at',
                key: 'uploaded_at',
                sorter: true,
                sortOrder: (dataChanges?.sorter as SorterResult<any>)?.column?.key === 'uploaded_at' ? (dataChanges?.sorter as SorterResult<any>).order : undefined,
                responsive: ['md'],
                width: 250,
                align: 'center',
                render: (value: any, row: any) => row.upload_progress !== null ? <>Uploading {Number((row.upload_progress * 100).toFixed(2))}%</> : moment(value).local().format('llll')
              }
            ]}
            onChange={onChange}
            pagination={false}
            scroll={{ x: 330 }}
            onRow={(row, index) => ({
              index,
              onContextMenu: e => {
                // if (tab !== 'mine') return

                e.preventDefault()
                if (!popup?.visible) {
                  document.addEventListener('click', function onClickOutside() {
                    setPopup({ visible: false })
                    document.removeEventListener('click', onClickOutside)
                  })
                }
                // const parent = document.querySelector('.ant-col-24.ant-col-md-20.ant-col-md-offset-2')
                setPopup({
                  row,
                  visible: true,
                  x: e.clientX,
                  y: e.clientY
                  // x: e.clientX - (parent?.getBoundingClientRect().left || 0),
                  // y: e.clientY - (parent?.getBoundingClientRect().top || 0)
                })
              }
            })} />
        </Col>
      </Row>
    </Layout.Content>
    <Footer me={me} />
    <ContextMenu />
    <Modal title={<Typography.Text ellipsis><Icon type={showDetails?.type} /> {showDetails?.name.replace(/\.part0*\d+$/, '')}</Typography.Text>}
      visible={Boolean(showDetails)}
      onCancel={() => setShowDetails(undefined)}
      okText="View"
      onOk={() => onRowClick(showDetails)}
      cancelButtonProps={{ shape: 'round' }}
      okButtonProps={{ shape: 'round' }}>
      <Descriptions column={1}>
        <Descriptions.Item label="Size">
          {filesParts?.length ? prettyBytes(filesParts?.files.reduce((res: number, file: any) => res + Number(file.size), 0)) + ` (${filesParts?.length} parts)` : showDetails?.size && prettyBytes(Number(showDetails?.size || 0))}
        </Descriptions.Item>
        <Descriptions.Item label="Uploaded At">{moment(showDetails?.uploaded_at).local().format('lll')}</Descriptions.Item>
      </Descriptions>
    </Modal>
  </Layout>
}

export default TableFiles