+
+
+
- )
-}
diff --git a/src/components/atoms/DropDownShare.tsx b/src/components/atoms/DropDownShare.tsx
deleted file mode 100644
index 854419c..0000000
--- a/src/components/atoms/DropDownShare.tsx
+++ /dev/null
@@ -1,131 +0,0 @@
-import { Menu, Transition } from '@headlessui/react'
-import Image from 'next/image'
-import { Fragment, useEffect, useState } from 'react'
-import ShareWhatsapp from '../../../public/images/IconWhatsapp.svg'
-import Share from '../../../public/images/shared1.svg'
-import ShareTwitter from '../../../public/images/xSocial.svg'
-
-export const DropDownShare = ({
- slug,
- id,
- counTwitter,
- countWhatsapp
-}: {
- slug?: string
- id: string
- counTwitter?: number
- countWhatsapp?: number
-}) => {
- const [textShare, setTextShare] = useState('')
- useEffect(() => {
- if (slug) {
- setTextShare(
- 'Tienes que ver este recurso, ' +
- location.href +
- 'post/' +
- slug +
- ' lo he encontrado aquí, pásate hay más ' +
- location.origin
- )
- } else {
- setTextShare(
- 'Tienes que ver este recurso, ' + location.href + ' lo he encontrado aquí, pásate hay más ' + location.origin
- )
- }
- }, [])
-
- {
- /*
-
-
*/
- }
- const sharePost = async (postId, platform) => {
- try {
- const response = await fetch('/api/share', {
- method: 'POST',
- headers: {
- 'Content-Type': 'application/json'
- },
- body: JSON.stringify({ postId, platform })
- })
-
- if (response.ok) {
- const data = await response.json()
- // Actualiza la interfaz de usuario según sea necesario
- } else {
- console.error('Error sharing post:', response.statusText)
- }
- } catch (error) {
- console.error('Error sharing post:', error.message)
- }
- }
-
- return (
-
- )
-}
diff --git a/src/components/atoms/ErrorSpan.tsx b/src/components/atoms/ErrorSpan.tsx
new file mode 100644
index 0000000..924d64a
--- /dev/null
+++ b/src/components/atoms/ErrorSpan.tsx
@@ -0,0 +1,8 @@
+type SpanProps = {
+ children: React.ReactNode
+ className?: string
+}
+
+export const ErrorSpan = ({ children, className }: SpanProps) => {
+ return
{children}
+}
diff --git a/src/components/atoms/Input.tsx b/src/components/atoms/Input.tsx
new file mode 100644
index 0000000..0f64db9
--- /dev/null
+++ b/src/components/atoms/Input.tsx
@@ -0,0 +1,49 @@
+import { useController, useFormContext } from 'react-hook-form'
+import { ErrorSpan } from './ErrorSpan'
+
+const Input = ({
+ name,
+ label,
+ type,
+ placeholder,
+ className,
+ classNameContent,
+ ...others
+}: {
+ name: string
+ label?: string
+ type?: string
+ placeholder?: string
+ className?: string
+ classNameContent?: string
+ [others: string]: unknown
+}) => {
+ const {
+ control,
+ formState: { errors }
+ } = useFormContext()
+
+ const { field } = useController({
+ name,
+ control
+ })
+ console.log(field.name)
+
+ return (
+
+
+
+ {errors[name] && {errors[name]?.message?.toString()}}
+
+ )
+}
+
+export default Input
diff --git a/src/components/atoms/Modal.tsx b/src/components/atoms/Modal.tsx
deleted file mode 100644
index f718064..0000000
--- a/src/components/atoms/Modal.tsx
+++ /dev/null
@@ -1,70 +0,0 @@
-import { Dialog } from '@headlessui/react'
-import Image from 'next/image'
-import { useRouter } from 'next/router'
-import AlertIcon from '../../../public/images/alert.svg'
-
-const Modal = ({
- setIsOpen,
- isOpen,
- icon,
- tittle,
- description,
- textTrue,
- textFalse = 'Cancelar',
- functionTrue,
- functionFalse
-}: {
- isOpen: boolean
- setIsOpen: (value: boolean) => void
- icon: boolean
- tittle: string
- description: string
- textTrue: string
- textFalse?: string
- functionTrue: () => void
- functionFalse: () => void
-}) => {
- const router = useRouter()
- return (
-
- )
-}
-
-export default Modal
diff --git a/src/components/atoms/ModalCreateTag.tsx b/src/components/atoms/ModalCreateTag.tsx
deleted file mode 100644
index 3871f14..0000000
--- a/src/components/atoms/ModalCreateTag.tsx
+++ /dev/null
@@ -1,138 +0,0 @@
-import { Dialog } from '@headlessui/react'
-import { useSession } from 'next-auth/react'
-import Image from 'next/image'
-import { useRouter } from 'next/router'
-import { SubmitHandler, useForm } from 'react-hook-form'
-import AlertIcon from '../../../public/images/alert.svg'
-
-interface FormData {
- name: string
- slug: string
- color: string
-}
-
-const ModalCreateTag = ({
- setIsOpen,
- isOpen,
- icon,
- tittle,
- description,
- textTrue,
- textFalse = 'Cancelar',
- functionTrue,
- functionFalse
-}: {
- isOpen: boolean
- setIsOpen: (value: boolean) => void
- icon?: boolean
- tittle: string
- description?: string
- textTrue: string
- textFalse?: string
- functionTrue: () => void
- functionFalse: () => void
-}) => {
- const router = useRouter()
- const { data: session } = useSession()
-
- const {
- register,
- handleSubmit,
- watch,
- getValues,
- formState: { errors }
- } = useForm
()
-
- const onSubmit: SubmitHandler = async (dataForm) => {
- const { name, slug, color } = dataForm
-
- // try {
- // const response = await fetch('/api/tag', {
- // method: 'POST',
- // headers: {
- // 'Content-Type': 'application/json'
- // },
-
- // body: JSON.stringify({
- // name,
- // slug: slugify(name),
- // color,
- // userEmail: session?.user?.email
- // })
- // })
- // // if (!response.ok) {
- // // throw new Error('You have already used this title')
- // // }
- // if (!response.ok) {
- // const errorData = await response.json()
- // }
- // const data = await response.json()
- // setIsOpen(false)
- // } catch (error) {
- // console.error(error, 'Error fetching data')
- // const errorMessage = (error as { message?: string })?.message || 'Error creating post'
- // }
- }
- return (
-
- )
-}
-
-export default ModalCreateTag
diff --git a/src/components/atoms/StatIndividual.tsx b/src/components/atoms/StatIndividual.tsx
deleted file mode 100644
index b550777..0000000
--- a/src/components/atoms/StatIndividual.tsx
+++ /dev/null
@@ -1,10 +0,0 @@
-const StatIndividual = ({ stat, tittle }: { stat: number; tittle: string }) => {
- return (
-
- )
-}
-
-export default StatIndividual
diff --git a/src/components/atoms/Tag.tsx b/src/components/atoms/Tag.tsx
deleted file mode 100644
index 2512abd..0000000
--- a/src/components/atoms/Tag.tsx
+++ /dev/null
@@ -1,21 +0,0 @@
-type Tag = {
- color: string
- name: string
- className?: string
- [others: string]: any
-}
-
-const Tag = ({ color, name, className, others }: Tag) => {
- return (
-
- )
-}
-
-export default Tag
diff --git a/src/components/forms/FormLogin.tsx b/src/components/forms/FormLogin.tsx
new file mode 100644
index 0000000..d3b0652
--- /dev/null
+++ b/src/components/forms/FormLogin.tsx
@@ -0,0 +1,117 @@
+import UserStore from '@/store/UserStore'
+import { yupResolver } from '@hookform/resolvers/yup'
+import { useTranslation } from 'next-i18next'
+import Image from 'next/image'
+import { useRouter } from 'next/router'
+import { useForm } from 'react-hook-form'
+import { SubmitHandler } from 'react-hook-form/dist/types'
+import * as yup from 'yup'
+import Logonegro from '../../../public/images/logo_sobre_negro.png'
+import { InputsLogin, User } from '../../../types'
+import { ErrorSpan } from '../atoms/ErrorSpan'
+
+export default function FormLogin() {
+ const { t } = useTranslation()
+ const { setUser } = UserStore()
+ const userSchema = yup.object({
+ username: yup.string().email(t('common:emailNoCorrecto')).required(t('common:userNameMandatory')),
+ password: yup.string().required(t('common:passwordMandatory'))
+ })
+
+ const {
+ register,
+ watch,
+ handleSubmit,
+ formState: { errors }
+ } = useForm({
+ resolver: yupResolver(userSchema)
+ })
+ const router = useRouter()
+
+ const onSubmit: SubmitHandler = async (data) => {
+ console.log(data)
+ const url = `${process.env.BASE_URL}api/login_check`
+ const username = 'developer'
+ const password = 'mambita'
+ // const base64Credentials = btoa(`${username}:${password}`)
+ // const urlWithCredentials = `${url}?username=${username}&password=${password}`
+
+ try {
+ const response = await fetch(url, {
+ method: 'POST',
+ headers: {
+ 'Content-Type': 'application/json'
+ // Authorization: `Basic ${urlWithCredentials}`,
+ // mode: 'cors'
+ // credentials: 'include'
+ },
+ body: JSON.stringify(data)
+ })
+ if (response.ok) {
+ const responseData: User = await response.json()
+ setUser(responseData)
+ router.push('/home')
+ setUser(responseData)
+ console.log(responseData, 'responseData')
+ } else {
+ console.error('Error al realizar la solicitud')
+ }
+ } catch (error) {
+ console.error('Error al realizar la solicitud', error)
+ }
+ }
+ return (
+
+ )
+}
diff --git a/src/components/forms/FormRegister.tsx b/src/components/forms/FormRegister.tsx
new file mode 100644
index 0000000..8e72858
--- /dev/null
+++ b/src/components/forms/FormRegister.tsx
@@ -0,0 +1,110 @@
+import UserStore from '@/store/UserStore'
+import { yupResolver } from '@hookform/resolvers/yup'
+import { useTranslation } from 'next-i18next'
+import Image from 'next/image'
+import { useRouter } from 'next/router'
+import { FormProvider, SubmitHandler, useForm } from 'react-hook-form'
+import * as yup from 'yup'
+import Logonegro from '../../../public/images/logo_sobre_negro.png'
+import { InputRegister } from '../../../types'
+import CheckBox from '../atoms/CheckBox'
+import Input from '../atoms/Input'
+
+export default function FormRegister() {
+ const { t } = useTranslation()
+ const { setUser } = UserStore()
+
+ const Schema = yup.object({
+ firstName: yup.string().required(t('common:userNameMandatory')),
+ lastName: yup.string().required('El apellido es obligatorio'),
+ email: yup.string().email(t('common:emailNoCorrecto')).required(t('common:enterYourEmail')),
+ password: yup.string().min(9, 'a dooonde vas flipado minimo 9').required(t('common:passwordMandatory')),
+ phone: yup.string().required('El telefono es obligatorio'),
+ birthday: yup.string().required('La fecha de cumpleaños es obligatoria'),
+ // profilePicture: yup.string(),
+ privacyPolicy: yup.boolean().oneOf([true], 'Debes aceptar los términos para poder continuar')
+ })
+ const methods = useForm({
+ resolver: yupResolver(Schema),
+ defaultValues: {
+ firstName: '',
+ lastName: '',
+ email: '',
+ birthday: '',
+ password: '',
+ phone: '',
+ privacyPolicy: false
+ }
+ })
+ const {
+ handleSubmit,
+ formState: { errors }
+ } = methods
+ const router = useRouter()
+ const onSubmit: SubmitHandler = async (data) => {
+ console.log(data)
+ const url = `${process.env.BASE_URL}api/register`
+
+ try {
+ const response = await fetch(url, {
+ method: 'POST',
+ headers: { 'Content-Type': 'application/json' },
+ body: JSON.stringify(data)
+ })
+ if (response.ok) {
+ const responseData = await response.json()
+ setUser(responseData)
+ router.push('/home')
+ console.log(responseData, 'responseData')
+ } else {
+ console.error('Error al realizar la solicitud')
+ }
+ } catch (error) {
+ console.error('Error al realizar la solicitud', error)
+ }
+ }
+
+ return (
+
+ )
+}
diff --git a/src/components/layouts/AuthLayout.tsx b/src/components/layouts/AuthLayout.tsx
new file mode 100644
index 0000000..8c38f76
--- /dev/null
+++ b/src/components/layouts/AuthLayout.tsx
@@ -0,0 +1,15 @@
+import React from 'react'
+import { Footer } from '../organism/Footer'
+
+type AuthLayoutProps = {
+ children: React.ReactNode
+}
+export const AuthLayout = ({ children }: AuthLayoutProps) => {
+ return (
+
+ {/*
*/}
+
{children}
+
+
+ )
+}
diff --git a/src/components/layouts/Layout.tsx b/src/components/layouts/Layout.tsx
index 9c9c067..59c4f4e 100644
--- a/src/components/layouts/Layout.tsx
+++ b/src/components/layouts/Layout.tsx
@@ -7,9 +7,9 @@ type LayoutProps = {
}
export const Layout = ({ children }: LayoutProps) => {
return (
-
+
-
{children}
+
{children}
)
diff --git a/src/components/molecules/Card.tsx b/src/components/molecules/Card.tsx
deleted file mode 100644
index 3de641b..0000000
--- a/src/components/molecules/Card.tsx
+++ /dev/null
@@ -1,301 +0,0 @@
-import Image from 'next/image'
-import Link from 'next/link'
-import { FaRegComment } from 'react-icons/fa'
-// import { FaLink } from 'react-icons/fa6'
-// import { MdDelete, MdEdit } from 'react-icons/md'
-import { useSession } from 'next-auth/react'
-import { useRouter } from 'next/router'
-import { useEffect, useState } from 'react'
-import { CgLoadbarSound } from 'react-icons/cg'
-import { FaRegStar, FaStar } from 'react-icons/fa'
-import { FcLike } from 'react-icons/fc'
-import { FiHeart } from 'react-icons/fi'
-import { Post } from '../../../type'
-import { DropDownShare } from '../atoms/DropDownShare'
-import Modal from '../atoms/Modal'
-
-interface CardProps {
- post: Post
-}
-
-export function Card({ post }: CardProps) {
- // const { postData, updatePostData } = usePostContext()
- const {
- description,
- title,
- Category,
- slug,
- url,
- Like,
- id,
- comments,
- views,
- twitterShareCount,
- whatsappShareCount,
- Favorite
- // Tags
- } = post
- const { data: session } = useSession()
- // const likeOfUser = Like?.some((user) => user.userEmail === session?.user?.email)
- const [isLike, setIsLike] = useState
()
- const [isFavorite, setIsFavorite] = useState()
- const [likesCount, setLikesCount] = useState(Like?.length || 0)
- const [favoriteCount, setFavoriteCount] = useState(Favorite?.length || 0)
- let [isOpen, setIsOpen] = useState(false)
- const router = useRouter()
-
- useEffect(() => {
- if (session && Like?.some((like) => like?.userEmail === session?.user?.email)) {
- setIsLike(true)
- } else {
- setIsLike(false)
- }
- }, [Like, session])
-
- useEffect(() => {
- if (session && Favorite?.some((fav) => fav?.userEmail === session?.user?.email)) {
- setIsFavorite(true)
- } else {
- setIsFavorite(false)
- }
- }, [Favorite, session])
-
- const handleAddLike = async () => {
- if (!session) {
- setIsOpen(true)
- return
- }
- const response = await fetch(`/api/like`, {
- method: 'POST',
- headers: {
- 'Content-Type': 'application/json'
- },
- body: JSON.stringify({
- email: session.user.email,
- postId: id,
- session: session
- })
- })
- const data = await response.json()
- if (response.ok) {
- data && setIsLike(true)
- setLikesCount((prevCount) => prevCount + 1)
- } else {
- console.error('Error al dar like:', data.error)
- }
- }
- const handleDeleteLike = async () => {
- if (!session) {
- setIsOpen(true)
- return
- }
- const response = await fetch('/api/like', {
- method: 'DELETE',
- headers: {
- 'Content-Type': 'application/json'
- },
- body: JSON.stringify({
- email: session.user.email,
- postId: id,
- session: session
- })
- })
-
- const data = await response.json()
-
- if (response.ok) {
- setIsLike(false)
- setLikesCount((prevCount) => Math.max(0, prevCount - 1))
- } else {
- console.error('Error al quitar like:', data.error)
- }
- }
- const handleAddFavorite = async () => {
- if (!session) {
- setIsOpen(true)
- return
- }
- const response = await fetch(`/api/favorite`, {
- method: 'POST',
- headers: {
- 'Content-Type': 'application/json'
- },
- body: JSON.stringify({
- email: session.user.email,
- postId: id,
- session: session
- })
- })
- const data = await response.json()
- if (response.ok) {
- data && setIsFavorite(true)
- setFavoriteCount((prevCount) => prevCount + 1)
- } else {
- console.error('Error al dar like:', data.error)
- }
- }
- const handleDeleteFavorite = async () => {
- if (!session) {
- setIsOpen(true)
- return
- }
- const response = await fetch('/api/favorite', {
- method: 'DELETE',
- headers: {
- 'Content-Type': 'application/json'
- },
- body: JSON.stringify({
- email: session.user.email,
- postId: id,
- session: session
- })
- })
-
- const data = await response.json()
-
- if (response.ok) {
- setIsFavorite(false)
- setFavoriteCount((prevCount) => Math.max(0, prevCount - 1))
- } else {
- console.error('Error al quitar like:', data.error)
- }
- }
-
- return (
-
-
-
-
-
-
-
{title}
-
-
-
-
- {description?.length > 80 ? `${description.substring(0, 80)}...` : description}
-
{' '}
- {description?.length > 80 && (
-
- ver más
-
- )}
-
-
-
- {/*
- {Tags &&
- Tags?.slice(0, 4).map((tag) => (
-
- ))}
-
*/}
-
- {/*
*/}
-
-
{
- isLike ? handleDeleteLike() : handleAddLike()
- }}
- >
- {isLike ? (
-
- ) : (
-
- )}
-
- {/*
*/}
-
-
- {likesCount}
-
-
-
-
{
- isFavorite ? handleDeleteFavorite() : handleAddFavorite()
- }}
- >
- {isFavorite ? (
-
- ) : (
-
- )}
-
- {favoriteCount}
-
-
-
-
-
-
-
-
-
-
- {comments?.length}
- {' '}
-
-
-
-
-
-
- {twitterShareCount + whatsappShareCount}
- {' '}
-
-
-
-
- {views}
- {' '}
-
-
-
-
-
router.push('/login')}
- functionFalse={() => router.back()}
- />
-
- )
-}
diff --git a/src/components/molecules/CardList.tsx b/src/components/molecules/CardList.tsx
deleted file mode 100644
index ed524f9..0000000
--- a/src/components/molecules/CardList.tsx
+++ /dev/null
@@ -1,48 +0,0 @@
-import { usePostContext } from '@/context/PostContext'
-import { Card } from './Card'
-import Pagination from './Pagination'
-
-export function CardList({ page, cat, count }: any) {
- // const [dataCards, setDataCards] = useState([])
- // const [countN, setCount] = useState(count)
- const { postData, updatePostData } = usePostContext()
-
- // const getData = async (page: any, cat: any) => {
- // console.log('funciona')
-
- // try {
- // const response = await fetch(`http://localhost:3000/api/posts?page=${page || 1}&cat=${cat || ''}`, {
- // cache: 'no-store'
- // })
- // console.log(response)
-
- // if (!response.ok) {
- // throw new Error('Failed')
- // }
- // const result = await response.json()
- // updatePostData(result.posts)
- // // setCount(result.count)
- // } catch (error) {
- // console.error(error)
- // }
- // }
- // useEffect(() => {
- // getData(page, cat)
- // }, [page, cat])
-
- // NO LO TENGO MUY CLARO PERO CREO QUE ESTO NO ME HACE FALTA, TENGO QUE REVISARLO CON CALMA
-
- const POST_PER_PAGE = 4
- const hasPrev = POST_PER_PAGE * (page - 1) > 0
- const hasNext = POST_PER_PAGE * (page - 1) + POST_PER_PAGE < count
- return (
- <>
-
- {Array.isArray(postData) && postData?.map((item) => )}
-
-
- >
- )
-}
diff --git a/src/components/molecules/CardPerfil.tsx b/src/components/molecules/CardPerfil.tsx
deleted file mode 100644
index 3aae3b7..0000000
--- a/src/components/molecules/CardPerfil.tsx
+++ /dev/null
@@ -1,279 +0,0 @@
-import Link from 'next/link'
-import { FaRegComment } from 'react-icons/fa'
-// import { FaLink } from 'react-icons/fa6'
-// import { MdDelete, MdEdit } from 'react-icons/md'
-import { useSession } from 'next-auth/react'
-import { useRouter } from 'next/router'
-import { useEffect, useState } from 'react'
-import { CgLoadbarSound } from 'react-icons/cg'
-import { FaRegStar, FaStar } from 'react-icons/fa'
-import { FcLike } from 'react-icons/fc'
-import { FiHeart } from 'react-icons/fi'
-import { Post } from '../../../type'
-import { DropDownShare } from '../atoms/DropDownShare'
-import Modal from '../atoms/Modal'
-
-interface CardPerfilProps {
- post: Post
-}
-
-export function CardPerfil({ post }: CardPerfilProps) {
- // const { postData, updatePostData } = usePostContext()
- const {
- description,
- title,
- Category,
- slug,
- url,
- Like,
- id,
- comments,
- views,
- twitterShareCount,
- whatsappShareCount,
- Favorite
- } = post
- const { data: session } = useSession()
- // const likeOfUser = Like?.some((user) => user.userEmail === session?.user?.email)
- const [isLike, setIsLike] = useState()
- const [isFavorite, setIsFavorite] = useState()
- const [likesCount, setLikesCount] = useState(Like?.length || 0)
- const [favoriteCount, setFavoriteCount] = useState(Favorite?.length || 0)
- let [isOpen, setIsOpen] = useState(false)
- const router = useRouter()
-
- useEffect(() => {
- if (session && Like?.some((like) => like?.userEmail === session?.user?.email)) {
- setIsLike(true)
- } else {
- setIsLike(false)
- }
- }, [Like, session])
-
- useEffect(() => {
- if (session && Favorite?.some((fav) => fav?.userEmail === session?.user?.email)) {
- setIsFavorite(true)
- } else {
- setIsFavorite(false)
- }
- }, [Favorite, session])
-
- const handleAddLike = async () => {
- if (!session) {
- setIsOpen(true)
- return
- }
- const response = await fetch(`/api/like`, {
- method: 'POST',
- headers: {
- 'Content-Type': 'application/json'
- },
- body: JSON.stringify({
- email: session.user.email,
- postId: id,
- session: session
- })
- })
- const data = await response.json()
- if (response.ok) {
- data && setIsLike(true)
- setLikesCount((prevCount) => prevCount + 1)
- } else {
- console.error('Error al dar like:', data.error)
- }
- }
- const handleDeleteLike = async () => {
- if (!session) {
- setIsOpen(true)
- return
- }
- const response = await fetch('/api/like', {
- method: 'DELETE',
- headers: {
- 'Content-Type': 'application/json'
- },
- body: JSON.stringify({
- email: session.user.email,
- postId: id,
- session: session
- })
- })
-
- const data = await response.json()
-
- if (response.ok) {
- setIsLike(false)
- setLikesCount((prevCount) => Math.max(0, prevCount - 1))
- } else {
- console.error('Error al quitar like:', data.error)
- }
- }
- const handleAddFavorite = async () => {
- if (!session) {
- setIsOpen(true)
- return
- }
- const response = await fetch(`/api/favorite`, {
- method: 'POST',
- headers: {
- 'Content-Type': 'application/json'
- },
- body: JSON.stringify({
- email: session.user.email,
- postId: id,
- session: session
- })
- })
- const data = await response.json()
- if (response.ok) {
- data && setIsFavorite(true)
- setFavoriteCount((prevCount) => prevCount + 1)
- } else {
- console.error('Error al dar like:', data.error)
- }
- }
- const handleDeleteFavorite = async () => {
- if (!session) {
- setIsOpen(true)
- return
- }
- const response = await fetch('/api/favorite', {
- method: 'DELETE',
- headers: {
- 'Content-Type': 'application/json'
- },
- body: JSON.stringify({
- email: session.user.email,
- postId: id,
- session: session
- })
- })
-
- const data = await response.json()
-
- if (response.ok) {
- setIsFavorite(false)
- setFavoriteCount((prevCount) => Math.max(0, prevCount - 1))
- } else {
- console.error('Error al quitar like:', data.error)
- }
- }
- return (
-
- {/*
*/}
-
-
-
-
-
- {/*
*/}
-
-
{
- isLike ? handleDeleteLike() : handleAddLike()
- }}
- >
- {isLike ? (
-
- ) : (
-
- )}
-
- {/*
*/}
-
-
- {likesCount}
-
-
-
-
{
- isFavorite ? handleDeleteFavorite() : handleAddFavorite()
- }}
- >
- {isFavorite ? (
-
- ) : (
-
- )}
-
- {favoriteCount}
-
-
-
-
-
-
-
-
-
-
- {comments?.length}
- {' '}
-
-
-
-
-
-
- {twitterShareCount + whatsappShareCount}
- {' '}
-
-
-
-
- {views}
- {' '}
-
-
-
-
-
router.push('/login')}
- functionFalse={() => router.back()}
- />
-
- )
-}
diff --git a/src/components/molecules/Coment.tsx b/src/components/molecules/Coment.tsx
deleted file mode 100644
index 4853183..0000000
--- a/src/components/molecules/Coment.tsx
+++ /dev/null
@@ -1,107 +0,0 @@
-'use client'
-
-import { useSession } from 'next-auth/react'
-import Image from 'next/image'
-import { useRouter } from 'next/router'
-import { useState } from 'react'
-import { MdDelete } from 'react-icons/md'
-import useSWR from 'swr'
-import { Comment } from '../../../type'
-import Modal from '../atoms/Modal'
-
-interface CommentProps {
- postSlug?: string | string[] | undefined
- // comments?: Comment[] | [] | undefined
- // setComments: React.Dispatch>
-}
-export default function Comment({
- postSlug
-}: // comments, setComments
-CommentProps) {
- const router = useRouter()
- const session = useSession()
- const [showModalComment, setShowModalComment] = useState(false)
- const fetcher = async (url: string) => {
- const res = await fetch(url)
- const data = await res.json()
- if (!res.ok) {
- throw new Error('Failed to fetch comments')
- }
- return data
- }
- // const [comments, setComments] = useState([])
- // const [loading, setLoading] = useState(true)
- const { data, mutate, isLoading } = useSWR(`/api/comments/?postSlug=${postSlug}`, fetcher)
- const formatDate = (dateString: string) => {
- const options: Intl.DateTimeFormatOptions = {
- year: 'numeric',
- month: 'long',
- day: 'numeric'
- }
- return new Date(dateString).toLocaleDateString('en-US', options)
- }
- const deleteComment = async (commentId: string) => {
- try {
- const response = await fetch(`/api/comments`, {
- method: 'DELETE',
- headers: { 'Content-Type': 'application/json' },
- body: JSON.stringify({ id: commentId })
- })
- if (!response.ok) {
- throw new Error('Failed to delete comment')
- }
- mutate()
- } catch (error) {}
- }
- return (
-
-
- {isLoading
- ? '...loading'
- : data?.map((comment: Comment) => (
-
-
-
-
- {comment?.user?.image && (
-
-
-
- )}
-
-
{comment?.user?.name}
-
{formatDate(comment?.createdAt)}
-
-
- {comment?.user?.email === session.data?.user?.email && (
-
setShowModalComment(true)}>
-
-
- )}
-
-
{comment.description}
-
- {/* MODAL PARA ELIMINAR COMENTARIO */}
-
deleteComment(comment?.id)}
- functionFalse={() => setShowModalComment(false)}
- />
-
- ))}
-
-
- )
-}
diff --git a/src/components/molecules/CommentWrite.tsx b/src/components/molecules/CommentWrite.tsx
deleted file mode 100644
index 61583d5..0000000
--- a/src/components/molecules/CommentWrite.tsx
+++ /dev/null
@@ -1,60 +0,0 @@
-import { useSession } from 'next-auth/react'
-import { useState } from 'react'
-import { useSWRConfig } from 'swr'
-import { Button } from '../atoms/Button'
-
-export default function CommentWrite({ postSlug }: any) {
- const [description, setDesc] = useState('')
- const { data: session } = useSession()
- const [loading, setLoading] = useState(false)
- const { mutate } = useSWRConfig()
-
- const handleChange = (e: React.ChangeEvent) => {
- setDesc(e.target.value)
- }
- const handleSubmit = async () => {
- try {
- setLoading(true)
-
- const response = await fetch('/api/comments', {
- method: 'POST',
- headers: {
- 'Content-Type': 'application/json'
- },
- body: JSON.stringify({ description, postSlug, session })
- })
-
- if (!response.ok) {
- throw new Error('Failed to create comment')
- }
-
- setDesc('')
- mutate(`/api/comments/?postSlug=${postSlug}`)
- } catch (error) {
- console.error(error)
- } finally {
- setLoading(false)
- }
- }
- return (
-
-
Comments
-
-
-
-
-
- )
-}
diff --git a/src/components/molecules/CreatePostForm.tsx b/src/components/molecules/CreatePostForm.tsx
deleted file mode 100644
index 55831f9..0000000
--- a/src/components/molecules/CreatePostForm.tsx
+++ /dev/null
@@ -1,240 +0,0 @@
-import { useSession } from 'next-auth/react'
-import Image from 'next/image'
-import { useRouter } from 'next/router'
-import { useEffect, useState } from 'react'
-import { SubmitHandler, useForm } from 'react-hook-form'
-import { Category } from '../../../type'
-import { Button } from '../atoms/Button'
-
-interface FormData {
- title: string
- description: string
- url: string
- catSlug: string
- // tag?: string[]
-}
-
-export function CreatePostForm() {
- const {
- register,
- handleSubmit,
- watch,
- getValues,
- formState: { errors }
- } = useForm()
- // console.log(errors)
-
- const router = useRouter()
- // const session = useSession()
- const { data: session } = useSession()
- const [categories, setCategories] = useState([])
- const [categorySelected, setCategorySelected] = useState()
- const [error, setError] = useState()
- // const [showCreateTag, setShowCreateTag] = useState(false)
-
- useEffect(() => {
- const getData = async () => {
- try {
- const response = await fetch('api/categories', {
- cache: 'no-store'
- })
-
- if (!response.ok) {
- throw new Error('Failed')
- }
-
- const result = await response.json()
- setCategories(result)
- } catch (error) {
- console.error(error)
- }
- }
-
- getData()
- }, [])
- const slugify = (str: string) => {
- return str
- .toLowerCase()
- .trim()
- .replace(/[^\w\s-]/g, '')
- .replace(/[\s_-]+/g, '-')
- .replace(/^-+|-+$/g, '')
- }
- const onSubmit: SubmitHandler = async (dataForm) => {
- const { title, description, url, catSlug } = dataForm
- try {
- const response = await fetch('/api/post', {
- method: 'POST',
- headers: {
- 'Content-Type': 'application/json'
- },
-
- body: JSON.stringify({
- title,
- description,
- slug: slugify(title),
- catSlug: catSlug,
- url,
- userEmail: session?.user?.email
- })
- })
- // if (!response.ok) {
- // throw new Error('You have already used this title')
- // }
- if (!response.ok) {
- const errorData = await response.json()
- if (errorData.type === 'duplicate') throw new Error(error)
- if (errorData.type === 'unAuthorized') throw new Error(error)
- }
- const data = await response.json()
- router.push('/')
- } catch (error) {
- console.error(error, 'Error fetching data')
- const errorMessage = (error as { message?: string })?.message || 'Error creating post'
- setError(errorMessage)
- }
- }
- useEffect(() => {
- const category = getValues('catSlug')
- const categorySelect = categories.find((cat) => cat.slug === category)
- categorySelect && setCategorySelected(categorySelect)
- }, [watch('catSlug')])
-
- useEffect(() => {
- // hago esto para comprobar si el usuario logeado (session) es admin.
- // Para eso hago un get del usuario para traerme los datos de este y ver si es admin.
- const fetchUser = async () => {
- try {
- const response = await fetch(`/api/user?email=${session?.user?.email}`)
- const userData = await response.json()
- !userData.isAdmin && router.push('/')
- } catch (error: any) {
- console.error('Error fetching user:', error.message)
- }
- }
-
- fetchUser()
- }, [])
-
- return (
-
- )
-}
diff --git a/src/components/molecules/EditPost.tsx b/src/components/molecules/EditPost.tsx
deleted file mode 100644
index d851bb9..0000000
--- a/src/components/molecules/EditPost.tsx
+++ /dev/null
@@ -1,291 +0,0 @@
-import { useSession } from 'next-auth/react'
-import Image from 'next/image'
-import { useRouter } from 'next/router'
-import { useEffect, useState } from 'react'
-import { SubmitHandler, useForm } from 'react-hook-form'
-import { Category, Post } from '../../../type'
-import { Button } from '../atoms/Button'
-
-interface FormData {
- title: string
- description: string
- url: string
- catSlug: string
- // Tags?: Tag[]
-}
-type EditProps = {
- dataPost: Post
-}
-export function EditPost({ dataPost }: EditProps) {
- const {
- register,
- handleSubmit,
- watch,
- getValues,
- reset,
- formState: { errors }
- } = useForm()
- // console.log(errors)
-
- const router = useRouter()
- // const session = useSession()
- const { data: session } = useSession()
- const [categories, setCategories] = useState([])
- // const [tags, setTags] = useState()
- const [categorySelected, setCategorySelected] = useState()
- // const [selectedTags, setSelectedTags] = useState()
-
- const [error, setError] = useState()
- useEffect(() => {
- const getData = async () => {
- try {
- const response = await fetch('/api/categories', {
- cache: 'no-store'
- })
-
- if (!response.ok) {
- throw new Error('Failed')
- }
-
- const result = await response.json()
- setCategories(result)
- } catch (error) {
- console.error(error)
- }
- }
-
- getData()
- }, [])
-
- // const slugify = (str: string) => {
- // return str
- // .toLowerCase()
- // .trim()
- // .replace(/[^\w\s-]/g, '')
- // .replace(/[\s_-]+/g, '-')
- // .replace(/^-+|-+$/g, '')
- // }
- const onSubmit: SubmitHandler = async (dataForm) => {
- const { title, description, url, catSlug } = dataForm
- try {
- const response = await fetch(`/api/post/${dataPost?.slug}`, {
- method: 'PUT',
- headers: {
- 'Content-Type': 'application/json'
- },
-
- body: JSON.stringify({
- title,
- description,
- // slug: slugify(title),
- catSlug: catSlug,
- url
- // Tags: selectedTags
- // userEmail: session?.user?.email
- })
- })
- // if (!response.ok) {
- // throw new Error('You have already used this title')
- // }
- if (!response.ok) {
- const errorData = await response.json()
- if (errorData.type === 'duplicate') throw new Error(error)
- if (errorData.type === 'unAuthorized') throw new Error(error)
- }
- const data = await response.json()
- router.push('/')
- } catch (error) {
- console.error(error, 'Error fetching data')
- const errorMessage = (error as { message?: string })?.message || 'Error creating post'
- setError(errorMessage)
- }
- }
- useEffect(() => {
- const category = getValues('catSlug')
- const categorySelect = categories.find((cat) => cat.slug === category)
- categorySelect && setCategorySelected(categorySelect)
- }, [watch('catSlug')])
-
- useEffect(() => {
- // hago esto para comprobar si el usuario logeado (session) es admin.
- // Para eso hago un get del usuario para traerme los datos de este y ver si es admin.
- const fetchUser = async () => {
- try {
- const response = await fetch(`/api/user?email=${session?.user?.email}`)
- const userData = await response.json()
- !userData.isAdmin && router.push('/')
- } catch (error: any) {
- console.error('Error fetching user:', error.message)
- }
- }
-
- fetchUser()
- }, [session])
-
- useEffect(() => {
- reset({
- title: dataPost?.title,
- catSlug: dataPost?.catSlug,
- description: dataPost?.description,
- url: dataPost?.url
- // Tags: dataPost?.Tags
- })
- // setSelectedTags(dataPost?.Tags?.map((tag) => tag) || [])
- }, [dataPost])
-
- return (
-
- )
-}
diff --git a/src/components/molecules/EditUser.tsx b/src/components/molecules/EditUser.tsx
deleted file mode 100644
index 9157b9a..0000000
--- a/src/components/molecules/EditUser.tsx
+++ /dev/null
@@ -1,136 +0,0 @@
-import { useSession } from 'next-auth/react'
-import Image from 'next/image'
-import { useRouter } from 'next/router'
-import { useEffect, useState } from 'react'
-import { SubmitHandler, useForm } from 'react-hook-form'
-import { User } from '../../../type'
-import { Button } from '../atoms/Button'
-
-type EditProps = {
- user: User
-}
-export function EditUser({ user }: EditProps) {
- const {
- register,
- handleSubmit,
- watch,
- getValues,
- reset,
- setError,
- formState: { errors }
- } = useForm({
- defaultValues: {}
- })
- const router = useRouter()
- // const [userData, setUser] = useState()
-
- const { data: session, status } = useSession()
- const [errorShow, setShowError] = useState('')
- const onSubmit: SubmitHandler = async (dataForm) => {
- try {
- const response = await fetch(`/api/user/?email=${user?.email}`, {
- method: 'PUT',
- headers: {
- 'Content-Type': 'application/json'
- },
-
- body: JSON.stringify({
- name: dataForm.name
- })
- })
-
- if (response.status === 409) {
- const errorData = await response.json()
- setError('name', { type: 'manual', message: errorData.message })
- return
- }
- if (!response.ok) {
- throw new Error('Error updating user. Please try again later.')
- }
- const data = await response.json()
- setShowError(data?.message)
- // router.push('/')
- } catch (error) {
- console.error(error, 'Error fetching data')
- }
- }
- useEffect(() => {
- status === 'unauthenticated' && router.push('/')
- }, [session, status, router])
- useEffect(() => {
- reset({
- name: user?.name,
- email: user?.email
- })
- }, [user])
-
- return (
-
- )
-}
diff --git a/src/components/molecules/MenuNavbar.tsx b/src/components/molecules/MenuNavbar.tsx
index b364944..c72ff93 100644
--- a/src/components/molecules/MenuNavbar.tsx
+++ b/src/components/molecules/MenuNavbar.tsx
@@ -1,76 +1,28 @@
-import { signOut, useSession } from 'next-auth/react'
+import { useTranslation } from 'next-i18next'
import { useRouter } from 'next/router'
-import { User } from '../../../type'
import { Button } from '../atoms/Button'
-interface MenuNavbarProps {
- // userCurrent: User | undefined
- dataUserCurrent: User
-}
-export const MenuNavbar = ({ dataUserCurrent }: MenuNavbarProps) => {
+export const MenuNavbar = () => {
+ const { t } = useTranslation()
const router = useRouter()
- const { status, data: session } = useSession()
return (
-
-