### Rust Tauri Commands for Settings Management Source: https://context7.com/zap-studio/local.ts/llms.txt Backend Tauri commands written in Rust for managing application settings. These commands interact with a database via `DbPool` and use services for fetching and updating settings. They also include a command to control system tray visibility. Dependencies include `tauri`, custom database modules, and services. ```rust use tauri::State; use crate::database::DbPool; use crate::database::models::settings::{Settings, SettingsUpdate}; use crate::services::settings::{get_settings, update_settings}; // Get current settings from database #[tauri::command] pub fn get_app_settings(pool: State<'_, DbPool>) -> Result { let mut conn = pool.get()?; get_settings(&mut conn) } // Update settings with partial data #[tauri::command] pub fn update_app_settings( pool: State<'_, DbPool>, update: SettingsUpdate, ) -> Result { let mut conn = pool.get()?; update_settings(&mut conn, update) } // Control system tray visibility #[tauri::command] pub fn set_tray_visible(tray: State<'_, TrayIcon>, visible: bool) -> Result<(), String> { tray.set_visible(visible).map_err(|e| e.to_string()) } ``` -------------------------------- ### Configure System Tray with Menu and Events (Rust) Source: https://context7.com/zap-studio/local.ts/llms.txt Sets up the system tray icon for the Tauri application, including a custom menu with 'Show', 'Hide', and 'Quit' options. It configures event handlers for menu item clicks and tray icon clicks (left-click to show the main window). The initial visibility of the tray icon can be controlled by application settings. ```rust use tauri::{App, Manager}; use tauri::menu::{Menu, MenuItem}; use tauri::tray::{TrayIconBuilder, TrayIconEvent, MouseButton, MouseButtonState}; pub fn setup(app: &App, pool: &DbPool) -> Result<(), Box> { // Create menu items let show_i = MenuItem::with_id(app, "show", "Show", true, None::<&str>)?; let hide_i = MenuItem::with_id(app, "hide", "Hide", true, None::<&str>)?; let quit_i = MenuItem::with_id(app, "quit", "Quit", true, None::<&str>)?; let menu = Menu::with_items(app, &[&show_i, &hide_i, &quit_i])?; // Build tray icon with handlers let tray = TrayIconBuilder::new() .icon(app.default_window_icon().unwrap().clone()) .menu(&menu) .tooltip("Local.ts") .on_menu_event(|app, event| match event.id.as_ref() { "show" => { if let Some(window) = app.get_webview_window("main") { let _ = window.show(); let _ = window.set_focus(); } } "hide" => { if let Some(window) = app.get_webview_window("main") { let _ = window.hide(); } } "quit" => app.exit(0), _ => {} }) .on_tray_icon_event(|tray, event| { // Left click shows main window if let TrayIconEvent::Click { button: MouseButton::Left, button_state: MouseButtonState::Up, .. } = event { let app = tray.app_handle(); if let Some(window) = app.get_webview_window("main") { let _ = window.show(); let _ = window.set_focus(); } } }) .build(app)?; // Apply initial visibility from settings if let Ok(mut conn) = pool.get() && let Ok(settings) = get_settings(&mut conn) && !settings.show_in_tray { let _ = tray.set_visible(false); } app.manage(tray); Ok(()) } ``` -------------------------------- ### Initialize SQLite Database with Migrations (Rust) Source: https://context7.com/zap-studio/local.ts/llms.txt Sets up a SQLite database connection pool and automatically applies pending migrations using diesel-migrations. It handles database path resolution and connection pooling with a maximum size of 10 connections. Errors during initialization or migration are returned as DbError. ```rust use diesel::r2d2::{self, ConnectionManager}; use diesel::sqlite::SqliteConnection; use diesel_migrations::{embed_migrations, EmbeddedMigrations, MigrationHarness}; use tauri::AppHandle; pub const MIGRATIONS: EmbeddedMigrations = embed_migrations!("migrations"); pub type DbPool = r2d2::Pool>; pub fn init(app: &AppHandle) -> Result { let db_path = get_database_path(app)?; let db_url = db_path.to_string_lossy().to_string(); log::info!("Initializing database at: {}", db_url); // Create connection manager and pool let manager = ConnectionManager::::new(&db_url); let pool = r2d2::Pool::builder() .max_size(10) .build(manager) .map_err(|e| DbError::Init(format!("Failed to create pool: {}", e)))?; // Run pending migrations automatically let mut conn = pool.get()?; conn.run_pending_migrations(MIGRATIONS) .map_err(|e| DbError::Migration(e.to_string()))?; log::info!("Database initialized successfully"); Ok(pool) } ``` -------------------------------- ### Store Initialization Component (TypeScript/TSX) Source: https://context7.com/zap-studio/local.ts/llms.txt A component that initializes Zustand stores on application startup and manages the splash screen. It uses `StoreInitializer` from `@/components/store-initializer`, `RouterProvider` from `@tanstack/react-router`, and `Toaster` from `sonner`. It handles Tauri environment checks, database loading, theme initialization, splash screen dismissal, and error handling. ```typescript import { StoreInitializer } from "@/components/store-initializer"; import { RouterProvider } from "@tanstack/react-router"; import { Toaster } from "sonner"; function App() { return ( ); } // StoreInitializer automatically: // 1. Checks if running in Tauri (not browser) // 2. Loads settings from database // 3. Initializes theme with system preference detection // 4. Closes splash screen and shows main window // 5. Shows error screen with retry on failure ``` -------------------------------- ### Manage Application Settings in TypeScript Source: https://context7.com/zap-studio/local.ts/llms.txt This API allows retrieving and updating application settings stored in an SQLite database. It supports updating multiple settings simultaneously or individually. Dependencies include the settings module from '@ /lib/tauri/settings'. Input is an object of settings to update, and output is the updated settings object. ```typescript import { getSettings, updateSettings } from "@/lib/tauri/settings"; // Get current settings const settings = await getSettings(); console.log(settings); // { // theme: "dark", // sidebarExpanded: true, // showInTray: true, // launchAtLogin: false, // enableLogging: true, // logLevel: "info", // enableNotifications: true // } // Update multiple settings at once const updatedSettings = await updateSettings({ theme: "light", enableNotifications: false, logLevel: "debug" }); // Update single setting const result = await updateSettings({ theme: "system" }); ``` -------------------------------- ### Theme Store Management with Zustand (TypeScript) Source: https://context7.com/zap-studio/local.ts/llms.txt Manages reactive theme settings using Zustand, including detection of system preferences. It relies on a custom `useTheme` hook from `@/stores/theme`. The store exposes current theme, resolved theme, and functions to set the theme to 'light', 'dark', or 'system'. ```typescript import { useTheme } from "@/stores/theme"; function ThemeToggle() { const { theme, resolvedTheme, setTheme } = useTheme(); return (

