Skip to content

Commit

Permalink
add: setting
Browse files Browse the repository at this point in the history
  • Loading branch information
shm11C3 committed Sep 1, 2024
1 parent 2dc0ae5 commit afe03fe
Show file tree
Hide file tree
Showing 9 changed files with 104 additions and 48 deletions.
16 changes: 16 additions & 0 deletions src-tauri/src/commands/config.rs
Original file line number Diff line number Diff line change
Expand Up @@ -77,6 +77,12 @@ impl Settings {
self.write_file();
println!("{:?}", self);
}

pub fn set_display_targets(&mut self, new_targets: Vec<hardware::HardwareType>) {
self.display_targets = new_targets;
self.write_file();
println!("{:?}", self);
}
}

#[derive(Debug)]
Expand Down Expand Up @@ -122,4 +128,14 @@ pub mod commands {
let settings = state.settings.lock().unwrap().clone();
Ok(settings)
}

#[tauri::command]
pub async fn set_display_targets(
state: tauri::State<'_, AppState>,
new_targets: Vec<hardware::HardwareType>,
) -> Result<(), String> {
let mut settings = state.settings.lock().unwrap();
settings.set_display_targets(new_targets);
Ok(())
}
}
22 changes: 20 additions & 2 deletions src-tauri/src/enums/hardware.rs
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
use serde::{Deserialize, Serialize, Serializer};
use serde::{Deserialize, Deserializer, Serialize, Serializer};

#[derive(Debug, PartialEq, Eq, Clone, Deserialize)]
#[derive(Debug, PartialEq, Eq, Clone)]
pub enum HardwareType {
CPU,
Memory,
Expand All @@ -20,3 +20,21 @@ impl Serialize for HardwareType {
serializer.serialize_str(s)
}
}

