Skip to content

Commit

Permalink
Run prettier
Browse files Browse the repository at this point in the history
  • Loading branch information
hanbyul-here committed Aug 3, 2023
1 parent 91b5313 commit ffc91ee
Show file tree
Hide file tree
Showing 3 changed files with 137 additions and 83 deletions.
179 changes: 111 additions & 68 deletions app/scripts/components/common/table/index.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -3,14 +3,18 @@ import {
flexRender,
getCoreRowModel,
useReactTable,
ColumnDef,
ColumnDef,
getSortedRowModel,
SortingState,
Row,
Row
} from '@tanstack/react-table';
import { useVirtual } from 'react-virtual';
import { Sheet2JSONOpts } from 'xlsx';
import { CollecticonArrowLoop, CollecticonArrowDown, CollecticonArrowUp } from '@devseed-ui/collecticons';
import {
CollecticonArrowLoop,
CollecticonArrowDown,
CollecticonArrowUp
} from '@devseed-ui/collecticons';
import { Button } from '@devseed-ui/button';
import { PlaceHolderWrapper, TableWrapper, StyledTable } from './markup';
import useLoadFile from '$utils/use-load-file';
Expand All @@ -20,37 +24,42 @@ interface TablecomponentProps {
columnToSort?: string[];
}

export default function TableComponent({ dataPath, excelOption, columnToSort }:TablecomponentProps) {
export default function TableComponent({
dataPath,
excelOption,
columnToSort
}: TablecomponentProps) {
const tableContainerRef = useRef<HTMLDivElement>(null);
const {data, dataLoading, dataError} = useLoadFile(dataPath, excelOption);

const { data, dataLoading, dataError } = useLoadFile(dataPath, excelOption);
const [sorting, setSorting] = React.useState<SortingState>([]);
const dataLoaded = !dataLoading && !dataError;

const columns: ColumnDef<object>[] = data.length? (Object.keys(data[0])).map(key => {

return {
accessorKey: key,
enableSorting: (columnToSort?.includes(key))? true : false
};
}) : [];
const columns: ColumnDef<object>[] = data.length
? Object.keys(data[0]).map((key) => {
return {
accessorKey: key,
enableSorting: columnToSort?.includes(key) ? true : false
};
})
: [];

const table = useReactTable({
data,
columns,
data,
columns,
state: {
sorting,
sorting
},
onSortingChange: setSorting,
getCoreRowModel: getCoreRowModel(),
getSortedRowModel: getSortedRowModel()
});

const { rows } = table.getRowModel();
const rowVirtualizer = useVirtual({
parentRef: tableContainerRef,
size: rows.length,
overscan: 50,
overscan: 50
});
const { virtualItems: virtualRows, totalSize } = rowVirtualizer;

Expand All @@ -62,61 +71,95 @@ export default function TableComponent({ dataPath, excelOption, columnToSort }:T

return (
<>
{dataLoading && <PlaceHolderWrapper><p>Loading Data...</p></PlaceHolderWrapper>}
{dataError && <PlaceHolderWrapper> <p> Something went wrong while loading the data. Please try later. </p></PlaceHolderWrapper> }
{dataLoaded &&
<TableWrapper ref={tableContainerRef}>
<StyledTable>
<thead>
{table.getHeaderGroups().map(headerGroup => (
{dataLoading && (
<PlaceHolderWrapper>
<p>Loading Data...</p>
</PlaceHolderWrapper>
)}
{dataError && (
<PlaceHolderWrapper>
{' '}
<p>
{' '}
Something went wrong while loading the data. Please try later.{' '}
</p>
</PlaceHolderWrapper>
)}
{dataLoaded && (
<TableWrapper ref={tableContainerRef}>
<StyledTable>
<thead>
{table.getHeaderGroups().map((headerGroup) => (
<tr key={headerGroup.id}>
{headerGroup.headers.map(header => (
{headerGroup.headers.map((header) => (
<th key={header.id} colSpan={header.colSpan}>
{flexRender(
header.column.columnDef.header,
header.getContext())}
{header.column.getCanSort() &&
<Button onClick={header.column.getToggleSortingHandler()} variation='base-text'>
{header.column.getIsSorted() as string == 'asc' && <CollecticonArrowUp meaningful={true} title='Sorted in ascending order' />}
{header.column.getIsSorted() as string == 'desc' && <CollecticonArrowDown meaningful={true} title='Sorted in descending order' />}
{!header.column.getIsSorted() && <CollecticonArrowLoop meaningful={true} title={`Sort the rows with this column's value`} />}
</Button>}
{flexRender(
header.column.columnDef.header,
header.getContext()
)}
{header.column.getCanSort() && (
<Button
onClick={header.column.getToggleSortingHandler()}
variation='base-text'
>
{(header.column.getIsSorted() as string) == 'asc' && (
<CollecticonArrowUp
meaningful={true}
title='Sorted in ascending order'
/>
)}
{(header.column.getIsSorted() as string) ==
'desc' && (
<CollecticonArrowDown
meaningful={true}
title='Sorted in descending order'
/>
)}
{!header.column.getIsSorted() && (
<CollecticonArrowLoop
meaningful={true}
title={`Sort the rows with this column's value`}
/>
)}
</Button>
)}
</th>
))}
</tr>
))}
</thead>
<tbody>
{paddingTop > 0 && (
<tr>
<td style={{ height: `${paddingTop}px` }} />
</tr>
)}
{virtualRows.map(virtualRow => {
const row = rows[virtualRow.index] as Row<unknown>;
return (
<tr key={row.id}>
{row.getVisibleCells().map(cell => {
return (
<td key={cell.id}>
{flexRender(
cell.column.columnDef.cell,
cell.getContext()
)}
</td>
);
})}
</thead>
<tbody>
{paddingTop > 0 && (
<tr>
<td style={{ height: `${paddingTop}px` }} />
</tr>
);
})}
{paddingBottom > 0 && (
<tr>
<td style={{ height: `${paddingBottom}px` }} />
</tr>
)}
</tbody>
</StyledTable>
</TableWrapper>}
</>);
)}
{virtualRows.map((virtualRow) => {
const row = rows[virtualRow.index] as Row<unknown>;
return (
<tr key={row.id}>
{row.getVisibleCells().map((cell) => {
return (
<td key={cell.id}>
{flexRender(
cell.column.columnDef.cell,
cell.getContext()
)}
</td>
);
})}
</tr>
);
})}
{paddingBottom > 0 && (
<tr>
<td style={{ height: `${paddingBottom}px` }} />
</tr>
)}
</tbody>
</StyledTable>
</TableWrapper>
)}
</>
);
}

4 changes: 1 addition & 3 deletions app/scripts/components/common/table/markup.tsx
Original file line number Diff line number Diff line change
@@ -1,5 +1,4 @@

import styled from "styled-components";
import styled from 'styled-components';
import { themeVal } from '@devseed-ui/theme-provider';
import { variableGlsp } from '$styles/variable-utils';

Expand All @@ -11,7 +10,6 @@ export const PlaceHolderWrapper = styled.div`
align-items: center;
justify-content: center;
font-weight: bold;
`;

export const TableWrapper = styled.div`
Expand Down
37 changes: 25 additions & 12 deletions app/scripts/utils/use-load-file.ts
Original file line number Diff line number Diff line change
Expand Up @@ -2,43 +2,56 @@ import { useState, useEffect } from 'react';
import { Sheet2JSONOpts } from 'xlsx';
import axios from 'axios';

type FileExtension = 'xlsx' | 'xls'| 'json' | 'csv';
type FileExtension = 'xlsx' | 'xls' | 'json' | 'csv';

const useFileLoader = (fileName: string, excelOption?: Sheet2JSONOpts) => {
const [data, setData] = useState<object[]>([]);
const [dataLoading, setLoading] = useState<boolean>(false);
const [dataError, setError] = useState<boolean>(false);

useEffect(() => {

const controller = new AbortController();
const { signal } = controller;
const loadData = async () => {
setLoading(true);

try {
// eslint-disable-next-line fp/no-mutating-methods
const extension: FileExtension = fileName.split('.').pop()?.toLowerCase() as FileExtension;
const extension: FileExtension = fileName
.split('.')
.pop()
?.toLowerCase() as FileExtension;
switch (extension) {
case 'xlsx':
case 'xls': {
const { read, utils } = await import('xlsx');
const f = await (await axios.get(fileName, { responseType: 'blob', signal: signal }).then(response => response.data)).arrayBuffer();
const f = await (
await axios
.get(fileName, { responseType: 'blob', signal: signal })
.then((response) => response.data)
).arrayBuffer();
const wb = read(f); // parse the array buffer
const ws = wb.Sheets[wb.SheetNames[0]]; // get the first sheet by default
const data = utils.sheet_to_json(ws, excelOption) as object[]; // generate objects
setData(data);
setLoading(false);
break;
} case 'json': {
const { data } = await axios.get(fileName, { signal: signal });
}
case 'json': {
const { data } = await axios.get(fileName, { signal: signal });
setData(data);
setLoading(false);
break;
} case 'csv':{
}
case 'csv': {
const { csvParse } = await import('d3');
const { data } = await axios.get(fileName, { responseType: 'blob', signal: signal });
const csvData = await data.text().then(csvStr => csvParse(csvStr));
const { data } = await axios.get(fileName, {
responseType: 'blob',
signal: signal
});
const csvData = await data
.text()
.then((csvStr) => csvParse(csvStr));
setData(csvData);
setLoading(false);
break;
Expand All @@ -48,9 +61,9 @@ const useFileLoader = (fileName: string, excelOption?: Sheet2JSONOpts) => {
}
}
} catch (error) {
setData([]);
setLoading(false);
setError(true);
setData([]);
setLoading(false);
setError(true);
}
};

Expand Down

0 comments on commit ffc91ee

Please sign in to comment.