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

feature: Dropzone field to add images and videos for news cards #130

Draft
wants to merge 2 commits into
base: main
Choose a base branch
from
Draft
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
131 changes: 131 additions & 0 deletions app/components/common/form/DropzoneField.tsx
Original file line number Diff line number Diff line change
@@ -0,0 +1,131 @@
import React, { useCallback, useState } from 'react';
import Dropzone from 'react-dropzone';
import { Controller } from 'react-hook-form';

import CancelIcon from '@mui/icons-material/Cancel';
import CloudUploadIcon from '@mui/icons-material/CloudUpload';
import Box from '@mui/material/Box';
import { SxProps } from '@mui/material/styles';
import Typography from '@mui/material/Typography';

import { FormInputProps } from '@/common/formTypes';

interface DropzoneFieldProps extends FormInputProps {
onFileAdded: (fileUrl: string | null) => void;
}

export const DropzoneField = ({ name, control, onFileAdded }: DropzoneFieldProps) => {
const [previewFile, setPreviewFile] = useState<string | null>(null);
const [isVideo, setIsVideo] = useState<boolean>(false);

const onDrop = useCallback(
(acceptedFiles: File[]) => {
if (acceptedFiles.length > 0) {
const file = acceptedFiles[0];
const previewUrl = URL.createObjectURL(file);
setPreviewFile(previewUrl);
setIsVideo(file.type.startsWith('video/'));
onFileAdded(previewUrl);
}
onFileAdded(null);
},
[onFileAdded],
);

const onCancel = () => {
setPreviewFile(null);
onFileAdded(null);
};

return (
<>
<Controller
control={control}
name={name}
render={({ field: { onChange, onBlur } }) => (
<Dropzone
onDrop={(acceptedFiles: File[]) => {
const file = onDrop(acceptedFiles);
onChange(file);
}}
accept={{ 'image/*': [], 'video/*': [] }}
multiple={false}
>
{({ getRootProps, getInputProps, isDragActive }) => (
<Box
{...getRootProps()}
sx={{ ...dropzoneStyles, borderColor: isDragActive ? 'primary.main' : 'rgba(0, 0, 0, 0.2)' }}
>
<input {...getInputProps()} onBlur={onBlur} />
<Box sx={boxStyles}>
<CloudUploadIcon />
<Typography variant="body1" color="rgba(0, 0, 0, 0.56)">
Foto oder Video hochladen
</Typography>
</Box>
</Box>
)}
</Dropzone>
)}
/>
{previewFile && (
<Box sx={{ mt: 2, display: 'flex', flexWrap: 'wrap', gap: 2 }}>
<Box sx={previewStyles}>
{isVideo ? (
<video autoPlay loop style={{ maxWidth: '100%', maxHeight: '100%' }}>
<source src={previewFile} type="video/mp4" />
</video>
) : (
// eslint-disable-next-line @next/next/no-img-element
<img src={previewFile} alt="preview" style={{ maxWidth: '100%', maxHeight: '100%' }} />
)}
</Box>
<CancelIcon sx={closeIconStyle} onClick={onCancel} aria-label="close dialog" />
</Box>
)}
</>
);
};

const dropzoneStyles = {
border: '1px dashed',
borderRadius: '4px',
padding: '20px',
marginTop: '10px',
cursor: 'pointer',
height: '100px',
alignItems: 'center',
display: 'flex',
justifyContent: 'center',
color: 'rgba(0, 0, 0, 0.56)',
'&:hover': {
borderColor: 'black',
},
};

const boxStyles = {
display: 'flex',
alignItems: 'center',
justifyContent: 'center',
flexDirection: 'row',
gap: 1,
};

const previewStyles = {
width: '130px',
height: '80px',
border: '1px solid rgba(0, 0, 0, 0.1)',
display: 'flex',
alignItems: 'center',
justifyContent: 'center',
overflow: 'hidden',
backgroundColor: 'rgba(0, 0, 0, 0.1)',
};

const closeIconStyle: SxProps = {
cursor: 'pointer',
color: 'rgba(0, 0, 0, 0.56)',
marginLeft: '-26.5px',
marginTop: '-13.5px',
width: '20px',
};
59 changes: 8 additions & 51 deletions app/components/newsFeed/NewsFeedContainer.tsx
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
'use client';

import { PropsWithChildren, useEffect, useRef, useState } from 'react';
import { PropsWithChildren, useRef, useState } from 'react';

