import React, { useState, useEffect } from "react"; import { DragDropContext, Droppable, DropResult } from "react-beautiful-dnd"; import Link, { EditableLink } from "components/Editor/Link"; import { useAuth } from "components/Login/AuthContext"; import Preview from "components/Preview"; import { useDragDrop } from "./useDragDrop"; import equal from "fast-deep-equal"; interface EditorProps { links: EditableLink[]; setLinks: React.Dispatch>; } const Editor: React.FC = ({ links, setLinks }) => { const { displayDragDrop } = useDragDrop(); const { headers } = useAuth(); const [editableLinks, setEditableLinks] = useState(links); const [isSaving, setIsSaving] = useState(false); useEffect(() => { setEditableLinks(links); }, [links]); const handleOnDragEnd = (result: DropResult) => { if (!result?.destination) return; const items = Array.from(editableLinks); const [reorderedItem] = items.splice(result.source.index, 1); items.splice(result.destination.index, 0, reorderedItem); setEditableLinks(items); }; /*note that we need to make the new links name render with nothing*/ const handleOnClickAdd = () => setEditableLinks([ ...editableLinks, { name: "", url: "", clicks: 0, active: true, }, ]); const onSubmit = async () => { setIsSaving(true); const res = await fetch("api/editor/links", { method: "POST", headers: { "Content-Type": "application/json", ...headers, }, body: JSON.stringify({ links: editableLinks }), }); const updatedLinks = await res.json(); setLinks(updatedLinks); setIsSaving(false); }; const onCancel = () => { setEditableLinks(links); }; return (
{displayDragDrop && ( {(provided) => (
{editableLinks.map((link, index) => ( setEditableLinks([ ...editableLinks.slice(0, index), newLink, ...editableLinks.slice(index + 1), ]) } onDelete={() => setEditableLinks([ ...editableLinks.slice(0, index), ...editableLinks.slice(index + 1), ]) } /> ))} {provided.placeholder}
)}
)}
link.active)} />
); }; export default Editor;