import { create } from "@bufbuild/protobuf"; import { FieldMaskSchema } from "@bufbuild/protobuf/wkt"; import React, { useEffect, useState } from "react"; import { toast } from "react-hot-toast"; import { Button } from "@/components/ui/button"; import { Dialog, DialogContent, DialogFooter, DialogHeader, DialogTitle } from "@/components/ui/dialog"; import { Input } from "@/components/ui/input"; import { Label } from "@/components/ui/label"; import { Textarea } from "@/components/ui/textarea"; import { shortcutServiceClient } from "@/connect"; import useCurrentUser from "@/hooks/useCurrentUser"; import useLoading from "@/hooks/useLoading"; import { userStore } from "@/store"; import { Shortcut, ShortcutSchema } from "@/types/proto/api/v1/shortcut_service_pb"; import { useTranslate } from "@/utils/i18n"; interface Props { open: boolean; onOpenChange: (open: boolean) => void; shortcut?: Shortcut; onSuccess?: () => void; } function CreateShortcutDialog({ open, onOpenChange, shortcut: initialShortcut, onSuccess }: Props) { const t = useTranslate(); const user = useCurrentUser(); const [shortcut, setShortcut] = useState( create(ShortcutSchema, { name: initialShortcut?.name || "", title: initialShortcut?.title || "", filter: initialShortcut?.filter || "", }), ); const requestState = useLoading(false); const isCreating = !initialShortcut; useEffect(() => { if (initialShortcut) { setShortcut( create(ShortcutSchema, { name: initialShortcut.name, title: initialShortcut.title, filter: initialShortcut.filter, }), ); } else { setShortcut(create(ShortcutSchema, { name: "", title: "", filter: "" })); } }, [initialShortcut]); const onShortcutTitleChange = (e: React.ChangeEvent) => { setShortcut({ ...shortcut, title: e.target.value }); }; const onShortcutFilterChange = (e: React.ChangeEvent) => { setShortcut({ ...shortcut, filter: e.target.value }); }; const handleConfirm = async () => { if (!shortcut.title || !shortcut.filter) { toast.error("Title and filter cannot be empty"); return; } try { requestState.setLoading(); if (isCreating) { await shortcutServiceClient.createShortcut({ parent: user.name, shortcut: { name: "", // Will be set by server title: shortcut.title, filter: shortcut.filter, }, }); toast.success("Create shortcut successfully"); } else { await shortcutServiceClient.updateShortcut({ shortcut: { ...shortcut, name: initialShortcut!.name, // Keep the original resource name }, updateMask: create(FieldMaskSchema, { paths: ["title", "filter"] }), }); toast.success("Update shortcut successfully"); } // Refresh shortcuts. await userStore.fetchUserSettings(); requestState.setFinish(); onSuccess?.(); onOpenChange(false); } catch (error: any) { console.error(error); toast.error(error.message); requestState.setError(); } }; return ( {`${isCreating ? t("common.create") : t("common.edit")} ${t("common.shortcuts")}`}