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

15 create new campaign page #31

Open
wants to merge 5 commits into
base: main
Choose a base branch
from
Open
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
26 changes: 26 additions & 0 deletions components/CreateNewCampaign/FileHeader.tsx
Original file line number Diff line number Diff line change
@@ -0,0 +1,26 @@
import { Button, Grid } from '@mui/material';
import React from 'react';
lihuicham marked this conversation as resolved.
Show resolved Hide resolved

export interface FileHeaderProps {
file: File;
onDelete: (file: File) => void;
}

export function FileHeader({ file, onDelete }: FileHeaderProps) {
return (
<Grid container sx={styledGrid}>
<Grid item>{file.name}</Grid>
<Grid item>
<Button size="small" onClick={() => onDelete(file)}>
Delete
</Button>
</Grid>
</Grid>
);
}

const styledGrid = {
display: 'flex',
justifyContent: 'space-between',
alignItems: 'center'
}
109 changes: 109 additions & 0 deletions components/CreateNewCampaign/MultipleFileUploadField.tsx
Original file line number Diff line number Diff line change
@@ -0,0 +1,109 @@
import { Grid, Button, Typography, Stack } from '@mui/material';
import { useField } from 'formik';
import React, { useCallback, useEffect, useState } from 'react';
import { FileError, FileRejection, useDropzone } from 'react-dropzone';
import SingleFileUploadWithProgress from './SingleFileUploadWithProgress';
import { UploadError } from './UploadError';

let currentId = 0;

function getNewId() {
return ++currentId;
}
Comment on lines +8 to +12
Copy link
Collaborator

Choose a reason for hiding this comment

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

not good to have a global variable. if we really need an id, put it as a state in the component.


export interface UploadableFile {
id: number;
file: File;
errors: FileError[];
url?: string;
}

const MultipleFileUploadField = ({ name }: { name: string }) => {
const [_, __, helpers] = useField(name);
const [files, setFiles] = useState<UploadableFile[]>([]);
const onDrop = useCallback((accFiles: File[], rejFiles: FileRejection[]) => {
const mappedAcc = accFiles.map((file) => ({ file, errors: [], id: getNewId() }));
const mappedRej = rejFiles.map((r) => ({ ...r, id: getNewId() }));
setFiles((curr) => [...curr, ...mappedAcc, ...mappedRej]);
Comment on lines +25 to +27
Copy link
Collaborator

Choose a reason for hiding this comment

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

think we can do away with id and just use the file's name as the key for ur map below, and we should not allow file with same name to be uploaded.
https://stackoverflow.com/questions/26296232/dropzone-prevent-uploading-of-duplicate-files

}, []);

useEffect(() => {
helpers.setValue(files);
}, [files]);

function onUpload(file: File, url: string) {
setFiles((curr) =>
curr.map((fw) => {
if (fw.file === file) {
return { ...fw, url };
}
return fw;
})
);
}

function onDelete(file: File) {
setFiles((curr) => curr.filter((fw) => fw.file !== file));
}

const { getRootProps, getInputProps } = useDropzone({
onDrop,
accept: {
'image/*': ['.png','.gif', '.jpeg', '.jpg', '.svg']
},
maxSize: 3000 * 1024, // 3MB
});

return (
<>
<Grid item>
<div {...getRootProps()}>
<input {...getInputProps()} />
<Stack sx={styledStack}>
<Button variant="contained" sx={styledButton}>Click to upload or drag and drop</Button>
<Typography sx={styledTypo}>PNG, GIF, JPEG, JPG or SVG files - max 3MB</Typography>
</Stack>

</div>
</Grid>

{files.map((fileWrapper) => (
<Grid item key={fileWrapper.id}>
{fileWrapper.errors.length ? (
<UploadError
file={fileWrapper.file}
errors={fileWrapper.errors}
onDelete={onDelete}
/>
) : (
<SingleFileUploadWithProgress
onDelete={onDelete}
onUpload={onUpload}
file={fileWrapper.file}
/>
)}
</Grid>
))}
</>
);
}

const styledStack = {
display: 'flex',
justifyContent: 'center',
}

const styledTypo = {
textAlign: 'center',
display: 'flex',
justifyContent: 'center',
alignItems: 'center',
fontSize: '15px',
marginTop: '20px',
}

const styledButton = {
padding: '20px',
}

export default MultipleFileUploadField;
73 changes: 73 additions & 0 deletions components/CreateNewCampaign/SingleFileUploadWithProgress.tsx
Original file line number Diff line number Diff line change
@@ -0,0 +1,73 @@
import { Grid, LinearProgress } from '@mui/material';
import React, { useEffect, useState } from 'react';
import { FileHeader } from './FileHeader';

export interface SingleFileUploadWithProgressProps {
file: File;
onDelete: (file: File) => void;
onUpload: (file: File, url: string) => void;
}