impl<'de> Deserialize<'de> for HardwareType {
fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
where
D: Deserializer<'de>,
{
let s = String::deserialize(deserializer)?.to_lowercase();
match s.as_str() {
"cpu" => Ok(HardwareType::CPU),
"memory" => Ok(HardwareType::Memory),
"gpu" => Ok(HardwareType::GPU),
_ => Err(serde::de::Error::unknown_variant(
&s,
&["cpu", "memory", "gpu"],
)),
}
}
}
1 change: 1 addition & 0 deletions src-tauri/src/main.rs
Original file line number Diff line number Diff line change
Expand Up @@ -58,6 +58,7 @@ fn main() {
hardware::get_gpu_usage_history,
config::commands::set_language,
config::commands::set_theme,
config::commands::set_display_targets,
config::commands::get_settings
])
.on_menu_event(|event| {
Expand Down
22 changes: 3 additions & 19 deletions src/App.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -3,36 +3,20 @@ import TestTemplate from "./components/Sample";
import ChartTemplate from "./template/Chart";
import "./index.css";
import { useSettingsModalListener } from "@/hooks/useTauriEventListener";
import { useAtom } from "jotai";
import { settingsAtom } from "./atom/main";
import { useSettingsAtom } from "./atom/useSettingsAtom";

import SettingsSheet from "./components/modals/SettingsSheet";
import SettingsSheet from "@/template/SettingsSheet";
import { useDarkMode } from "./hooks/useDarkMode";
import { getSettings } from "./services/settingService";

type ButtonState = "chart" | "raw";

const useLoadSettings = () => {
const [, setSettings] = useAtom(settingsAtom);

useEffect(() => {
const loadSettings = async () => {
const setting = await getSettings();
setSettings(setting);
};
loadSettings();
}, [setSettings]);
};

const Page = () => {
const [buttonState, setButtonState] = useState<ButtonState>("chart");
const [settings] = useAtom(settingsAtom);
const { settings } = useSettingsAtom();
const { toggle } = useDarkMode();

useSettingsModalListener();

useLoadSettings();

const handleShowData = () => {
setButtonState(buttonState === "raw" ? "chart" : "raw");
};
Expand Down
8 changes: 0 additions & 8 deletions src/atom/main.ts

This file was deleted.

42 changes: 42 additions & 0 deletions src/atom/useSettingsAtom.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,42 @@
import {
getSettings,
setDisplayTargets,
setTheme,
} from "@/services/settingService";
import type { ChartDataType } from "@/types/chartType";
import type { Settings } from "@/types/settingsType";
import { atom, useAtom } from "jotai";
import { useEffect } from "react";
const settingsAtom = atom<Settings>({
language: "en",
theme: "light",
display_targets: [],
});

export const useSettingsAtom = () => {
const [settings, setSettings] = useAtom(settingsAtom);

useEffect(() => {
const loadSettings = async () => {
const setting = await getSettings();
setSettings(setting);
};
loadSettings();
}, [setSettings]);

const toggleDisplayTarget = async (target: ChartDataType) => {
const newTargets = settings.display_targets.includes(target)
? settings.display_targets.filter((t) => t !== target)
: [...settings.display_targets, target];

setSettings((prev) => ({ ...prev, display_targets: newTargets }));
await setDisplayTargets(settings.display_targets);
};

const toggleTheme = async (theme: "light" | "dark") => {
setSettings((prev) => ({ ...prev, theme }));
await setTheme(theme);
};

return { settings, toggleDisplayTarget, toggleTheme };
};
10 changes: 10 additions & 0 deletions src/services/settingService.ts
Original file line number Diff line number Diff line change
Expand Up @@ -4,3 +4,13 @@ import { invoke } from "@tauri-apps/api/tauri";
export const getSettings = async (): Promise<Settings> => {
return await invoke("get_settings");
};

export const setTheme = async (theme: Settings["theme"]): Promise<void> => {
return await invoke("set_theme", { newTheme: theme });
};

export const setDisplayTargets = async (
targets: Settings["display_targets"],
): Promise<void> => {
return await invoke("set_display_targets", { newTargets: targets });
};
4 changes: 2 additions & 2 deletions src/template/Chart.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -3,7 +3,7 @@ import {
graphicUsageHistoryAtom,
memoryUsageHistoryAtom,
} from "@/atom/chart";
import { settingsAtom } from "@/atom/main";
import { useSettingsAtom } from "@/atom/useSettingsAtom";
import LineChart from "@/components/charts/LineChart";
import { chartConfig } from "@/consts/chart";
import { useUsageUpdater } from "@/hooks/useHardwareData";
Expand Down Expand Up @@ -45,7 +45,7 @@ const GpuUsageChart = () => {
};

const ChartTemplate = () => {
const [settings] = useAtom(settingsAtom);
const { settings } = useSettingsAtom();

const renderedCharts = useMemo(() => {
return (
Expand Down
Original file line number Diff line number Diff line change
@@ -1,13 +1,11 @@
import { settingsAtom } from "@/atom/main";
import { modalAtoms } from "@/atom/ui";
import { useSettingsAtom } from "@/atom/useSettingsAtom";
import { Button } from "@/components/ui/button";
import { Label } from "@/components/ui/label";
import {
Sheet,
SheetClose,
SheetContent,
SheetDescription,
SheetFooter,
SheetHeader,
SheetTitle,
} from "@/components/ui/sheet";
Expand All @@ -16,11 +14,11 @@ import type { ChartDataType } from "@/types/chartType";
import { useAtom } from "jotai";

const SettingGraphType = () => {
const [settings] = useAtom(settingsAtom);
const { settings, toggleDisplayTarget } = useSettingsAtom();
const selectedGraphTypes = settings.display_targets;

const toggleGraphType = (type: ChartDataType) => {
console.log(type);
const toggleGraphType = async (type: ChartDataType) => {
await toggleDisplayTarget(type);
};

return (
Expand All @@ -35,34 +33,34 @@ const SettingGraphType = () => {
checked={selectedGraphTypes.includes("cpu")}
onChange={() => toggleGraphType("cpu")}
/>
<span>Line Graph</span>
<span>CPU</span>
</label>
<label className="flex items-center space-x-2">
<input
type="checkbox"
checked={selectedGraphTypes.includes("memory")}
onChange={() => toggleGraphType("memory")}
/>
<span>Bar Graph</span>
<span>Memory</span>
</label>
<label className="flex items-center space-x-2">
<input
type="checkbox"
checked={selectedGraphTypes.includes("gpu")}
onChange={() => toggleGraphType("gpu")}
/>
<span>Pie Chart</span>
<span>GPU</span>
</label>
</div>
</div>
);
};

const SettingColorMode = () => {
const [settings] = useAtom(settingsAtom);
const { settings, toggleTheme } = useSettingsAtom();

const toggleDarkMode = (mode: "light" | "dark") => {
console.log(mode);
const toggleDarkMode = async (mode: "light" | "dark") => {
await toggleTheme(mode);
};

return (
Expand Down Expand Up @@ -105,11 +103,6 @@ const SettingsSheet = () => {
<SettingColorMode />
<SettingGraphType />
</div>
<SheetFooter>
<SheetClose asChild>
<Button type="submit">Save changes</Button>
</SheetClose>
</SheetFooter>
</SheetContent>
</Sheet>
);
Expand Down

0 comments on commit afe03fe

Please sign in to comment.