Skip to content

Commit

Permalink
Merge pull request #46 from maidh91/refactor-commands-tauri
Browse files Browse the repository at this point in the history
Refactor: Move all @tauri-apps calls to src/commands
  • Loading branch information
afadil authored Sep 9, 2024
2 parents b7c9bc0 + 27ece0e commit 4a7ab30
Show file tree
Hide file tree
Showing 9 changed files with 107 additions and 40 deletions.
6 changes: 6 additions & 0 deletions src/commands/README.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,6 @@
# Notes

- This `src/commands` directory contains all actions to communicate with Tauri via `@tauti-apps`
library, e.g. invoke, listen, open

- All other directories under `src` are native React code only
11 changes: 11 additions & 0 deletions src/commands/file.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,11 @@
import { open } from '@tauri-apps/api/dialog';

// openCsvFile
export const openCsvFileDialog = async (): Promise<null | string | string[]> => {
try {
return open({ filters: [{ name: 'CSV', extensions: ['csv'] }] });
} catch (error) {
console.error('Error open csv file', error);
throw error;
}
};
33 changes: 33 additions & 0 deletions src/commands/import-listener.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,33 @@
import { listen, EventCallback, UnlistenFn } from '@tauri-apps/api/event';

// listenImportFileDropHover
export const listenImportFileDropHover = async <T>(handler: EventCallback<T>): Promise<UnlistenFn> => {
try {
return listen<T>('tauri://file-drop-hover', handler);
} catch (error) {
console.error('Error listen tauri://file-drop-hover:', error);
throw error;
}
};

// listenImportFileDrop
export const listenImportFileDrop = async <T>(handler: EventCallback<T>): Promise<UnlistenFn> => {
try {
return listen<T>('tauri://file-drop', handler);
} catch (error) {
console.error('Error listen tauri://file-drop:', error);
throw error;
}
};

// listenImportFileDropCancelled
export const listenImportFileDropCancelled = async <T>(handler: EventCallback<T>): Promise<UnlistenFn> => {
try {
return listen<T>('tauri://file-drop-cancelled', handler);
} catch (error) {
console.error('Error listen tauri://file-drop-cancelled:', error);
throw error;
}
};

export type { UnlistenFn };
21 changes: 21 additions & 0 deletions src/commands/quote-listener.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,21 @@
import { listen, EventCallback, UnlistenFn } from '@tauri-apps/api/event';

// listenQuotesSyncStart
export const listenQuotesSyncStart = async <T>(handler: EventCallback<T>): Promise<UnlistenFn> => {
try {
return listen<T>('QUOTES_SYNC_START', handler);
} catch (error) {
console.error('Error listen QUOTES_SYNC_START:', error);
throw error;
}
};

// listenQuotesSyncComplete
export const listenQuotesSyncComplete = async <T>(handler: EventCallback<T>): Promise<UnlistenFn> => {
try {
return listen<T>('QUOTES_SYNC_COMPLETE', handler);
} catch (error) {
console.error('Error listen QUOTES_SYNC_COMPLETE:', error);
throw error;
}
};
24 changes: 24 additions & 0 deletions src/commands/setting.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,24 @@
import { invoke } from '@tauri-apps/api';
import { Settings } from '@/lib/types';

// getSettings
export const getSettings = async (): Promise<Settings> => {
try {
const settings = await invoke('get_settings');
return settings as Settings;
} catch (error) {
console.error('Error fetching settings:', error);
return {} as Settings;
}
};

// saveSettings
export const saveSettings = async (settings: Settings): Promise<Settings> => {
try {
const updatedSettings = await invoke('update_settings', { settings });
return updatedSettings as Settings;
} catch (error) {
console.error('Error updating settings:', error);
throw error;
}
};
12 changes: 1 addition & 11 deletions src/lib/settings-provider.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -2,8 +2,8 @@ import { createContext, useState, useEffect, ReactNode, useContext } from 'react
import { Settings, SettingsContextType } from './types';
import { useSettings } from './useSettings';
import { useMutation, useQueryClient } from '@tanstack/react-query';
import { invoke } from '@tauri-apps/api';
import { toast } from '@/components/ui/use-toast';
import { saveSettings } from '@/commands/setting';

const SettingsContext = createContext<SettingsContextType | undefined>(undefined);

Expand Down Expand Up @@ -77,13 +77,3 @@ const applySettingsToDocument = (newSettings: Settings) => {
// Color scheme must be applied to document element (`<html>`)
document.documentElement.style.colorScheme = newSettings.theme;
};

