diff --git a/src/context/Patterns.tsx b/src/context/Patterns.tsx index 8a97260..f073600 100644 --- a/src/context/Patterns.tsx +++ b/src/context/Patterns.tsx @@ -1,9 +1,10 @@ import { invoke } from '@tauri-apps/api/core'; import dayjs from 'dayjs'; -import { atom } from 'jotai'; -import { atomFamily, atomWithRefresh } from 'jotai/utils'; +import { atom, useSetAtom } from 'jotai'; +import { atomWithDefault, atomWithRefresh } from 'jotai/utils'; import { get, reduce } from 'lodash-es'; import { v4 } from 'uuid'; +import { NotificationType, ToastDuration, useNotification } from '../components/Notifications'; export enum FrequencyShifting { /** @@ -120,18 +121,34 @@ export function totalDuration(pattern: Pattern): number { ); } -export const PatternsAtom = atomFamily((keyword: string) => - atomWithRefresh(async () => { - try { - const patterns = await invoke('list_patterns', { keyword }); - return patterns; - } catch (e) { - console.error('[retrieving pattern list]', e); +export const SearchKeywordAtom = atom(null); +export const PatternsAtom = atomWithRefresh(async (get) => { + try { + const keyword = get(SearchKeywordAtom); + if (keyword === null) { + return []; } - return []; - }), -); -export const CurrentPatternAtom = atom(null); + const patterns = await invoke('list_patterns', { keyword }); + return patterns; + } catch (e) { + console.error('[retrieving pattern list]', e); + } + return []; +}); +export const SelectedPatternIdAtom = atomWithDefault(null); +export const CurrentPatternAtom = atom(async (get) => { + try { + const patternId = get(SelectedPatternIdAtom); + if (patternId === null) { + return null; + } + const pattern = await invoke('get_pattern', { patternId }); + return pattern; + } catch (e) { + console.error('[retrieving pattern]', e); + } + return null; +}); export const PulsesInCurrentPatternAtom = atom( (get) => get(CurrentPatternAtom)?.pulses ?? [], (get, set, pulse: Pulse) => { @@ -155,3 +172,25 @@ export const CurrentPatternDuration = atom((get) => { if (!currentPattern) return 0; return totalDuration(currentPattern); }); + +export function useSavePattern() { + const refreshPatterns = useSetAtom(PatternsAtom); + const { showToast } = useNotification(); + + const savePattern = async (pattern: Pattern) => { + try { + await invoke('save_pattern', { pattern }); + refreshPatterns(); + } catch (error) { + console.error('[save pattern]', error); + showToast( + NotificationType.ERROR, + 'Failed to save pattern. Please try again.', + 'material-symbols-light:error-outline', + ToastDuration.MEDIUM, + ); + } + }; + + return savePattern; +}