const SingleFileUploadWithProgress = ({
file,
onDelete,
onUpload,
}: SingleFileUploadWithProgressProps) => {
const [progress, setProgress] = useState(0);

useEffect(() => {
async function upload() {
const url = await uploadFile(file, setProgress);
onUpload(file, url);
}

upload();
}, []);

return (
<Grid item sx={styledGrid}>
<FileHeader file={file} onDelete={onDelete} />
<LinearProgress variant="determinate" value={progress} sx={styledProgress}/>
</Grid>
);
}

function uploadFile(file: File, onProgress: (percentage: number) => void) {
const url = 'https://api.cloudinary.com/v1_1/demo/image/upload';
const key = 'docs_upload_example_us_preset';

return new Promise<string>((res, rej) => {
const xhr = new XMLHttpRequest();
xhr.open('POST', url);

xhr.onload = () => {
const resp = JSON.parse(xhr.responseText);
res(resp.secure_url);
};
xhr.onerror = (evt) => rej(evt);
xhr.upload.onprogress = (event) => {
if (event.lengthComputable) {
const percentage = (event.loaded / event.total) * 100;
onProgress(Math.round(percentage));
}
};

const formData = new FormData();
formData.append('file', file);
formData.append('upload_preset', key);

xhr.send(formData);
});
}

const styledProgress = {
width: '100%',
}

const styledGrid = {
marginLeft: '20px',
marginRight: '20px',
marginTop: '10px'
}

export default SingleFileUploadWithProgress;
27 changes: 27 additions & 0 deletions components/CreateNewCampaign/UploadError.tsx
Original file line number Diff line number Diff line change
@@ -0,0 +1,27 @@
import {
LinearProgress,
Typography,
} from '@mui/material';
import React from 'react';
import { FileError } from 'react-dropzone';
import { FileHeader } from './FileHeader';

export interface UploadErrorProps {
file: File;
onDelete: (file: File) => void;
errors: FileError[];
}

export function UploadError({ file, onDelete, errors }: UploadErrorProps) {
return (
<React.Fragment>
<FileHeader file={file} onDelete={onDelete} />
<LinearProgress variant="buffer" value={100} color="error" />
{errors.map((error) => (
<div key={error.code}>
<Typography color="error">{error.message}</Typography>
</div>
))}
</React.Fragment>
);
}
41 changes: 41 additions & 0 deletions components/CreateNewCampaign/UploadMedia.tsx
Original file line number Diff line number Diff line change
@@ -0,0 +1,41 @@
import { Card, Grid } from '@mui/material';
import { Form, Formik } from 'formik';
import React from 'react';
import { array, object, string } from 'yup';
import MultipleFileUploadField from './MultipleFileUploadField';

const UploadMedia = () => {
return (
<Formik
initialValues={{ files: [] }}
validationSchema={object({
files: array(
object({
url: string().required(),
})
),
})}
onSubmit={(values) => {
console.log('values', values)
return new Promise((res) => setTimeout(res, 2000))
}}
>
{() => (
<Form>
<Card style={styledCard}>
<Grid container spacing={2} direction="column">
<MultipleFileUploadField name="files" />
</Grid>
</Card>
</Form>
)}
</Formik>
)
}

const styledCard = {
minHeight: '140px',
overflow: 'scroll',
}

export default UploadMedia
9 changes: 8 additions & 1 deletion package.json
Original file line number Diff line number Diff line change
Expand Up @@ -23,20 +23,27 @@
"@emotion/styled": "^11.10.4",
"@mui/icons-material": "^5.10.9",
"@mui/material": "^5.10.10",
"@mui/styles": "^5.11.0",
"@mui/x-date-pickers": "^5.0.11",
"@mui/x-date-pickers-pro": "^5.0.11",
"@mui/x-data-grid": "^5.17.14",
"@next/font": "^13.0.6",
"axios": "^1.1.2",
"classnames": "^2.3.2",
"eslint-plugin-unused-imports": "^2.0.0",
"formik": "^2.2.9",
"lodash": "^4.17.21",
"moment": "^2.29.4",
"next": "12.3.1",
"postcss": "^8.4.17",
"postcss-scss": "^4.0.5",
"react": "18.2.0",
"react-date-range": "^1.4.0",
"react-dom": "18.2.0",
"react-dropzone": "^14.2.3",
"sass": "^1.55.0",
"swr": "^1.3.0"
"swr": "^1.3.0",
"yup": "^0.32.11"
},
"devDependencies": {
"@types/lodash": "^4.14.191",
Expand Down
3 changes: 2 additions & 1 deletion pages/_app.tsx
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
import type { AppProps } from 'next/app'
import Layout from 'components/Layout'


function MyApp({ Component, pageProps }: AppProps) {
return (
<Layout>
Expand All @@ -9,4 +10,4 @@ function MyApp({ Component, pageProps }: AppProps) {
)
}

export default MyApp
export default MyApp
Loading