Skip to content

Commit

Permalink
Separate logic from UI (#63)
Browse files Browse the repository at this point in the history
  • Loading branch information
Ryczko authored Mar 14, 2023
1 parent fd2fcd0 commit 6884298
Show file tree
Hide file tree
Showing 53 changed files with 533 additions and 395 deletions.
File renamed without changes
File renamed without changes
File renamed without changes
File renamed without changes
File renamed without changes
File renamed without changes
8 changes: 8 additions & 0 deletions src/features/application/context.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,8 @@
import { useDefinedContext } from './../../shared/context/useDefinedContext';
import { createContext } from 'react';
import { ApplicationManager } from './manager';


export const ApplicationContext = createContext<ApplicationManager | undefined>(undefined);

export const useApplicationContext = (): ApplicationManager => useDefinedContext(ApplicationContext);
19 changes: 19 additions & 0 deletions src/features/application/manager.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,19 @@
import { User } from 'firebase/auth';
import { useAuthState } from 'react-firebase-hooks/auth';
import { auth } from 'src/firebase';

export interface ApplicationManager {
user: User;
loading: boolean;
error: Error;
}

export const useApplicationManager = (): ApplicationManager => {
const [user, loading, error] = useAuthState(auth);

return {
user,
loading,
error,
};
};
Empty file added src/features/settings/.gitkeep
Empty file.
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,6 @@ import clsx from 'clsx';
import BarChart, { BarChartData } from '../BarChart/BarChart';
import DataCard from '../DataCard/DataCard';


interface AnswerHeaderProps {
totalVotes: number;
startDate: string;
Expand Down
File renamed without changes.
File renamed without changes.
File renamed without changes.
File renamed without changes.
Original file line number Diff line number Diff line change
@@ -1,9 +1,9 @@
import { useRef, useState } from 'react';
import { useCloseComponent } from '../../hooks/useCloseComponent';
import { useCloseComponent } from '../../../../shared/hooks/useCloseComponent';

import dynamic from 'next/dynamic';
import Emoji from '../Emoji/Emoji';
import Loader from '../Loader/Loader';
import Loader from '../../../../shared/components/Loader/Loader';
const Picker = dynamic(() => import('emoji-picker-react'), {
ssr: false,
loading: () => <Loader isLoading={true} />,
Expand Down
File renamed without changes.
Original file line number Diff line number Diff line change
Expand Up @@ -2,13 +2,17 @@ import { useState, Fragment } from 'react';
import { LinkIcon, TrashIcon } from '@heroicons/react/outline';

import toast from 'react-hot-toast';
import useCopyToClipboard from '../../hooks/useCopyToClipboard';
import useCopyToClipboard from '../../../../shared/hooks/useCopyToClipboard';
import { Dialog, Transition } from '@headlessui/react';
import { db } from '../../firebase';
import { db } from '../../../../firebase';
import { deleteDoc, doc } from 'firebase/firestore';
import { useRouter } from 'next/router';
import Button, { ButtonVariant } from '../Button/Button';
import IconButton, { IconButtonVariant } from '../IconButton/IconButton';
import Button, {
ButtonVariant,
} from '../../../../shared/components/Button/Button';
import IconButton, {
IconButtonVariant,
} from '../../../../shared/components/IconButton/IconButton';

type Props = {
question: string;
Expand Down
6 changes: 6 additions & 0 deletions src/features/surveys/interfaces/AnswerData.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,6 @@
export interface AnswerData {
id: string;
answerDate: string;
selectedIcon: string;
answer: string;
}
92 changes: 92 additions & 0 deletions src/features/surveys/managers/createSurveyManager.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,92 @@
import { addDoc, collection } from 'firebase/firestore';
import { useRouter } from 'next/router';
import { useState, useEffect } from 'react';
import toast from 'react-hot-toast';
import { useApplicationContext } from 'src/features/application/context';
import { db } from 'src/firebase';
import useCopyToClipboard from 'src/shared/hooks/useCopyToClipboard';

export const useCreateSurveyManager = () => {
const [title, setTitle] = useState('');
const [pack, setPack] = useState(['😃', '🙂', '🙁', '😡']);

const { user } = useApplicationContext();
const [buttonDisable, setButtonDisable] = useState(false);

const router = useRouter();
const [, copy] = useCopyToClipboard();

const handleChangeTitle = (e: any) => {
setTitle(e.target.value);
};

const handleEmotePick = (index: number, newEmote: string) => {
setPack((oldPack) => {
oldPack.splice(index, 1, newEmote);
return oldPack;
});
};

const [startDate, setStartDate] = useState<Date | null>(new Date());
const [endDate, setEndDate] = useState<Date | null>(
new Date(new Date().setDate(new Date().getDate() + 1)) as any
);

useEffect(() => {
if (startDate! > endDate!) {
setStartDate(endDate);
setEndDate(startDate);
}
}, [startDate, endDate]);

const createSurvey = async () => {
setButtonDisable(true);
try {
const newSurvey = await addDoc(collection(db, 'surveys'), {
title,
pack,
creatorId: user?.uid,
startDate,
endDate,
});
const domain =
window.location.hostname === 'localhost' ? 'http://' : 'https://';
const link = `${domain}${window.location.host}/survey/${newSurvey.id}`;
copy(link);
router.push(`/survey/answer/${newSurvey.id}`);

toast.success('Survey created and link copied to clipboard');
} catch (error) {
toast.error('Survey creation failed');
}
setButtonDisable(false);
};

const filterPassedTime = (time: string | number | Date) => {
const currentDate = new Date();
const selectedDate = new Date(time);

return currentDate.getTime() < selectedDate.getTime();
};

const filterPassedSelectedTime = (time: string | number | Date) => {
const currentDate = startDate;
const selectedDate = new Date(time);

return currentDate!.getTime() < selectedDate.getTime();
};
return {
title,
pack,
handleChangeTitle,
startDate,
setStartDate,
endDate,
filterPassedTime,
setEndDate,
filterPassedSelectedTime,
handleEmotePick,
createSurvey,
buttonDisable,
};
};
99 changes: 99 additions & 0 deletions src/features/surveys/managers/surveyAnswerManager.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,99 @@
import { getDoc, doc, addDoc, collection } from 'firebase/firestore';
import { useRouter } from 'next/router';
import { useState, useEffect } from 'react';
import toast from 'react-hot-toast';
import { db } from 'src/firebase';

export const useSurveyAnswerManager = () => {
const router = useRouter();

const { surveyId } = router.query as { surveyId: string };

const [question, setQuestion] = useState('');
const [answer, setAnswer] = useState('');
const [icons, setIcons] = useState<string[]>([]);
const [selectedIcon, setSelectedIcon] = useState<string | null>('');
const [buttonDisable, setButtonDisable] = useState(false);
const [isLoading, setIsLoading] = useState(true);

useEffect(() => {
if (surveyId) {
getSurveyData();
}
}, [surveyId]);

const getSurveyData = async () => {
const surveyData = await getDoc(doc(db, 'surveys', surveyId!));
if (!surveyData.exists()) {
router.replace('/');
return;
}

if (
surveyData.data()?.startDate.toDate().toISOString() >
new Date().toISOString()
) {
toast.error('Survey is not opened yet');
router.replace('/');
return;
}

if (
surveyData.data()?.endDate.toDate().toISOString() <
new Date().toISOString()
) {
toast.error('Survey is closed');
router.replace('/');
return;
}

setQuestion(surveyData.data()?.title);
setIcons(surveyData.data()?.pack);
setIsLoading(false);
};

const handleIconClick = (e: React.MouseEvent<HTMLButtonElement>) => {
const target = e.target as HTMLElement;
setSelectedIcon(target.textContent);
};

const handleSave = async () => {
setButtonDisable(true);
setIsLoading(true);

try {
if (!surveyId) {
toast.error('Survey ID not found');
throw new Error('Survey ID not found');
}
await addDoc(collection(db, 'surveys', surveyId, 'answers'), {
selectedIcon,
answer,
answerDate: new Date(),
});
toast.success('The reply has been sent');
router.replace('/');
} catch (error) {
toast.error('Error occured');
} finally {
setButtonDisable(false);
setIsLoading(false);
}
};

const handleInputAnswer = (e: React.ChangeEvent<HTMLTextAreaElement>) => {
setAnswer(e.target.value);
};

return {
isLoading,
question,
icons,
selectedIcon,
handleIconClick,
answer,
handleInputAnswer,
buttonDisable,
handleSave,
};
};
34 changes: 34 additions & 0 deletions src/features/surveys/managers/surveyListManager.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,34 @@
import {
collection,
DocumentData,
orderBy,
query,
Query,
where,
} from 'firebase/firestore';
import { useEffect, useState } from 'react';
import { useCollection } from 'react-firebase-hooks/firestore';
import { useApplicationContext } from 'src/features/application/context';
import { db } from 'src/firebase';

export const useSurveyListManager = () => {
const { user } = useApplicationContext();
const [q, setQ] = useState<Query<DocumentData>>();

useEffect(() => {
if (user?.uid) {
const surveysCollectionRef = collection(db, 'surveys');
setQ(
query(
surveysCollectionRef,
where('creatorId', '==', user?.uid),
orderBy('startDate', 'desc')
)
);
}
}, [user]);

const [surveysCollection, loading, error] = useCollection(q);

return { error, loading, surveysCollection };
};
Loading

0 comments on commit 6884298

Please sign in to comment.