import { Button, IconButton, Input, Modal, ModalDialog } from "@mui/joy"; import { useEffect, useState } from "react"; import { toast } from "react-hot-toast"; import { useStorageContext } from "@/context"; import { useShortcutStore } from "@/stores"; import type { Visibility } from "@/types/proto/api/v1/common"; import { Shortcut } from "@/types/proto/api/v1/shortcut_service"; import Icon from "./Icon"; interface State { name: string; title: string; link: string; } const CreateShortcutButton = () => { const context = useStorageContext(); const shortcutStore = useShortcutStore(); const [state, setState] = useState({ name: "", title: "", link: "", }); const [tag, setTag] = useState(""); const [isLoading, setIsLoading] = useState(false); const [showModal, setShowModal] = useState(false); useEffect(() => { if (showModal) { document.body.style.height = "384px"; } else { document.body.style.height = "auto"; } }, [showModal]); const handleCreateShortcutButtonClick = async () => { chrome.tabs.query({ active: true, currentWindow: true }, async (tabs) => { if (tabs.length === 0) { toast.error("No active tab found"); return; } const tab = tabs[0]; setState((state) => ({ ...state, name: "", title: tab.title || "", link: tab.url || "", })); setShowModal(true); }); }; const generateRandomName = () => { const chars = "abcdefghijklmnopqrstuvwxyz0123456789"; let name = ""; for (let i = 0; i < 8; i++) { name += chars.charAt(Math.floor(Math.random() * chars.length)); } setState((state) => ({ ...state, name, })); }; const handleNameInputChange = (e: React.ChangeEvent) => { setState((state) => ({ ...state, name: e.target.value, })); }; const handleTitleInputChange = (e: React.ChangeEvent) => { setState((state) => ({ ...state, title: e.target.value, })); }; const handleLinkInputChange = (e: React.ChangeEvent) => { setState((state) => ({ ...state, link: e.target.value, })); }; const handleTagsInputChange = (e: React.ChangeEvent) => { const text = e.target.value as string; setTag(text); }; const handleSaveBtnClick = async () => { if (isLoading) { return; } if (!state.name) { toast.error("Name is required"); return; } setIsLoading(true); try { const tags = tag.split(" ").filter(Boolean); await shortcutStore.createShortcut( context.instanceUrl, context.accessToken, Shortcut.fromPartial({ name: state.name, title: state.title, link: state.link, tags, visibility: context.defaultVisibility as Visibility, }), ); toast.success("Shortcut created successfully"); setShowModal(false); } catch (error: any) { console.error(error); toast.error(error.response.data.message); } setIsLoading(false); }; return ( <> handleCreateShortcutButtonClick()}> document.body} open={showModal} onClose={() => setShowModal(false)}>
Create Shortcut
Name } />
Title
Link
Tags
); }; export default CreateShortcutButton;