añadido editar y eliminar posts

This commit is contained in:
2025-11-25 19:15:46 -03:00
parent dd49f853b4
commit e39bbe7047
20 changed files with 490 additions and 31 deletions

View File

@@ -15,35 +15,90 @@
import DropdownMenuLabel from './ui/dropdown-menu/dropdown-menu-label.svelte';
import DropdownMenuSeparator from './ui/dropdown-menu/dropdown-menu-separator.svelte';
import DropdownMenuItem from './ui/dropdown-menu/dropdown-menu-item.svelte';
import Avatar from './ui/avatar/avatar.svelte';
import AvatarImage from './ui/avatar/avatar-image.svelte';
import AvatarFallback from './ui/avatar/avatar-fallback.svelte';
import { deletePost } from '@/hooks/deletePost';
import Spinner from './ui/spinner/spinner.svelte';
import { removePost, updatePostStore } from '@/stores/posts';
import { Dialog } from './ui/dialog';
import DialogContent from './ui/dialog/dialog-content.svelte';
import DialogHeader from './ui/dialog/dialog-header.svelte';
import DialogTitle from './ui/dialog/dialog-title.svelte';
import DialogDescription from './ui/dialog/dialog-description.svelte';
import { updatePost } from '@/hooks/updatePost';
import { sesionStore } from '@/stores/usuario';
interface postProp {
post: Post;
postAModificar: Post | null;
}
let { post }: postProp = $props();
let { post, postAModificar = $bindable() }: postProp = $props();
let cargandoBorrar = $state(false);
let mensajeError = $state('');
let cargandoEditar = $state(false);
async function handleBorrar() {
await deletePost(
post,
() => {
removePost(post.id);
},
cargandoBorrar,
mensajeError
);
}
async function handleEditar() {
postAModificar = post;
}
</script>
<Card>
<CardHeader>
<div class="flex flex-col">
<div class="flex items-center justify-between">
<span class="text-sm font-medium">{post.authorId}</span>
<DropdownMenu>
<DropdownMenuTrigger>
<Button variant="ghost" class="rounded-full"><Ellipsis /></Button>
</DropdownMenuTrigger>
<DropdownMenuContent>
<DropdownMenuGroup>
<DropdownMenuLabel>Opciones Publicación</DropdownMenuLabel>
<DropdownMenuSeparator />
<DropdownMenuItem><Pen /> Editar</DropdownMenuItem>
<DropdownMenuItem onclick={() => {}}>
<Trash2 class="text-red-500" />
<p class="text-red-500">Borrar</p>
</DropdownMenuItem>
</DropdownMenuGroup>
</DropdownMenuContent>
</DropdownMenu>
<div class="flex gap-3">
<Avatar>
<AvatarImage></AvatarImage>
<AvatarFallback>{post.authorDisplayName[0].toUpperCase()}</AvatarFallback>
</Avatar>
<div class="flex space-x-2">
<span class="text-lg font-medium">{post.authorDisplayName}</span>
<span class="text-lg text-muted-foreground">@{post.authorName}</span>
</div>
</div>
{#if post.authorName === $sesionStore?.username}
<DropdownMenu>
<DropdownMenuTrigger>
<Button variant="ghost" class="rounded-full"><Ellipsis /></Button>
</DropdownMenuTrigger>
<DropdownMenuContent>
<DropdownMenuGroup>
<DropdownMenuLabel>Opciones Publicación</DropdownMenuLabel>
<DropdownMenuSeparator />
<DropdownMenuItem class="flex gap-2" onclick={() => handleEditar()}>
<Pen /> Editar
</DropdownMenuItem>
<DropdownMenuItem
class="flex gap-2"
onclick={() => {
handleBorrar();
}}
>
{#if cargandoBorrar}
<Spinner class="text-red-500" />
{:else}
<Trash2 class="text-red-500" />
{/if}
<p class="text-red-500">Borrar</p>
</DropdownMenuItem>
</DropdownMenuGroup>
</DropdownMenuContent>
</DropdownMenu>
{/if}
</div>
</div>
</CardHeader>
@@ -66,3 +121,15 @@
</div>
</CardFooter>
</Card>
{#if mensajeError}
<Dialog>
<DialogContent>
<DialogHeader>
<DialogTitle>Hubo un fallo</DialogTitle>
<DialogDescription>
{mensajeError}
</DialogDescription>
</DialogHeader>
</DialogContent>
</Dialog>
{/if}

View File

@@ -30,7 +30,7 @@
//credentials: 'include',
headers: {
'Content-Type': 'application/json',
"Authorization": `Bearer ${$sesionStore?.accessToken}`
Authorization: `Bearer ${$sesionStore?.accessToken}`
},
body: JSON.stringify(data)
@@ -51,11 +51,21 @@
cargando = false;
}
}
function handleKeydown(e: KeyboardEvent) {
if (e.ctrlKey && e.key === 'Enter') {
handlePost(e);
}
}
</script>
<form onsubmit={(e: Event) => handlePost(e)}>
<InputGroup>
<InputGroupTextarea bind:value={mensaje} maxlength="280" placeholder="Alguna novedad?"
<InputGroupTextarea
bind:value={mensaje}
maxlength="280"
placeholder="Alguna novedad?"
onkeydown={handleKeydown}
></InputGroupTextarea>
<InputGroupAddon align="block-end" class="bg-">

View File

@@ -0,0 +1,7 @@
<script lang="ts">
import { Dialog as DialogPrimitive } from "bits-ui";
let { ref = $bindable(null), ...restProps }: DialogPrimitive.CloseProps = $props();
</script>
<DialogPrimitive.Close bind:ref data-slot="dialog-close" {...restProps} />

View File

@@ -0,0 +1,43 @@
<script lang="ts">
import { Dialog as DialogPrimitive } from "bits-ui";
import XIcon from "@lucide/svelte/icons/x";
import type { Snippet } from "svelte";
import * as Dialog from "./index.js";
import { cn, type WithoutChildrenOrChild } from "$lib/utils.js";
let {
ref = $bindable(null),
class: className,
portalProps,
children,
showCloseButton = true,
...restProps
}: WithoutChildrenOrChild<DialogPrimitive.ContentProps> & {
portalProps?: DialogPrimitive.PortalProps;
children: Snippet;
showCloseButton?: boolean;
} = $props();
</script>
<Dialog.Portal {...portalProps}>
<Dialog.Overlay />
<DialogPrimitive.Content
bind:ref
data-slot="dialog-content"
class={cn(
"bg-background data-[state=open]:animate-in data-[state=closed]:animate-out data-[state=closed]:fade-out-0 data-[state=open]:fade-in-0 data-[state=closed]:zoom-out-95 data-[state=open]:zoom-in-95 fixed start-[50%] top-[50%] z-50 grid w-full max-w-[calc(100%-2rem)] translate-x-[-50%] translate-y-[-50%] gap-4 rounded-lg border p-6 shadow-lg duration-200 sm:max-w-lg",
className
)}
{...restProps}
>
{@render children?.()}
{#if showCloseButton}
<DialogPrimitive.Close
class="ring-offset-background focus:ring-ring rounded-xs focus:outline-hidden absolute end-4 top-4 opacity-70 transition-opacity hover:opacity-100 focus:ring-2 focus:ring-offset-2 disabled:pointer-events-none [&_svg:not([class*='size-'])]:size-4 [&_svg]:pointer-events-none [&_svg]:shrink-0"
>
<XIcon />
<span class="sr-only">Close</span>
</DialogPrimitive.Close>
{/if}
</DialogPrimitive.Content>
</Dialog.Portal>

View File

@@ -0,0 +1,17 @@
<script lang="ts">
import { Dialog as DialogPrimitive } from "bits-ui";
import { cn } from "$lib/utils.js";
let {
ref = $bindable(null),
class: className,
...restProps
}: DialogPrimitive.DescriptionProps = $props();
</script>
<DialogPrimitive.Description
bind:ref
data-slot="dialog-description"
class={cn("text-muted-foreground text-sm", className)}
{...restProps}
/>

View File

@@ -0,0 +1,20 @@
<script lang="ts">
import { cn, type WithElementRef } from "$lib/utils.js";
import type { HTMLAttributes } from "svelte/elements";
let {
ref = $bindable(null),
class: className,
children,
...restProps
}: WithElementRef<HTMLAttributes<HTMLDivElement>> = $props();
</script>
<div
bind:this={ref}
data-slot="dialog-footer"
class={cn("flex flex-col-reverse gap-2 sm:flex-row sm:justify-end", className)}
{...restProps}
>
{@render children?.()}
</div>

View File

@@ -0,0 +1,20 @@
<script lang="ts">
import type { HTMLAttributes } from "svelte/elements";
import { cn, type WithElementRef } from "$lib/utils.js";
let {
ref = $bindable(null),
class: className,
children,
...restProps
}: WithElementRef<HTMLAttributes<HTMLDivElement>> = $props();
</script>
<div
bind:this={ref}
data-slot="dialog-header"
class={cn("flex flex-col gap-2 text-center sm:text-start", className)}
{...restProps}
>
{@render children?.()}
</div>

View File

@@ -0,0 +1,20 @@
<script lang="ts">
import { Dialog as DialogPrimitive } from "bits-ui";
import { cn } from "$lib/utils.js";
let {
ref = $bindable(null),
class: className,
...restProps
}: DialogPrimitive.OverlayProps = $props();
</script>
<DialogPrimitive.Overlay
bind:ref
data-slot="dialog-overlay"
class={cn(
"data-[state=open]:animate-in data-[state=closed]:animate-out data-[state=closed]:fade-out-0 data-[state=open]:fade-in-0 fixed inset-0 z-50 bg-black/50",
className
)}
{...restProps}
/>

View File

@@ -0,0 +1,17 @@
<script lang="ts">
import { Dialog as DialogPrimitive } from "bits-ui";
import { cn } from "$lib/utils.js";
let {
ref = $bindable(null),
class: className,
...restProps
}: DialogPrimitive.TitleProps = $props();
</script>
<DialogPrimitive.Title
bind:ref
data-slot="dialog-title"
class={cn("text-lg font-semibold leading-none", className)}
{...restProps}
/>

View File

@@ -0,0 +1,7 @@
<script lang="ts">
import { Dialog as DialogPrimitive } from "bits-ui";
let { ref = $bindable(null), ...restProps }: DialogPrimitive.TriggerProps = $props();
</script>
<DialogPrimitive.Trigger bind:ref data-slot="dialog-trigger" {...restProps} />

View File

@@ -0,0 +1,37 @@
import { Dialog as DialogPrimitive } from "bits-ui";
import Title from "./dialog-title.svelte";
import Footer from "./dialog-footer.svelte";
import Header from "./dialog-header.svelte";
import Overlay from "./dialog-overlay.svelte";
import Content from "./dialog-content.svelte";
import Description from "./dialog-description.svelte";
import Trigger from "./dialog-trigger.svelte";
import Close from "./dialog-close.svelte";
const Root = DialogPrimitive.Root;
const Portal = DialogPrimitive.Portal;
export {
Root,
Title,
Portal,
Footer,
Header,
Trigger,
Overlay,
Content,
Description,
Close,
//
Root as Dialog,
Title as DialogTitle,
Portal as DialogPortal,
Footer as DialogFooter,
Header as DialogHeader,
Trigger as DialogTrigger,
Overlay as DialogOverlay,
Content as DialogContent,
Description as DialogDescription,
Close as DialogClose,
};

View File

@@ -0,0 +1,33 @@
import { apiBase } from '@/stores/url';
import type { Post } from '../../types';
import { sesionStore } from '@/stores/usuario';
import { get } from 'svelte/store';
export async function deletePost(
post: Post,
callbackfn: Function,
cargando: boolean,
message: string = ''
) {
try {
cargando = true;
const req = await fetch(get(apiBase) + `/api/posts/${post.id}`, {
method: 'DELETE',
headers: {
'Content-Type': 'application/json',
Authorization: `Bearer ${get(sesionStore)?.accessToken}`
}
});
if (req.status === 204) {
callbackfn();
return;
}
const msg = await req.json();
message = msg.message;
} catch {
message = 'No se pudo alcanzar el servidor';
} finally {
cargando = false;
}
}

View File

@@ -0,0 +1,29 @@
import { apiBase } from '@/stores/url';
import type { Post, PostResponseDto } from '../../types';
import { get } from 'svelte/store';
import { sesionStore } from '@/stores/usuario';
export async function updatePost(post: Post, callbackfn: Function, message: string) {
try {
const data = {
content: post.content,
imageUrl: post.imageUrl
};
const req = await fetch(get(apiBase) + `/api/posts/${post.id}`, {
method: 'PUT',
headers: {
'Content-Type': 'application/json',
Authorization: `Bearer ${get(sesionStore)?.accessToken}`
},
body: JSON.stringify(data)
});
if (req.ok) {
const newpost: PostResponseDto = await req.json();
callbackfn(newpost);
return;
}
message = 'Fallo al intentar modificar la publicación';
} catch {
message = 'No se pudo alcanzar el servidor';
}
}

View File

@@ -11,12 +11,18 @@ export const addPost = (post: Post) => {
posts.update((currentPosts) => [post, ...currentPosts]);
};
export const updatePost = (postId: string, updatedData: Partial<Post>) => {
export const updatePostStore = (postId: string, updatedData: Partial<Post>) => {
posts.update((currentPosts) =>
currentPosts.map((post) => (post._id === postId ? { ...post, ...updatedData } : post))
currentPosts.map((post) => (post.id === postId ? { ...post, ...updatedData } : post))
);
};
export const removePost = (postId: string) => {
posts.update((currentPosts) => currentPosts.filter((post) => post._id !== postId));
posts.update((currentPosts) => {
const a = currentPosts.filter((post) => post.id !== postId);
console.log(a);
return a;
});
console.log(postId);
};

View File

@@ -1,6 +1,6 @@
import { dev } from '$app/environment';
import { writable } from 'svelte/store';
import { readable } from 'svelte/store';
export const apiBase = writable(
export const apiBase = readable(
dev ? 'http://localhost:5000' : 'https://minix-back-dsuk.onrender.com'
);

View File

@@ -1,4 +1,4 @@
import { writable } from 'svelte/store';
import { get, writable } from 'svelte/store';
import { browser } from '$app/environment';
import type { Sesion } from '../../types';
import { apiBase } from '@/stores/url';
@@ -29,7 +29,7 @@ if (browser) {
if (browser) {
const refreshAccessToken = async () => {
try {
const response = await fetch(baseUrl + '/api/auth/refresh', {
const response = await fetch(get(apiBase) + '/api/auth/refresh', {
method: 'POST',
headers: {
'Content-Type': 'application/json'

View File

@@ -29,7 +29,7 @@
</script>
<div class="flex min-h-fit w-full items-center justify-center p-6 md:p-10">
<div class="w-full max-w-2xl">
<div class="w-full max-w-6xl">
<div class="flex flex-col gap-2">
{#if $sesionStore !== null}
<CrearPost />

View File

@@ -9,12 +9,19 @@
import type { Post } from '../../types.js';
import Spinner from '@/components/ui/spinner/spinner.svelte';
import { fade, slide } from 'svelte/transition';
import PostCard from '@/components/PostCard.svelte';
import { posts, setPosts, updatePostStore } from '@/stores/posts.js';
import InputGroup from '@/components/ui/input-group/input-group.svelte';
import InputGroupTextarea from '@/components/ui/input-group/input-group-textarea.svelte';
import InputGroupAddon from '@/components/ui/input-group/input-group-addon.svelte';
import { updatePost } from '@/hooks/updatePost.js';
import ModalEditar from './modalEditar.svelte';
let { params } = $props();
let posts: Post[] = $state([]);
let cargando = $state(true);
let mensajeError = $state('');
let postAModificar: Post | null = $state(null);
const { subscribe } = apiBase;
let baseUrl: string = '';
@@ -33,7 +40,7 @@
method: 'GET'
});
if (req.ok) {
posts = await req.json();
setPosts(await req.json());
return;
}
mensajeError = 'Fallo al obtener los datos';
@@ -43,10 +50,23 @@
cargando = false;
}
}
async function handleEditar(e: SubmitEvent) {
e.preventDefault();
// post.content = 'test';
if (postAModificar == null) return;
await updatePost(
postAModificar,
(postnuevo: Post) => updatePostStore(postAModificar!.id, postnuevo),
mensajeError
);
postAModificar = null;
}
</script>
<div class="flex min-h-fit w-full items-center justify-center p-6 md:p-10">
<div class="w-full max-w-2xl">
<div class="w-full max-w-6xl">
<Card class="mb-2 overflow-hidden">
<CardContent>
<div class="flex justify-center">
@@ -87,6 +107,19 @@
</CardContent>
</Card>
</div>
{:else}
<div class="flex flex-col gap-2">
{#each $posts as post}
<div out:slide>
<PostCard {post} bind:postAModificar />
</div>
{/each}
</div>
{/if}
</div>
</div>
{#if postAModificar}
<div in:fade>
<ModalEditar callbackfn={handleEditar} bind:post={postAModificar} />
</div>
{/if}

View File

@@ -0,0 +1,71 @@
<script lang="ts">
import { InputGroup } from '@/components/ui/input-group';
import InputGroupAddon from '@/components/ui/input-group/input-group-addon.svelte';
import InputGroupButton from '@/components/ui/input-group/input-group-button.svelte';
import InputGroupTextarea from '@/components/ui/input-group/input-group-textarea.svelte';
import Kbd from '@/components/ui/kbd/kbd.svelte';
import type { Post } from '../../types';
import ArrowUpIcon from '@lucide/svelte/icons/arrow-up';
import { Dialog } from '@/components/ui/dialog';
import DialogContent from '@/components/ui/dialog/dialog-content.svelte';
import DialogDescription from '@/components/ui/dialog/dialog-description.svelte';
import DialogHeader from '@/components/ui/dialog/dialog-header.svelte';
import DialogTitle from '@/components/ui/dialog/dialog-title.svelte';
interface Props {
post: Post | null;
callbackfn: Function;
}
let { post = $bindable(), callbackfn }: Props = $props();
function handleKeydown(e: KeyboardEvent) {
if (e.ctrlKey && e.key === 'Enter') {
callbackfn(e);
}
}
</script>
<Dialog open={true} onOpenChange={() => (post = null)}>
<DialogContent>
<DialogHeader>
<DialogTitle>Editar Publicacion</DialogTitle>
</DialogHeader>
<DialogDescription>
<form
onsubmit={(e: SubmitEvent) => {
callbackfn(e);
}}
>
<InputGroup>
<InputGroupTextarea
bind:value={post!.content}
maxlength={280}
placeholder="Alguna novedad?"
onkeydown={handleKeydown}
class="text-white"
></InputGroupTextarea>
<InputGroupAddon align="block-end" class="bg-">
<div class="flex w-full justify-between">
<Kbd class="text-sm leading-none font-medium italic">
<p class:text-red-500={post!.content.length > 239}>
{post!.content.length}
</p>
/ 280
</Kbd>
<InputGroupButton
variant="default"
type="submit"
class="transform rounded-full transition-transform ease-in hover:scale-120"
size="xs"
>
<p>Modificar</p>
<ArrowUpIcon />
</InputGroupButton>
</div>
</InputGroupAddon>
</InputGroup>
</form>
</DialogDescription>
</DialogContent>
</Dialog>

22
src/types.d.ts vendored
View File

@@ -1,6 +1,10 @@
export interface Post {
_id: string;
id: string;
authorId: string;
authorDisplayName: string;
authorImageUrl: string;
authorName: string;
content: string;
imageUrl?: string;
parentPostId?: string;
@@ -52,3 +56,21 @@ export interface CreatePostDto {
imageUrl: string?;
parentPostId: string?;
}
export interface PostResponseDto {
id: string;
authorId: string;
authorImageUrl: string?;
authorDisplayName: string;
authorName: string;
content: string;
imageUrl: string?;
parentPostId: string?;
likesCount: number;
repliesCount: number;
createdAt: string;
updatedAt: string?;
isEdited: boolean;
visibility: string;
hashtags: string[]?;
}