import FilterIcon from '@mui/icons-material/FilterAlt';
import Box from '@mui/material/Box';
Expand Down Expand Up @@ -30,8 +30,6 @@ export default function NewsFeedContainer({ children }: PropsWithChildren) {
const [drawerOpen, setDrawerOpen] = useState(false);
const { addEntry } = useNewsFeed();

const [formHeight, setFormHeight] = useState<number>(0);
const [contentOpacity, setContentOpacity] = useState(0);
const formRef = useRef<HTMLDivElement | null>(null);

async function handleTogglePostForm() {
Expand Down Expand Up @@ -71,33 +69,6 @@ export default function NewsFeedContainer({ children }: PropsWithChildren) {
setShowPostForm(false);
}

function scrollToFormWithOffset(offset: number) {
if (formRef.current) {
const elementPosition = formRef.current.getBoundingClientRect().top + window.pageYOffset;
const offsetPosition = elementPosition - offset;

window.scrollTo({
top: offsetPosition,
behavior: 'smooth',
});
}
}

useEffect(() => {
if (formRef.current) {
if (showPostForm) {
const targetHeight = formRef.current.scrollHeight;
setFormHeight(targetHeight);
setTimeout(() => setContentOpacity(1), 100);

scrollToFormWithOffset(100);
} else {
setContentOpacity(0);
setFormHeight(0);
}
}
}, [showPostForm]);

return (
<EditingContextProvider>
<Grid container spacing={2}>
Expand Down Expand Up @@ -137,28 +108,14 @@ export default function NewsFeedContainer({ children }: PropsWithChildren) {
</Box>
</Grid>
<Grid item xs={12} md={8} lg={9}>
<Box
ref={formRef}
sx={{
...addPostFormStyles(showPostForm),
height: `${formHeight}px`,
transition: 'height 0.3s ease-in-out',
}}
>
<Box ref={formRef} sx={addPostFormStyles(showPostForm)}>
{showPostForm && (
<Box
sx={{
opacity: contentOpacity,
transition: 'opacity 0.3s ease-in-out',
}}
>
<AddPostForm
onAddPost={handleAddPost}
onAddUpdate={handleAddUpdate}
projectOptions={projectOptions}
handleClose={() => setCancelDialogOpen(true)}
/>
</Box>
<AddPostForm
onAddPost={handleAddPost}
onAddUpdate={handleAddUpdate}
projectOptions={projectOptions}
handleClose={() => setCancelDialogOpen(true)}
/>
)}
</Box>
{children}
Expand Down
18 changes: 17 additions & 1 deletion app/components/newsPage/addPost/form/AddPostForm.tsx
Original file line number Diff line number Diff line change
@@ -1,5 +1,6 @@
'use client';

import { useState } from 'react';
import { SubmitHandler, useForm } from 'react-hook-form';
import { zodResolver } from '@hookform/resolvers/zod';
import { StatusCodes } from 'http-status-codes';
Expand All @@ -20,6 +21,7 @@ import { inputStyle } from '@/components/common/form/formStyle';
import InteractionButton, { InteractionType } from '@/components/common/InteractionButton';
import * as m from '@/src/paraglide/messages.js';

import { DropzoneField } from '../../../common/form/DropzoneField';
import { MultilineTextInputField } from '../../../common/form/MultilineTextInputField';
import { handleProjectUpdate } from '../../addUpdate/form/actions';

Expand All @@ -44,7 +46,7 @@ const defaultValues = {
anonymous: false,
};

const { PROJECT, CONTENT, ANONYMOUS } = formFieldNames;
const { PROJECT, CONTENT, ANONYMOUS, MEDIA } = formFieldNames;

interface AddUpdateFormProps {
onAddPost: (post: Post) => void;
Expand All @@ -56,6 +58,7 @@ interface AddUpdateFormProps {

export default function AddPostForm(props: AddUpdateFormProps) {
const { onAddPost, onAddUpdate, handleClose, defaultFormValues, projectOptions } = props;
const [fileUrl, setFileUrl] = useState<string | null>(null);

const { handleSubmit, control, formState } = useForm<FormData>({
defaultValues: defaultFormValues || defaultValues,
Expand All @@ -66,6 +69,11 @@ export default function AddPostForm(props: AddUpdateFormProps) {
const onSubmit: SubmitHandler<UpdateFormValidationSchema> = async (data) => {
const { content, project, anonymous } = data;

const formData = new FormData();
if (fileUrl) {
formData.append('media', fileUrl);
}

if (project && project.id) {
const response = await handleProjectUpdate({ comment: content, projectId: project.id, anonymous });
if (response.status === StatusCodes.OK && response.data) {
Expand Down Expand Up @@ -110,6 +118,14 @@ export default function AddPostForm(props: AddUpdateFormProps) {
/>
</form>

<DropzoneField
name={MEDIA}
control={control}
onFileAdded={(fileUrl) => {
setFileUrl(fileUrl);
}}
/>

<Stack spacing={2} direction={{ sm: 'column', md: 'row' }}>
{!defaultFormValues?.project && (
<AutocompleteDropdownField
Expand Down
1 change: 1 addition & 0 deletions app/components/newsPage/addPost/form/formFields.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,7 @@ const formFieldNames = {
CONTENT: 'content',
PROJECT: 'project',
ANONYMOUS: 'anonymous',
MEDIA: 'media',
};

export default formFieldNames;
Loading