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

Allow import from CSV #72

Merged
merged 1 commit into from
Oct 26, 2023
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
25 changes: 25 additions & 0 deletions apps/abclaunch/src/components/ImportCSVButton.tsx
Original file line number Diff line number Diff line change
@@ -0,0 +1,25 @@
import { Button, Input } from "@chakra-ui/react"
import { useRef } from "react"
import { readFile, removeCSVHeaders } from "../utils/csv-utils"

export default function ImportButton ({ onImport, children, ...props }: { onImport: (csv: string) => void, children: React.ReactNode, [x: string]: any }) {
const fileInput = useRef<HTMLInputElement>(null)
async function handleChange (file: File) {
const csv = removeCSVHeaders(await readFile(file))
onImport(csv)
}
const handleClick = () => fileInput.current && fileInput.current.click()
return (
<>
<Button onClick={handleClick} {...props}>{children}</Button>
<Input
ref={fileInput}
sx={{ display: 'none' }}
type="file"
accept=".csv"
onClick={e => ((e.target as HTMLInputElement).value = '')}
onChange={e => e.target.files && handleChange(e.target.files[0])}
/>
</>
)
}
35 changes: 33 additions & 2 deletions apps/abclaunch/src/components/dao-steps/ConfigureToken.tsx
Original file line number Diff line number Diff line change
@@ -1,9 +1,11 @@
import { Divider, Button, FormControl, FormLabel, HStack, InputGroup, InputRightElement, Text, VStack, Tooltip } from "@chakra-ui/react";
import { InfoOutlineIcon, DeleteIcon, AddIcon } from '@chakra-ui/icons';
import { InfoOutlineIcon, DeleteIcon, AttachmentIcon, AddIcon } from '@chakra-ui/icons';
import React from 'react';
import { useRecoilState, useRecoilValue } from "recoil";
import { newDaoTokenState, newDaoTokenSupplyState } from "../../recoil";
import { isAddress } from "viem";
import ImportCSVButton from "../ImportCSVButton";
import { csvStringToArray } from "../../utils/csv-utils";
import { formatUnits, isAddress, parseUnits } from "viem";
import { Input, NumberInput, NumberInputField } from "commons-ui/src/components/Input";

export default function ConfigureToken() {
Expand Down Expand Up @@ -45,6 +47,28 @@ export default function ConfigureToken() {
});
}

function handlePaste(e: React.ClipboardEvent<HTMLInputElement>) {
const tokenHolders = tokenSettings.tokenHolders;
const isEmpty = tokenHolders.length === 1 && tokenHolders[0][0] === '' && tokenHolders[0][1] === ''
if (isEmpty) { // Only paste a CSV on a blank state, otherwise paste normally
e.preventDefault();
handleImportCSV(e.clipboardData.getData('Text'));
}
}

function handleImportCSV(csv: string) {
if (!csv) return;
const array = csvStringToArray(csv);
const processAddress = (address: string) => address.trim() || '';
const processBalance = (balance: string) => !isNaN(Number(balance)) && formatUnits(parseUnits(balance, 18), 18) || '';
const tokenHolders: [string, string][] = array.map(([address, balance]) => [processAddress(address), processBalance(balance)]);
setTokenSettings(settings => ({ ...settings, tokenHolders }));
}

function deleteAll() {
setTokenSettings(settings => ({ ...settings, tokenHolders: [['', '']] }));
}

return (
<VStack spacing={4} pt="75px" mx="100px">
<Text fontFamily="VictorSerifTrial" fontSize="72px" color="brand.900">Token</Text>
Expand Down Expand Up @@ -117,6 +141,7 @@ export default function ConfigureToken() {
onChange={(e: React.ChangeEvent<HTMLInputElement>) =>
handleHolderChange(i, e.target.value, true)
}
onPaste={handlePaste}
/>
<InputRightElement onClick={() => handleRemoveHolder(i)} >
<DeleteIcon />
Expand Down Expand Up @@ -145,6 +170,12 @@ export default function ConfigureToken() {
<Button leftIcon={<AddIcon />} onClick={() => handleAddEmptyHolder()}>
Add more
</Button>
<ImportCSVButton leftIcon={<AttachmentIcon />} onImport={handleImportCSV}>
Import CSV
</ImportCSVButton>
<Button variant="outline" leftIcon={<DeleteIcon />} onClick={() => deleteAll()}>
Delete all
</Button>
</HStack>
</VStack>
<Divider paddingTop="24px"
Expand Down
49 changes: 49 additions & 0 deletions apps/abclaunch/src/utils/csv-utils.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,49 @@
export function csvStringToArray(strData: string, strDelimiter: string = '\t'): string[][] {
const objPattern = new RegExp(
'(\\' +
strDelimiter +
'|\\r?\\n|\\r|^)' +
'(?:"([^"]*(?:""[^"]*)*)"|' +
'([^"\\' +
strDelimiter +
'\\r\\n]*))',
'gi'
)

let arrData: string[][] = [[]]
let arrMatches: RegExpExecArray | null = null

while ((arrMatches = objPattern.exec(strData.trim()))) {
const strMatchedDelimiter: string = arrMatches[1]
if (strMatchedDelimiter.length && strMatchedDelimiter !== strDelimiter) {
arrData.push([])
}

let strMatchedValue: string

if (arrMatches[2]) {
strMatchedValue = arrMatches[2].replace(new RegExp('""', 'g'), '"')
} else {
strMatchedValue = arrMatches[3]
}

arrData[arrData.length - 1].push(strMatchedValue)
}

return arrData
}

export function readFile(file: File): Promise<string> {
return new Promise((resolve, reject) => {
const fr = new FileReader()
fr.onload = () => {
resolve(fr.result as string) // Ensure the result is treated as a string
}
fr.onerror = (error) => {
reject(error) // Handle the error event
}
fr.readAsText(file)
})
}

export const removeCSVHeaders = (text: string): string => text.substring(text.indexOf('\n') + 1)