import { Action, ActionPanel, useNavigation, Form, Icon, getPreferenceValues, showToast, Toast } from "@raycast/api"; import { MutatePromise, useForm, FormValidation, useFetch } from "@raycast/utils"; import { Page, UniversalInboxPreferences } from "../types"; import { Notification } from "../notification"; import { Task, TaskStatus } from "../task"; import { handleErrors } from "../api"; import { useState } from "react"; import fetch from "node-fetch"; interface LinkNotificationToTaskProps { notification: Notification; mutate: MutatePromise | undefined>; } interface TaskLinkFormValues { taskId: string; } export function LinkNotificationToTask({ notification, mutate }: LinkNotificationToTaskProps) { const preferences = getPreferenceValues(); const { pop } = useNavigation(); const [searchText, setSearchText] = useState(""); const { isLoading, data: tasks } = useFetch>( `${preferences.universalInboxBaseUrl.replace(/\/$/, "")}/api/tasks/search?matches=${searchText}`, { keepPreviousData: true, headers: { Authorization: `Bearer ${preferences.apiKey}`, }, }, ); const { handleSubmit, itemProps } = useForm({ async onSubmit(values) { await linkNotificationToTask(notification, values.taskId, mutate); pop(); }, validation: { taskId: FormValidation.Required, }, }); return (
} > {tasks?.map((task) => { return ; })} ); } async function linkNotificationToTask( notification: Notification, taskId: string, mutate: MutatePromise | undefined>, ) { const preferences = getPreferenceValues(); const toast = await showToast({ style: Toast.Style.Animated, title: "Linking notification to task" }); try { await mutate( handleErrors( fetch(`${preferences.universalInboxBaseUrl.replace(/\/$/, "")}/api/notifications/${notification.id}`, { method: "PATCH", body: JSON.stringify({ status: TaskStatus.Deleted, task_id: taskId }), headers: { "Content-Type": "application/json", Authorization: `Bearer ${preferences.apiKey}`, }, }), ), { optimisticUpdate(page) { if (page) { page.content = page.content.filter((n) => n.id !== notification.id); } return page; }, }, ); toast.style = Toast.Style.Success; toast.title = "Notification successfully linked to task"; } catch (error) { toast.style = Toast.Style.Failure; toast.title = "Failed to link notification to task"; toast.message = (error as Error).message; throw error; } }