export const saveSettings = async (settings: Settings): Promise<Settings> => {
try {
const updatedSettings = await invoke('update_settings', { settings });
return updatedSettings as Settings;
} catch (error) {
console.error('Error updating settings:', error);
throw error;
}
};
12 changes: 1 addition & 11 deletions src/lib/useSettings.ts
Original file line number Diff line number Diff line change
@@ -1,20 +1,10 @@
import { useQuery } from '@tanstack/react-query';
import { Settings } from './types';
import { invoke } from '@tauri-apps/api';
import { getSettings } from '@/commands/setting';

export function useSettings() {
return useQuery<Settings, Error>({
queryKey: ['settings'],
queryFn: getSettings,
});
}

export const getSettings = async (): Promise<Settings> => {
try {
const settings = await invoke('get_settings');
return settings as Settings;
} catch (error) {
console.error('Error fetching settings:', error);
return {} as Settings;
}
};
22 changes: 7 additions & 15 deletions src/pages/activity/import/import-form.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -2,8 +2,6 @@ import { zodResolver } from '@hookform/resolvers/zod';
import { useState, useEffect } from 'react';
import { useForm } from 'react-hook-form';
import * as z from 'zod';
import { open } from '@tauri-apps/api/dialog';
import { listen, Event, UnlistenFn } from '@tauri-apps/api/event';
import { Link } from 'react-router-dom';

import { EmptyPlaceholder } from '@/components/empty-placeholder';
Expand Down Expand Up @@ -31,6 +29,8 @@ import type { Account, ActivityImport } from '@/lib/types';
import { getAccounts } from '@/commands/account';
import { useMutation, useQuery } from '@tanstack/react-query';
import { checkActivitiesImport } from '@/commands/activity';
import { listenImportFileDrop, listenImportFileDropCancelled, listenImportFileDropHover, UnlistenFn } from '@/commands/import-listener';
import { openCsvFileDialog } from '@/commands/file';

const importFormSchema = z.object({
account_id: z.string({ required_error: 'Please select an account.' }),
Expand All @@ -51,17 +51,9 @@ export const ActivityImportForm = ({ onSuccess, onError }: ActivityImportFormPro
const [dragging, setDragging] = useState<boolean>(false);

useEffect(() => {
const unlistenHover = listen<string>('tauri://file-drop-hover', () => {
setDragging(true);
});

const unlistenDrop = listen<string>('tauri://file-drop', () => {
setDragging(false);
});

const unlistenCancelled = listen<string>('tauri://file-drop-cancelled', () => {
setDragging(false);
});
const unlistenHover = listenImportFileDropHover<string>(() => setDragging(true));
const unlistenDrop = listenImportFileDrop<string>(() => setDragging(false));
const unlistenCancelled = listenImportFileDropCancelled<string>(() => setDragging(false));

return () => {
unlistenHover;
Expand All @@ -76,7 +68,7 @@ export const ActivityImportForm = ({ onSuccess, onError }: ActivityImportFormPro
let unlisten: UnlistenFn | null = null;
(async () => {
//tauri://file-drop and tauri://file-drop-hover (and tauri://file-drop-cancelled)
unlisten = await listen('tauri://file-drop', (event: Event<string[]>) => {
unlisten = await listenImportFileDrop<string[]>((event) => {
if (event.payload) {
setDragging(false);
form.setValue('file_path', event.payload[0] as string);
Expand Down Expand Up @@ -107,7 +99,7 @@ export const ActivityImportForm = ({ onSuccess, onError }: ActivityImportFormPro
});

const openFilePicker = async () => {
let filepath = await open({ filters: [{ name: 'CSV', extensions: ['csv'] }] });
let filepath = await openCsvFileDialog();
form.setValue('file_path', filepath as string);
};

Expand Down
6 changes: 3 additions & 3 deletions src/useGlobalEventListener.ts
Original file line number Diff line number Diff line change
@@ -1,8 +1,8 @@
// useGlobalEventListener.ts
import { useEffect } from 'react';
import { listen } from '@tauri-apps/api/event';
import { useQueryClient } from '@tanstack/react-query';
import { toast } from '@/components/ui/use-toast';
import { listenQuotesSyncComplete, listenQuotesSyncStart } from '@/commands/quote-listener';

const useGlobalEventListener = () => {
const queryClient = useQueryClient();
Expand All @@ -23,8 +23,8 @@ const useGlobalEventListener = () => {
});
};
const setupListeners = async () => {
const unlistenSyncStart = await listen('QUOTES_SYNC_START', handleQuoteSyncStart);
const unlistenSyncComplete = await listen('QUOTES_SYNC_COMPLETE', handleQuotesSyncComplete);
const unlistenSyncStart = await listenQuotesSyncStart(handleQuoteSyncStart);
const unlistenSyncComplete = await listenQuotesSyncComplete(handleQuotesSyncComplete);

return () => {
unlistenSyncStart();
Expand Down

0 comments on commit 4a7ab30

Please sign in to comment.