Current theme: {theme}

Resolved theme: {resolvedTheme}

); } // Initialize theme on app startup (done automatically by StoreInitializer) // const { initialize } = useTheme.getState(); // initialize(); ``` -------------------------------- ### Manage Settings in Database (Rust) Source: https://context7.com/zap-studio/local.ts/llms.txt Provides low-level functions for retrieving and updating application settings stored in the database. It assumes settings are stored at row ID 1. Updates are applied using a changeset, and the function returns the newly updated settings. Requires a mutable SQLite connection. ```rust use diesel::prelude::*; use crate::database::DbError; use crate::database::models::settings::{Settings, SettingsChangeset, SettingsRow, SettingsUpdate}; // Get settings from database (always row ID = 1) pub fn get_settings(conn: &mut SqliteConnection) -> Result { use crate::database::schema::settings::dsl::*; let row = settings .find(1) .select(SettingsRow::as_select()) .first(conn)?; Settings::from_row(row) } // Update settings and return updated version pub fn update_settings( conn: &mut SqliteConnection, update: SettingsUpdate, ) -> Result { use crate::database::schema::settings::dsl::*; let changeset: SettingsChangeset = update.into(); diesel::update(settings.find(1)) .set(&changeset) .execute(conn)?; get_settings(conn) } ``` -------------------------------- ### Async Action Hook for Loading and Notifications (TypeScript) Source: https://context7.com/zap-studio/local.ts/llms.txt A generic hook `useAsyncAction` wraps asynchronous operations, providing loading state and toast notifications for success and error scenarios. It requires the `sonner` library for toast notifications and custom hooks for data fetching and file export. Input is an async function and configuration options; output is the result of the async operation or null. ```typescript import { useAsyncAction } from "@/hooks/use-async-action"; import { toast } from "sonner"; function DataManager() { const [withSaving, isSaving] = useAsyncAction(); const handleExport = async () => { const result = await withSaving( async () => { const data = await fetchData(); await exportToFile(data); return data; }, { successMessage: "Export completed successfully", errorMessage: "Failed to export data", onSuccess: () => console.log("Export done"), onError: () => console.log("Export failed") } ); if (result) { console.log("Exported:", result); } }; return ( ); } ``` -------------------------------- ### Settings Store Management with Zustand (TypeScript) Source: https://context7.com/zap-studio/local.ts/llms.txt Provides global state management for application settings using Zustand. It depends on the `useSettings` hook from `@/stores/settings`. The store handles loading states, current settings, and updating settings. The primary function shown is `updateSettings`, which accepts partial settings data. ```typescript import { useSettings } from "@/stores/settings"; function SettingsDisplay() { const { settings, isLoading, updateSettings } = useSettings(); if (isLoading) return
Loading...
; const toggleLogging = async () => { await updateSettings({ enableLogging: !settings?.enableLogging, logLevel: "debug" }); }; return (

Logging: {settings?.enableLogging ? "On" : "Off"}

Log Level: {settings?.logLevel}

); } ``` -------------------------------- ### Define Settings Type Definitions (TypeScript) Source: https://context7.com/zap-studio/local.ts/llms.txt Defines TypeScript interfaces and types that mirror the Rust backend models for application settings. This includes types for theme, log level, and the complete settings structure, as well as a partial type for updating settings. ```typescript // Theme options export type Theme = "light" | "dark" | "system"; // Log level options export type LogLevel = "error" | "warn" | "info" | "debug" | "trace"; // Complete settings structure export interface Settings { theme: Theme; sidebarExpanded: boolean; showInTray: boolean; launchAtLogin: boolean; enableLogging: boolean; logLevel: LogLevel; enableNotifications: boolean; } // Partial update type export type SettingsUpdate = Partial; ``` -------------------------------- ### Control System Tray Icon Visibility in TypeScript Source: https://context7.com/zap-studio/local.ts/llms.txt Dynamically shows or hides the system tray icon. This function can be used independently or in conjunction with updating the 'showInTray' setting. It takes a boolean argument to determine visibility. Dependencies include the settings module from '@ /lib/tauri/settings'. ```typescript import { setTrayVisible } from "@/lib/tauri/settings"; // Hide the system tray icon await setTrayVisible(false); // Show the system tray icon await setTrayVisible(true); // Combine with settings update await updateSettings({ showInTray: true }); await setTrayVisible(true); ``` -------------------------------- ### React Hook for Settings Management in TypeScript Source: https://context7.com/zap-studio/local.ts/llms.txt A React hook simplifying settings management within React components. It provides loading states, handles optimistic updates, and manages error handling for settings operations. It integrates with Tauri's backend API for settings and notifications. The hook returns various handler functions for different settings and UI elements. ```typescript import { useHandleSettings } from "@/hooks/use-handle-settings"; function SettingsPage() { const { settings, isLoading, isSaving, handleUpdateSetting, handleAutostartChange, handleTrayVisibilityChange, handleNotificationChange } = useHandleSettings(); if (isLoading) return
Loading settings...
; return (
{/* Update theme */} {/* Toggle autostart */} {/* Toggle tray icon */} {/* Toggle notifications (requests permission if enabling) */}
); } ``` -------------------------------- ### Send Native Notifications with TypeScript Source: https://context7.com/zap-studio/local.ts/llms.txt Allows sending native desktop notifications. It supports sending notifications that respect user preferences (respecting settings) and critical notifications that bypass some settings but still require user permission. Dependencies include '@ /lib/tauri/notifications/send' and '@ /lib/tauri/settings'. ```typescript import { notify, notifyForced } from "@/lib/tauri/notifications/send"; import { getSettings } from "@/lib/tauri/settings"; // Send notification respecting user settings const settings = await getSettings(); const sent = await notify( { title: "Task Complete", body: "Your export has finished processing", icon: "/icon.png" }, settings ); if (sent) { console.log("Notification sent successfully"); } else { console.log("Notification blocked by settings or permissions"); } // Send critical notification bypassing settings (still requires permission) const forceSent = await notifyForced({ title: "Critical Alert", body: "System backup required" }); ``` -------------------------------- ### Manage Notification Permissions in TypeScript Source: https://context7.com/zap-studio/local.ts/llms.txt Handles requesting and checking notification permissions. It ensures that notifications can be sent by prompting the user if permission has not been granted. Dependencies include '@ /lib/tauri/notifications/permissions'. The function returns the current permission status ('granted', 'denied', or 'default'). ```typescript import { ensureNotificationPermission } from "@/lib/tauri/notifications/permissions"; // Check and request permission if needed const permission = await ensureNotificationPermission(); if (permission === "granted") { console.log("Ready to send notifications"); } else { console.log("User denied notification permission"); } ``` === COMPLETE CONTENT === This response contains all available snippets from this library. No additional content exists. Do not make further requests.