Move toast state to Jotai

This commit is contained in:
Gregory Schier
2025-01-06 12:05:43 -08:00
parent c2ea2a5fe5
commit ab55c2e0ce
5 changed files with 62 additions and 80 deletions

View File

@@ -1,6 +1,7 @@
import { emit } from '@tauri-apps/api/event';
import type { PromptTextRequest, PromptTextResponse } from '@yaakapp-internal/plugins';
import {useWatchWorkspace} from "@yaakapp-internal/sync";
import { useWatchWorkspace } from '@yaakapp-internal/sync';
import type { ShowToastRequest } from '@yaakapp/api';
import {
useEnsureActiveCookieJar,
useSubscribeActiveCookieJarId,
@@ -28,6 +29,7 @@ import { useSyncWorkspaceChildModels } from '../hooks/useSyncWorkspaceChildModel
import { useSyncWorkspaceRequestTitle } from '../hooks/useSyncWorkspaceRequestTitle';
import { useSyncZoomSetting } from '../hooks/useSyncZoomSetting';
import { useSubscribeTemplateFunctions } from '../hooks/useTemplateFunctions';
import {useToast} from "../hooks/useToast";
import { useToggleCommandPalette } from '../hooks/useToggleCommandPalette';
export function GlobalHooks() {
@@ -55,6 +57,12 @@ export function GlobalHooks() {
useActiveWorkspaceChangedToast();
useEnsureActiveCookieJar();
// Listen for toasts
const toast = useToast();
useListenToTauriEvent<ShowToastRequest>('show_toast', (event) => {
toast.show({ ...event.payload });
});
// Trigger workspace sync operation when workspace files change
const activeWorkspace = useActiveWorkspace();
const { debouncedSync } = useSyncWorkspace(activeWorkspace, { debounceMillis: 1000 });

View File

@@ -1,4 +0,0 @@
import { createContext } from 'react';
import type { ToastState } from './Toasts';
export const ToastContext = createContext<ToastState>({} as ToastState);

View File

@@ -1,74 +1,24 @@
import type { ShowToastRequest } from '@yaakapp-internal/plugins';
import { AnimatePresence } from 'framer-motion';
import React, { type ReactNode, useContext, useMemo, useRef, useState } from 'react';
import { useListenToTauriEvent } from '../hooks/useListenToTauriEvent';
import { generateId } from '../lib/generateId';
import { useAtomValue } from 'jotai';
import React, { type ReactNode } from 'react';
import { toastsAtom, useToast } from '../hooks/useToast';
import { Toast, type ToastProps } from './core/Toast';
import { Portal } from './Portal';
import { ToastContext } from './ToastContext';
type ToastEntry = {
export type ToastEntry = {
id?: string;
message: ReactNode;
timeout?: 3000 | 5000 | 8000 | null;
onClose?: ToastProps['onClose'];
} & Omit<ToastProps, 'onClose' | 'open' | 'children' | 'timeout'>;
type PrivateToastEntry = ToastEntry & {
export type PrivateToastEntry = ToastEntry & {
id: string;
timeout: number | null;
};
export interface ToastState {
toasts: PrivateToastEntry[];
actions: Actions;
}
export interface Actions {
show: (d: ToastEntry) => void;
hide: (id: string) => void;
}
export const ToastProvider = ({ children }: { children: React.ReactNode }) => {
const [toasts, setToasts] = useState<ToastState['toasts']>([]);
const timeoutRef = useRef<NodeJS.Timeout>();
const actions = useMemo<Actions>(
() => ({
show({ id, timeout = 5000, ...props }: ToastEntry) {
id = id ?? generateId();
if (timeout != null) {
timeoutRef.current = setTimeout(() => this.hide(id), timeout);
}
setToasts((a) => {
if (a.some((v) => v.id === id)) {
// It's already visible with this id
return a;
}
return [...a, { id, timeout, ...props }];
});
return id;
},
hide: (id: string) => {
setToasts((all) => {
const t = all.find((t) => t.id === id);
t?.onClose?.();
return all.filter((t) => t.id !== id);
});
},
}),
[],
);
useListenToTauriEvent<ShowToastRequest>('show_toast', (event) => {
actions.show({ ...event.payload });
});
const state: ToastState = { toasts, actions };
return <ToastContext.Provider value={state}>{children}</ToastContext.Provider>;
};
function ToastInstance({ id, message, timeout, ...props }: PrivateToastEntry) {
const { actions } = useContext(ToastContext);
const toast = useToast();
return (
<Toast
open
@@ -76,7 +26,7 @@ function ToastInstance({ id, message, timeout, ...props }: PrivateToastEntry) {
{...props}
// We call onClose inside actions.hide instead of passing to toast so that
// it gets called from external close calls as well
onClose={() => actions.hide(id)}
onClose={() => toast.hide(id)}
>
{message}
</Toast>
@@ -84,7 +34,7 @@ function ToastInstance({ id, message, timeout, ...props }: PrivateToastEntry) {
}
export const Toasts = () => {
const { toasts } = useContext(ToastContext);
const toasts = useAtomValue(toastsAtom);
return (
<Portal name="toasts">
<div className="absolute right-0 bottom-0 z-20">

View File

@@ -1,6 +1,36 @@
import { useContext } from 'react';
import { ToastContext } from '../components/ToastContext';
import { atom } from 'jotai/index';
import { useMemo } from 'react';
import type { PrivateToastEntry, ToastEntry } from '../components/Toasts';
import { generateId } from '../lib/generateId';
import { jotaiStore } from '../lib/jotai';
export const toastsAtom = atom<PrivateToastEntry[]>([]);
export function useToast() {
return useContext(ToastContext).actions;
return useMemo(
() => ({
show({ id, timeout = 5000, ...props }: ToastEntry) {
id = id ?? generateId();
if (timeout != null) {
setTimeout(() => this.hide(id), timeout);
}
jotaiStore.set(toastsAtom, (a) => {
if (a.some((v) => v.id === id)) {
// It's already visible with this id
return a;
}
return [...a, { id, timeout, ...props }];
});
return id;
},
hide: (id: string) => {
jotaiStore.set(toastsAtom, (all) => {
const t = all.find((t) => t.id === id);
t?.onClose?.();
return all.filter((t) => t.id !== id);
});
},
}),
[],
);
}

View File

@@ -10,7 +10,7 @@ import { HelmetProvider } from 'react-helmet-async';
import { DialogProvider, Dialogs } from '../components/Dialogs';
import { GlobalHooks } from '../components/GlobalHooks';
import RouteError from '../components/RouteError';
import { ToastProvider, Toasts } from '../components/Toasts';
import { Toasts } from '../components/Toasts';
import { useOsInfo } from '../hooks/useOsInfo';
import { jotaiStore } from '../lib/jotai';
@@ -66,19 +66,17 @@ function RouteComponent() {
<DndProvider backend={HTML5Backend}>
<Suspense>
<DialogProvider>
<ToastProvider>
<GlobalHooks />
<Toasts />
<Dialogs />
<div
className={classNames(
'w-full h-full',
osInfo?.osType === 'linux' && 'border border-border-subtle',
)}
>
<Outlet />
</div>
</ToastProvider>
<GlobalHooks />
<Toasts />
<Dialogs />
<div
className={classNames(
'w-full h-full',
osInfo?.osType === 'linux' && 'border border-border-subtle',
)}
>
<Outlet />
</div>
</DialogProvider>
</Suspense>
</DndProvider>