### Bundle Analysis Setup Source: https://github.com/kvnxiao/tauri-tanstack-start-react-template/blob/main/_autodocs/performance.md Install and configure vite-plugin-visualizer to analyze bundle sizes. After building, open the generated stats.html file for an interactive visualization. ```bash # Install size analyzer pnpm add -D vite-plugin-visualizer # Add to vite.config.ts import { visualizer } from 'vite-plugin-visualizer'; plugins: [ visualizer(), // ... ] # Build and view pnpm build:vite open dist/stats.html ``` -------------------------------- ### Start Development Server Source: https://github.com/kvnxiao/tauri-tanstack-start-react-template/blob/main/_autodocs/README.md Starts the Vite development server and launches the Tauri webview window. This command enables hot module reloading and requires the Rust binary to compile separately. ```bash pnpm tauri dev ``` -------------------------------- ### Responsive Design Mobile-First Example Source: https://github.com/kvnxiao/tauri-tanstack-start-react-template/blob/main/_autodocs/api-reference/styling.md Illustrates the mobile-first approach to responsive design. Styles are applied starting with the smallest screens, and breakpoints are used to progressively enhance the design for larger screens. ```typescript // Good: Start with mobile, add breakpoints
Text
// Avoid: Desktop-first overrides
Text
``` -------------------------------- ### Production Build Output Source: https://github.com/kvnxiao/tauri-tanstack-start-react-template/blob/main/_autodocs/build-system.md Shows the directory structure and installer artifacts generated after a production build. This includes frontend assets in `.output/public/` and platform-specific installers (DMG, MSI, AppImage) in `src-tauri/target/release/bundle/`. ```text project-root/ ├── .output/ │ └── public/ # Frontend assets ├── src-tauri/ │ ├── target/ │ │ └── release/ │ │ └── bundle/ │ │ ├── dmg/ # macOS DMG installer │ │ ├── msi/ # Windows MSI installer │ │ └── appimage/ # Linux AppImage │ └── [Rust source] └── [Node dependencies and config] ``` -------------------------------- ### Usage Example for getRouter() Source: https://github.com/kvnxiao/tauri-tanstack-start-react-template/blob/main/_autodocs/api-reference/router.md Demonstrates how to import and use the getRouter() function to obtain a router instance and integrate it with the RouterProvider for application routing. ```typescript import { getRouter } from "./router"; const router = getRouter(); // Use router in your application export const App = () => { return {/* content */}; }; ``` -------------------------------- ### Build Tauri Application for Release Source: https://github.com/kvnxiao/tauri-tanstack-start-react-template/blob/main/README.md Compiles the TanStack Start frontend and packages the Tauri application for a production release. ```shell pnpm tauri build ``` -------------------------------- ### Run Tauri Development Server Source: https://github.com/kvnxiao/tauri-tanstack-start-react-template/blob/main/README.md Starts the development server and opens the application in a Tauri window. Also launches a separate development server on localhost:3000. ```shell pnpm tauri dev ``` -------------------------------- ### Type-Safe Path Example Source: https://github.com/kvnxiao/tauri-tanstack-start-react-template/blob/main/_autodocs/api-reference/tanstack-router.md Demonstrates the recommended way to use type-safe paths with the Link component. Avoid using string variables for paths. ```typescript // Good Home // Avoid const path = "/home"; Home ``` -------------------------------- ### Frontend Usage of Tauri 'greet' Command Source: https://github.com/kvnxiao/tauri-tanstack-start-react-template/blob/main/_autodocs/api-reference/tauri-commands.md Demonstrates how to invoke the 'greet' command from the frontend using the `invoke` function from `@tauri-apps/api/core`. Includes examples using async/await with error handling and Promise-based .then()/.catch(). ```typescript import { invoke } from "@tauri-apps/api/core"; // Call the greet command const result = await invoke("greet"); console.log(result); // "Hello world from Rust! Current epoch: 1719878400000" // With error handling try { const greeting = await invoke("greet"); console.log("Greeting:", greeting); } catch (error) { console.error("Failed to greet:", error); } // Using .then()/.catch() invoke("greet") .then((greeting) => console.log(greeting)) .catch((error) => console.error(error)); ``` -------------------------------- ### Unit Test Setup Imports Source: https://github.com/kvnxiao/tauri-tanstack-start-react-template/blob/main/_autodocs/testing.md These imports are necessary for setting up unit tests with Vitest and Testing Library. They provide functions for rendering components, simulating events, and managing test environments. ```typescript import { cleanup, fireEvent, render, screen } from "@testing-library/react"; import { afterEach, describe, expect, it, vi } from "vitest"; ``` -------------------------------- ### CI/CD GitHub Actions for Testing Source: https://github.com/kvnxiao/tauri-tanstack-start-react-template/blob/main/_autodocs/testing.md Example GitHub Actions workflow steps for running tests and generating code coverage reports. These steps ensure code quality and adherence to coverage thresholds. ```yaml - name: Run tests run: pnpm test - name: Generate coverage run: pnpm test --coverage ``` -------------------------------- ### Tauri Configuration - Bundle Settings Source: https://github.com/kvnxiao/tauri-tanstack-start-react-template/blob/main/_autodocs/configuration.md Enables platform-specific binary bundling and installer generation. 'targets' can be set to 'all' for cross-platform support. The 'icon' property specifies branding assets. ```json { "bundle": { "active": true, "targets": "all", "icon": [ "icons/32x32.png", "icons/128x128.png", "icons/128x128@2x.png", "icons/icon.icns", "icons/icon.ico" ] } } ``` -------------------------------- ### Tauri Command Invocation Source: https://github.com/kvnxiao/tauri-tanstack-start-react-template/blob/main/_autodocs/api-reference/routes.md Example of how to invoke a Tauri command named 'greet' from the frontend. It handles both successful responses and potential errors. ```typescript invoke("greet") .then((response) => { console.log(response); // "Hello world from Rust! Current epoch: 1719878400000" }) .catch((error) => { console.error("Command failed:", error); }); ``` -------------------------------- ### Vite Code Splitting Example Source: https://github.com/kvnxiao/tauri-tanstack-start-react-template/blob/main/_autodocs/performance.md Vite automatically splits code into main and chunk bundles for lazy loading. This example shows the typical output structure. ```javascript // Vite generates: index.html (2KB) _assets/index-xxxxx.js (main bundle) _assets/chunk-yyyyy.js (lazy-loaded component) _assets/chunk-zzzzz.js (dependency) ``` -------------------------------- ### Utility-First Approach Example Source: https://github.com/kvnxiao/tauri-tanstack-start-react-template/blob/main/_autodocs/api-reference/styling.md Demonstrates the recommended utility-first approach using Tailwind CSS classes for styling elements directly within JSX. Avoids custom CSS classes for better maintainability and consistency. ```typescript // Good: Use Tailwind utilities // Avoid: Custom CSS classes const styles = css` background-color: #3b82f6; color: white; padding: 0.5rem 1rem; border-radius: 0.25rem; `; ``` -------------------------------- ### Vitest Configuration in vite.config.ts Source: https://github.com/kvnxiao/tauri-tanstack-start-react-template/blob/main/_autodocs/testing.md Configure Vitest by adding test-specific settings to your vite.config.ts file. This example enables global test functions, sets the environment to jsdom, specifies a setup file, and defines which files should be included in tests. ```typescript export default defineConfig({ test: { globals: true, environment: "jsdom", setupFiles: ["./tests/setup.ts"], include: ["src/**/*.{test,spec}.{ts,tsx}"], }, }); ``` -------------------------------- ### Full React Component with Tauri Command Source: https://github.com/kvnxiao/tauri-tanstack-start-react-template/blob/main/_autodocs/api-reference/tauri-integration.md A complete React component example that integrates the 'greet' Tauri command. It includes state management for messages and errors, a button to trigger the command, and displays the result or any errors encountered. ```typescript import { invoke } from "@tauri-apps/api/core"; import { useState, useCallback } from "react"; export const MyComponent = () => { const [message, setMessage] = useState(null); const [error, setError] = useState(null); const handleGreet = useCallback(async () => { try { const result = await invoke("greet"); setMessage(result); setError(null); } catch (err) { setError(String(err)); setMessage(null); } }, []); return (
{message &&

Message: {message}

} {error &&

Error: {error}

}
); }; ``` -------------------------------- ### Rust Command Handler Source: https://github.com/kvnxiao/tauri-tanstack-start-react-template/blob/main/_autodocs/PROJECT_OVERVIEW.md Example of a Rust function decorated with the `#[tauri::command]` macro, making it callable from the frontend via IPC. ```rust #[tauri::command] fn greet() -> string { string::from("Hello") } ``` -------------------------------- ### Handling Loading States Source: https://github.com/kvnxiao/tauri-tanstack-start-react-template/blob/main/_autodocs/api-reference/tanstack-router.md Provides an example of how to display a loading indicator while a route is pending. It uses the useRouterState hook to check the pending status. ```typescript import { useRouterState } from "@tanstack/react-router"; const LoadingIndicator = () => { const state = useRouterState(); if (state.isPending) return ; return null; }; ``` -------------------------------- ### Self-Hosted Font Optimization Source: https://github.com/kvnxiao/tauri-tanstack-start-react-template/blob/main/_autodocs/performance.md Example of importing self-hosted variable fonts using @fontsource-variable. This approach bundles the font, avoiding network requests. ```css /* Current: Self-hosted variable fonts */ @import "@fontsource-variable/inter"; /* Font is bundled (no network request) */ ``` -------------------------------- ### Nested Route Example Source: https://github.com/kvnxiao/tauri-tanstack-start-react-template/blob/main/_autodocs/api-reference/routes.md Illustrates how to create a nested route, such as an 'about' route, which will be rendered within the of the RootComponent. Requires importing RootComponent and Route. ```typescript import { RootComponent, Route } from "@/routes/__root"; // Nested routes automatically appear under RootComponent // Example: src/routes/about.tsx would render inside export const AboutRoute = createFileRoute("/about")({ component: About, }); ``` -------------------------------- ### Semantic Color Variables Example Source: https://github.com/kvnxiao/tauri-tanstack-start-react-template/blob/main/_autodocs/api-reference/styling.md Shows how to use semantic color variables for defining and applying colors. This improves readability and maintainability by using descriptive names for colors like `--foreground` and `--background`. ```typescript // In styles.css :root { --foreground: #171717; // Semantic name --background: #ffffff; // Semantic name } // In components
Text
// Or with className (using Tailwind)
Text
``` -------------------------------- ### useRouter Hook Source: https://github.com/kvnxiao/tauri-tanstack-start-react-template/blob/main/_autodocs/api-reference/tanstack-router.md Provides access to the router instance, allowing you to get information like the current path and history. ```APIDOC ## `useRouter` Access the router instance: ```typescript import { useRouter } from "@tanstack/react-router"; const MyComponent = () => { const router = useRouter(); const current = router.state.location.pathname; // Current path const history = router.history; return
Current page: {current}
; }; ``` ``` -------------------------------- ### Using Promise for Async Operations Source: https://github.com/kvnxiao/tauri-tanstack-start-react-template/blob/main/_autodocs/types.md Demonstrates how to handle an asynchronous operation that resolves to a specific type using Promise. The example shows invoking a command and processing its string result. ```typescript const greet = useCallback((): void => { invoke("greet") // Promise .then((s) => { setGreeted(s); // s is string }); }, []); ``` -------------------------------- ### useState Hook Example Source: https://github.com/kvnxiao/tauri-tanstack-start-react-template/blob/main/_autodocs/types.md Demonstrates the usage of the `useState` hook from React to manage state. The generic parameter specifies the type of the state value. ```typescript const [greeted, setGreeted] = useState(null); // Type: [greeted: string | null, setGreeted: (value: string | null) => void] ``` -------------------------------- ### Rust Command Registration Source: https://github.com/kvnxiao/tauri-tanstack-start-react-template/blob/main/_autodocs/PROJECT_OVERVIEW.md Example of registering commands in Rust using `tauri::generate_handler!`. This makes the specified commands available for frontend invocation. ```rust tauri::generate_handler![ greet ] ``` -------------------------------- ### Image Optimization with Lazy Loading Source: https://github.com/kvnxiao/tauri-tanstack-start-react-template/blob/main/_autodocs/performance.md Example of an image tag with lazy loading enabled. Specify width and height to prevent layout shifts. ```typescript Logo ``` -------------------------------- ### Responsive Button Height and Text Size Source: https://github.com/kvnxiao/tauri-tanstack-start-react-template/blob/main/_autodocs/api-reference/styling.md This example demonstrates responsive styling for a button's height and text size using Tailwind CSS prefixes. The `h-10` and `text-sm` classes apply to mobile-first, while `sm:h-12` and `sm:text-base` apply from the 'sm' breakpoint upwards. ```html ``` -------------------------------- ### Dynamic Route Segment with Multiple Parameters Source: https://github.com/kvnxiao/tauri-tanstack-start-react-template/blob/main/_autodocs/api-reference/tanstack-router.md Handle routes with multiple dynamic segments by using the '$paramName' syntax for each segment in the file path. This example defines a route for a user's posts. ```typescript export const UserPost: React.FC = () => { const { userId, postId } = Route.useParams(); return
User {userId}, Post {postId}
; }; ``` -------------------------------- ### Frontend IPC Command Invocation Source: https://github.com/kvnxiao/tauri-tanstack-start-react-template/blob/main/_autodocs/PROJECT_OVERVIEW.md Example of how the frontend invokes a command on the Rust backend using Tauri's `invoke` function. Ensure the command name and expected return type are correctly specified. ```typescript invoke("greet") ``` -------------------------------- ### Build Production Application Source: https://github.com/kvnxiao/tauri-tanstack-start-react-template/blob/main/_autodocs/PROJECT_OVERVIEW.md Use this script to create a production build of the application, including both the frontend and the Rust backend binary. ```bash tauri build ``` -------------------------------- ### Preview Production Build Source: https://github.com/kvnxiao/tauri-tanstack-start-react-template/blob/main/_autodocs/PROJECT_OVERVIEW.md Use this script to locally preview the production build of the application. This helps in testing the final output before deployment. ```bash vite preview ``` -------------------------------- ### React.ReactElement Type for JSX Elements Source: https://github.com/kvnxiao/tauri-tanstack-start-react-template/blob/main/_autodocs/types.md Example of typing a JSX element using React.ReactElement, representing a virtual DOM element. ```typescript const element: React.ReactElement =
Content
; ``` -------------------------------- ### Build Frontend with Vite Source: https://github.com/kvnxiao/tauri-tanstack-start-react-template/blob/main/_autodocs/performance.md Execute the Vite build command to create a production-ready frontend application. Build times vary depending on whether it's a Single Page Application (SPA) or Server-Side Rendering (SSR). ```bash pnpm build:vite # SPA: ~5-15s # SSR: ~10-30s (depends on route count) ``` -------------------------------- ### Development Build Output Source: https://github.com/kvnxiao/tauri-tanstack-start-react-template/blob/main/_autodocs/build-system.md Illustrates the directory structure and key files generated after a development build. Includes the frontend SPA entry point, bundled assets, and the debug binary for the Rust backend. ```text project-root/ ├── .output/ │ └── public/ │ ├── index.html # SPA entry point │ ├── _assets/ # Bundled JS/CSS │ └── [other assets] ├── src-tauri/ │ ├── target/ │ │ └── debug/ │ │ └── tauri_tanstack_start_react_template_lib # Debug binary │ └── [Rust source] └── [Node dependencies and config] ``` -------------------------------- ### Run Unit Tests Source: https://github.com/kvnxiao/tauri-tanstack-start-react-template/blob/main/_autodocs/PROJECT_OVERVIEW.md Use this script to execute the unit tests for the project using Vitest. ```bash vitest run ``` -------------------------------- ### useCallback Hook Example Source: https://github.com/kvnxiao/tauri-tanstack-start-react-template/blob/main/_autodocs/types.md Illustrates the `useCallback` hook from React for memoizing callback functions. The generic parameter defines the type of the callback function. ```typescript const greet = useCallback((): void => { // callback implementation }, []); // Type: () => void ``` -------------------------------- ### Mock a Module Partially Source: https://github.com/kvnxiao/tauri-tanstack-start-react-template/blob/main/_autodocs/testing.md To mock only specific exports from a module, use `vi.importActual` to get the original module and then override individual exports with mocks. ```typescript vi.mock("@tauri-apps/api/core", async () => { const actual = await vi.importActual("@tauri-apps/api/core"); return { ...actual, invoke: vi.fn(), // Override just invoke }; }); ``` -------------------------------- ### Run Project Tests Source: https://github.com/kvnxiao/tauri-tanstack-start-react-template/blob/main/README.md Executes the unit tests for the project using the configured testing framework. ```shell pnpm test ``` -------------------------------- ### Run Tauri Development Server Source: https://github.com/kvnxiao/tauri-tanstack-start-react-template/blob/main/_autodocs/PROJECT_OVERVIEW.md Use this script to run both the frontend and backend within the Tauri webview for full-stack development. ```bash tauri dev ``` -------------------------------- ### Test Router Navigation Source: https://github.com/kvnxiao/tauri-tanstack-start-react-template/blob/main/_autodocs/testing.md This snippet demonstrates how to test router navigation by creating a router instance and verifying its initial state. ```typescript import { createRouter } from "@tanstack/react-router"; import { getRouter } from "@/router"; describe("Router", () => { it("creates router with route tree", () => { const router = getRouter(); expect(router).toBeDefined(); expect(router.state.location.pathname).toBe("/"); }); }); ``` -------------------------------- ### Vite Build Commands Source: https://github.com/kvnxiao/tauri-tanstack-start-react-template/blob/main/_autodocs/build-system.md Commands for managing the Vite development server, production build, and previewing the production build. ```bash # Development server (Vite) pnpm dev:vite ``` ```bash # Production build pnpm build:vite ``` ```bash # Preview production build pnpm preview ``` -------------------------------- ### RoundedButton Usage Example Source: https://github.com/kvnxiao/tauri-tanstack-start-react-template/blob/main/_autodocs/api-reference/RoundedButton.md Demonstrates how to import and use the RoundedButton component in another React component. It includes a sample click handler and passes the title prop. ```typescript import { RoundedButton } from "@/components/RoundedButton"; export const MyComponent = () => { const handleClick = () => { console.log("Button clicked!"); }; return ( ); }; ``` -------------------------------- ### Test Edge Cases in Forms Source: https://github.com/kvnxiao/tauri-tanstack-start-react-template/blob/main/_autodocs/testing.md Provides examples of test cases for a form component, including handling empty submissions, trimming whitespace, and managing loading states. ```typescript describe("Form", () => { it("shows error for empty submission", () => { // Test empty input }); it("trims whitespace from input", () => { // Test whitespace handling }); it("disables submit while processing", () => { // Test loading state }); }); ``` -------------------------------- ### Create TanStack Router Instance Source: https://github.com/kvnxiao/tauri-tanstack-start-react-template/blob/main/_autodocs/api-reference/router.md This function initializes the router with the auto-generated route tree and essential configurations. It should be used to obtain the router instance for application-wide routing. ```typescript export const getRouter = () => { const router = createRouter({ routeTree, context: {}, scrollRestoration: true, defaultPreloadStaleTime: 0, }); return router; }; ``` -------------------------------- ### Tauri Configuration - Build Settings Source: https://github.com/kvnxiao/tauri-tanstack-start-react-template/blob/main/_autodocs/configuration.md Configures the build process, including commands to run before development and production builds, and the location of frontend assets. Ensure 'devUrl' matches the Vite server port. ```json { "build": { "beforeDevCommand": "pnpm dev:vite", "devUrl": "http://localhost:3000", "beforeBuildCommand": "pnpm build:vite", "frontendDist": "../.output/public" } } ``` -------------------------------- ### Tauri Configuration - Main Window Settings Source: https://github.com/kvnxiao/tauri-tanstack-start-react-template/blob/main/_autodocs/configuration.md Defines the properties of the application's main window, including its title and initial dimensions. Additional properties like minimum/maximum size and resizability can also be configured. ```json { "app": { "windows": [ { "title": "tauri-tanstack-start-react-template", "width": 800, "height": 600 } ] } } ``` -------------------------------- ### Register Tauri Commands in Rust Source: https://github.com/kvnxiao/tauri-tanstack-start-react-template/blob/main/_autodocs/api-reference/tauri-commands.md Register the `greet` function as an IPC command in your Tauri application's `src-tauri/src/lib.rs` file. Ensure the `greet` function is defined elsewhere in your Rust code. ```rust pub fn run() { tauri::Builder::default() .plugin(tauri_plugin_opener::init()) .invoke_handler(tauri::generate_handler![greet]) .run(tauri::generate_context!()) .expect("error while running tauri application"); } ``` -------------------------------- ### greet Command Source: https://github.com/kvnxiao/tauri-tanstack-start-react-template/blob/main/_autodocs/api-reference/tauri-commands.md A simple command that returns a greeting from the Rust backend with the current system time. Demonstrates the Tauri IPC bridge between the React frontend and Rust backend. ```APIDOC ## greet Command ### Description A simple command that returns a greeting from the Rust backend with the current system time. Demonstrates the Tauri IPC bridge between the React frontend and Rust backend. The function captures the current system time using `SystemTime::now()`, calculates the duration since the Unix epoch, and formats a response string with the millisecond value. ### Signature ```rust #[tauri::command] fn greet() -> String { // ... implementation ... } ``` ### Parameters None ### Return Type `String` — A formatted greeting message containing the current Unix timestamp in milliseconds. **Format:** `"Hello world from Rust! Current epoch: {milliseconds}"` **Example Return Value:** `"Hello world from Rust! Current epoch: 1719878400000"` ### Frontend Usage ```typescript import { invoke } from "@tauri-apps/api/core"; // Call the greet command const result = await invoke("greet"); console.log(result); // "Hello world from Rust! Current epoch: 1719878400000" // With error handling try { const greeting = await invoke("greet"); console.log("Greeting:", greeting); } catch (error) { console.error("Failed to greet:", error); } // Using .then()/.catch() invoke("greet") .then((greeting) => console.log(greeting)) .catch((error) => console.error(error)); ``` ### Errors **Panic Condition:** If `duration_since(UNIX_EPOCH)` returns an error (system clock before 1970), the `unwrap()` will panic. This is considered acceptable for this command because system clocks should never be before the Unix epoch in normal operation. ``` -------------------------------- ### Complete Global Styles File Source: https://github.com/kvnxiao/tauri-tanstack-start-react-template/blob/main/_autodocs/api-reference/styling.md This is the complete `src/styles.css` file, encompassing all imports, theme configurations, and base styles for the application. ```css @import "tailwindcss"; @import "@fontsource-variable/inter"; @import "@fontsource-variable/jetbrains-mono"; @theme { --font-sans: "Inter Variable", sans-serif; --font-mono: "JetBrains Mono Variable", monospace; } :root { --background: #ffffff; --foreground: #171717; --font-inter-sans: "Inter Variable", sans-serif; --font-jetbrains-mono: "JetBrains Mono Variable", monospace; } @media (prefers-color-scheme: dark) { :root { --background: #0a0a0a; --foreground: #ededed; } } body { color: var(--foreground); background: var(--background); font-family: var(--font-inter-sans); margin: 0; -webkit-font-smoothing: antialiased; -moz-osx-font-smoothing: grayscale; } code { font-family: var(--font-jetbrains-mono); } ``` -------------------------------- ### Dynamic Route Segment with Single Parameter Source: https://github.com/kvnxiao/tauri-tanstack-start-react-template/blob/main/_autodocs/api-reference/tanstack-router.md Define dynamic route segments using the '$paramName' syntax in your route file names. This example shows a route for a single blog post ID. ```typescript export const BlogPost: React.FC = () => { const { postId } = Route.useParams(); return
Post ID: {postId}
; }; export const Route = createFileRoute("/blog/$postId")({ component: BlogPost, }); ``` -------------------------------- ### Build Production Binaries for Release Source: https://github.com/kvnxiao/tauri-tanstack-start-react-template/blob/main/_autodocs/README.md Commands to build production binaries for the Tauri application. Ensure the app identifier in `src-tauri/tauri.conf.json` is changed for release builds. ```bash # Change app identifier (required for release) # Edit: src-tauri/tauri.conf.json # Change: "identifier": "com.tauri.deva" → "com.your-company.app-name" # Build production binaries pnpm tauri build # Outputs appear in: src-tauri/target/release/bundle/ # - macOS: .dmg installer # - Windows: .msi installer # - Linux: .AppImage bundle ``` -------------------------------- ### Router Initialization with TanStack Router Source: https://github.com/kvnxiao/tauri-tanstack-start-react-template/blob/main/_autodocs/api-reference/tanstack-router.md This snippet shows how to create and configure a TanStack Router instance using the `createRouter` factory function. It utilizes the auto-generated `routeTree` and sets up essential configurations like context and scroll restoration. ```typescript import { createRouter } from "@tanstack/react-router"; import { routeTree } from "./routeTree.gen"; export const getRouter = () => { const router = createRouter({ routeTree, context: {}, scrollRestoration: true, defaultPreloadStaleTime: 0, }); return router; }; ``` -------------------------------- ### Initialize Tauri Opener Plugin Source: https://github.com/kvnxiao/tauri-tanstack-start-react-template/blob/main/_autodocs/api-reference/tauri-integration.md Initialize the `tauri_plugin_opener` plugin in your Tauri application's main function. This enables OS-level integrations for opening external resources. ```rust .plugin(tauri_plugin_opener::init()) ``` -------------------------------- ### Complete Unit Test Suite for RoundedButton Source: https://github.com/kvnxiao/tauri-tanstack-start-react-template/blob/main/_autodocs/testing.md This is a complete test suite for the RoundedButton component. It includes setup, cleanup, and two test cases: one for rendering with a title and another for verifying the onClick handler. ```typescript import { cleanup, fireEvent, render, screen } from "@testing-library/react"; import { afterEach, describe, expect, it, vi } from "vitest"; import { RoundedButton } from "./RoundedButton"; afterEach(() => { cleanup(); }); describe("RoundedButton", () => { it("renders with the provided title", () => { render( {}} title="Click me" />); expect(screen.getByRole("button", { name: "Click me" })).toBeDefined(); }); it("calls onClick when clicked", () => { const handleClick = vi.fn(); render(); fireEvent.click(screen.getByRole("button")); expect(handleClick).toHaveBeenCalledTimes(1); }); }); ``` -------------------------------- ### Rust Backend Command Definition Source: https://github.com/kvnxiao/tauri-tanstack-start-react-template/blob/main/_autodocs/api-reference/tauri-commands.md Defines a simple 'greet' command in Rust that returns a greeting string with the current Unix epoch time in milliseconds. This function is intended to be called from the frontend via Tauri's IPC. ```rust #[tauri::command] fn greet() -> String { let now = SystemTime::now(); let epoch_ms = now.duration_since(UNIX_EPOCH).unwrap().as_millis(); format!("Hello world from Rust! Current epoch: {epoch_ms}") } ``` -------------------------------- ### Initialize Web Vitals Metrics Source: https://github.com/kvnxiao/tauri-tanstack-start-react-template/blob/main/_autodocs/performance.md Import and initialize core Web Vitals metrics (CLS, FID, FCP, LCP, TTFB) using the web-vitals package. These metrics help in understanding the user experience related to loading performance. ```typescript import { getCLS, getFID, getFCP, getLCP, getTTFB } from "web-vitals"; getCLS(console.log); // Cumulative Layout Shift getFID(console.log); // First Input Delay getFCP(console.log); // First Contentful Paint getLCP(console.log); // Largest Contentful Paint getTTFB(console.log); // Time to First Byte ``` -------------------------------- ### Tauri Configuration (`tauri.conf.json`) Source: https://github.com/kvnxiao/tauri-tanstack-start-react-template/blob/main/_autodocs/PROJECT_OVERVIEW.md Defines essential application settings such as the app identifier, window properties, and frontend build output. ```json { "identifier": "com.tauri.deva", "window": { "title": "tauri-tanstack-start-react-template", "width": 800, "height": 600 }, "build": { "distDir": ".output/public", "devUrl": "http://localhost:3000" } } ``` -------------------------------- ### Configure Tailwind CSS Vite Plugin Source: https://github.com/kvnxiao/tauri-tanstack-start-react-template/blob/main/_autodocs/api-reference/styling.md Integrates Tailwind CSS into Vite for efficient styling. Ensure the package `@tailwindcss/vite` is installed. This plugin compiles directives, scans for class usage, and generates only necessary classes for tree-shaking. ```typescript import tailwindcss from "@tailwindcss/vite"; export default defineConfig({ plugins: [ tailwindcss(), // ... other plugins ], }); ``` -------------------------------- ### Build SPA Mode Source: https://github.com/kvnxiao/tauri-tanstack-start-react-template/blob/main/_autodocs/configuration.md Builds the project in Single Page Application (SPA) mode, which is the default behavior. This generates a single HTML file for the application. ```bash pnpm tauri build ``` -------------------------------- ### Mock Tauri API for Component Testing Source: https://github.com/kvnxiao/tauri-tanstack-start-react-template/blob/main/_autodocs/testing.md When testing components that utilize Tauri's `invoke()` function, mock the Tauri API to isolate your component. This example demonstrates mocking the `invoke` function and asserting its calls and return values. ```typescript import { invoke } from "@tauri-apps/api/core"; import { vi } from "vitest"; vi.mock("@tauri-apps/api/core"); describe("Home Component", () => { it("calls greet command on button click", async () => { const mockInvoke = vi.mocked(invoke); mockInvoke.mockResolvedValue("Hello from Rust!"); render(); const button = screen.getByRole("button"); fireEvent.click(button); // Wait for promise await vi.waitFor(() => { expect(mockInvoke).toHaveBeenCalledWith("greet"); }); // Check that response is displayed expect(screen.getByText("Hello from Rust!")).toBeDefined(); }); }); ``` -------------------------------- ### Project Structure Source: https://github.com/kvnxiao/tauri-tanstack-start-react-template/blob/main/_autodocs/PROJECT_OVERVIEW.md Illustrates the directory layout for the frontend (TypeScript React) and backend (Rust Tauri). ```tree tauri-tanstack-start-react-template/ ├── src/ # TypeScript React frontend │ ├── components/ # Reusable React components │ │ ├── RoundedButton.tsx # Button component │ │ └── RoundedButton.test.tsx │ ├── routes/ # TanStack Router file-based routes │ │ ├── __root.tsx # Root layout │ │ └── index.tsx # Home page (/) │ ├── router.tsx # Router initialization │ ├── routeTree.gen.ts # Auto-generated route tree (do not edit) │ └── styles.css # Global styles + Tailwind imports ├── src-tauri/ # Rust Tauri backend │ ├── src/ │ │ ├── lib.rs # Library with Tauri command handlers │ │ └── main.rs # Binary entry point │ ├── Cargo.toml # Rust dependencies │ ├── tauri.conf.json # Tauri app configuration │ └── capabilities/ # Permission definitions ├── package.json # Node dependencies ├── tsconfig.json # TypeScript configuration ├── vite.config.ts # Vite/TanStack Start build config ├── biome.json # Code formatting & linting rules └── README.md ``` -------------------------------- ### Tauri Application Entry Point Source: https://github.com/kvnxiao/tauri-tanstack-start-react-template/blob/main/_autodocs/module-graph.md The main function for the Tauri desktop application. It calls the run function from the library crate. ```rust #![cfg_attr(not(debug_assertions), windows_subsystem = "windows")] fn main() { tauri_tanstack_start_react_template_lib::run() } ``` -------------------------------- ### Use Semantic Queries for Testing Source: https://github.com/kvnxiao/tauri-tanstack-start-react-template/blob/main/_autodocs/testing.md Illustrates using semantic queries like `getByRole` and `getByLabelText` for more robust tests, while advising against querying by CSS class or ID. ```typescript // Good: Query by role (how users interact) screen.getByRole("button", { name: "Submit" }); // Acceptable: Query by label for inputs screen.getByLabelText("Email"); // Avoid: Query by CSS class or ID screen.getByClassName("submit-button"); screen.getByTestId("submit"); ``` -------------------------------- ### Format Rust Code Source: https://github.com/kvnxiao/tauri-tanstack-start-react-template/blob/main/_autodocs/build-system.md Run this command to format your Rust code according to the project's style guidelines. It uses the `rustfmt` tool. ```bash cargo fmt ``` -------------------------------- ### Import Variable Fonts Source: https://github.com/kvnxiao/tauri-tanstack-start-react-template/blob/main/_autodocs/api-reference/styling.md Self-hosts Inter (sans-serif) and JetBrains Mono (monospace) variable fonts for UI text and code, respectively. This avoids external CDN dependencies. ```css @import "@fontsource-variable/inter"; @import "@fontsource-variable/jetbrains-mono"; ``` -------------------------------- ### Build Frontend Only Source: https://github.com/kvnxiao/tauri-tanstack-start-react-template/blob/main/_autodocs/PROJECT_OVERVIEW.md Use this script to build only the frontend assets using Vite. This is useful for frontend-only deployment or analysis. ```bash vite build ``` -------------------------------- ### Tauri Configuration - Top-Level Properties Source: https://github.com/kvnxiao/tauri-tanstack-start-react-template/blob/main/_autodocs/configuration.md Defines essential application metadata like product name, version, and a unique identifier. The 'identifier' must be changed for distribution. ```json { "$schema": "https://schema.tauri.app/config/2", "productName": "tauri-tanstack-start-react-template", "version": "0.1.0", "identifier": "com.tauri.deva" } ``` -------------------------------- ### Mock a Basic Function Source: https://github.com/kvnxiao/tauri-tanstack-start-react-template/blob/main/_autodocs/testing.md Use `vi.fn()` to create a mock function. You can optionally provide a return value. ```typescript import { vi } from "vitest"; const mockFunction = vi.fn(); const mockFunctionWithReturn = vi.fn(() => "return value"); ``` -------------------------------- ### Run Vite Frontend Development Server Source: https://github.com/kvnxiao/tauri-tanstack-start-react-template/blob/main/_autodocs/PROJECT_OVERVIEW.md Use this script to run only the frontend development server using Vite. This is useful for frontend-only development or debugging. ```bash vite dev --port 3000 ``` -------------------------------- ### Build Rust Backend with Cargo Source: https://github.com/kvnxiao/tauri-tanstack-start-react-template/blob/main/_autodocs/performance.md Compile the Rust backend for a Tauri application in release mode using Cargo. The initial build can take longer due to optimizations, but subsequent incremental builds are significantly faster. ```bash cd src-tauri && cargo build --release # First: ~30-60s # Incremental: <10s ``` -------------------------------- ### getRouter() Source: https://github.com/kvnxiao/tauri-tanstack-start-react-template/blob/main/_autodocs/api-reference/router.md Creates and returns a configured TanStack Router instance for the application. This function initializes the router with the auto-generated route tree and can be extended with type-safe context. ```APIDOC ## `getRouter()` ### Description Creates and returns a configured TanStack Router instance for the application. ### Signature ```typescript export const getRouter = () => { const router = createRouter({ routeTree, context: {}, scrollRestoration: true, defaultPreloadStaleTime: 0, }); return router; }; ``` ### Parameters None ### Return Type `Router` — A TanStack Router instance configured with: | Option | Type | Value | Description | |--------|------|-------|-------------| | `routeTree` | RouteTree | Auto-generated from `routeTree.gen.ts` | Hierarchical route configuration with all routes from `src/routes/*` | | `context` | object | `{}` | Empty context object (can be extended with type-safe context) | | `scrollRestoration` | boolean | `true` | Restores scroll position when navigating back | | `defaultPreloadStaleTime` | number | `0` | Preloads stale routes immediately (0ms delay) | ### Description This factory function initializes the router with the auto-generated route tree. The router instance should be used with TanStack Router's provider components to enable routing throughout the application. The empty `context` object serves as a foundation for passing global state or utilities to route loaders and components. It can be extended by modifying the `createRouter` call. ### Usage Example ```typescript import { getRouter } from "./router"; const router = getRouter(); // Use router in your application export const App = () => { return {/* content */}; }; ``` ``` -------------------------------- ### Run Project Tests Source: https://github.com/kvnxiao/tauri-tanstack-start-react-template/blob/main/_autodocs/README.md Executes the Vitest test runner to discover and run test files. Components are rendered using Testing Library. ```bash pnpm test ``` -------------------------------- ### Vite Configuration (`vite.config.ts`) Source: https://github.com/kvnxiao/tauri-tanstack-start-react-template/blob/main/_autodocs/PROJECT_OVERVIEW.md Configures the Vite build process, including the development server port and SSR prerendering behavior. ```typescript import { defineConfig } from 'vite'; import react from '@vitejs/plugin-react'; import { TanStackRouterVite } from '@tanstack/router-vite-plugin'; // https://vitejs.dev/config/ export default defineConfig({ plugins: [ react(), TanStackRouterVite({ // Use SSR prerender mode if USE_SSR_PRERENDER_MODE env var is set to true or 1 // Otherwise, it defaults to SPA mode (outputs a single /index.html) useSSRPrerenderMode: process.env.USE_SSR_PRERENDER_MODE === 'true' || process.env.USE_SSR_PRERENDER_MODE === '1', }), ], // Strict port configuration: Vite will error if port 3000 is unavailable server: { strictPort: true, // Configure HMR for remote dev machines via TAURI_DEV_HOST env var hmr: process.env.TAURI_DEV_HOST ? { protocol: 'ws', host: process.env.TAURI_DEV_HOST, } : undefined, }, }); ``` -------------------------------- ### Module Dependency Graph Visualization Source: https://github.com/kvnxiao/tauri-tanstack-start-react-template/blob/main/_autodocs/module-graph.md Visual representation of the project's module dependencies, showing imports and exports for each file. ```tree src/ ├── router.tsx │ ├── Imports: @tanstack/react-router (createRouter) │ ├── Imports: ./routeTree.gen (routeTree) │ └── Exports: getRouter() [factory function] │ ├── routes/ │ ├── __root.tsx │ │ ├── Imports: @tanstack/react-router │ │ ├── Imports: ../styles.css?url │ │ ├── Exports: RootComponent (React.FC) │ │ └── Exports: Route (createRootRoute config) │ │ │ └── index.tsx │ ├── Imports: @tanstack/react-router │ ├── Imports: @tauri-apps/api/core (invoke) │ ├── Imports: react (useState, useCallback) │ ├── Imports: ../components/RoundedButton │ ├── Exports: Home (React.FC) │ └── Exports: Route (createFileRoute config) │ ├── components/ │ └── RoundedButton.tsx │ ├── Imports: react (React.FC) │ ├── Exports: RoundedButton (React.FC) │ └── Exports: RoundedButtonProps (interface) │ ├── routeTree.gen.ts (AUTO-GENERATED) │ ├── Imports: ./routes/__root │ ├── Imports: ./routes/index │ └── Exports: FileRoutesByFullPath, FileRoutesByTo, FileRoutes │ └── styles.css ├── Imports: tailwindcss (CSS directives) └── Imports: @fontsource-variable fonts ``` -------------------------------- ### TypeScript Configuration (`tsconfig.json`) Source: https://github.com/kvnxiao/tauri-tanstack-start-react-template/blob/main/_autodocs/PROJECT_OVERVIEW.md Sets up TypeScript compilation options, including the target ECMAScript version, module system, and path aliases. ```json { "compilerOptions": { "target": "ES2022", "module": "ESNext", "lib": ["ES2022", "DOM", "DOM.Iterable"], "skipLibCheck": true, "allowJs": false, "forceConsistentCasingInFileNames": true, "esModuleInterop": false, "isolatedModules": true, "//": "See https://vitejs.dev/guide/features.html#typescript", "moduleResolution": "bundler", "resolveJsonModule": true, "jsx": "react-jsx", "//": "Path alias for src directory", "baseUrl": ".", "paths": { "@/*": ["./src/*"] }, "//": "Strict mode enabled", "strict": true, "noUnusedLocals": true, "noUnusedParameters": true }, "include": ["src"], "references": [{ "path": "./tsconfig.node.json" }] } ``` -------------------------------- ### Tauri Opener Plugin API Source: https://github.com/kvnxiao/tauri-tanstack-start-react-template/blob/main/_autodocs/api-reference/tauri-integration.md The `tauri_plugin_opener` allows your application to interact with the operating system to open external resources like URLs, files, or execute system commands. ```APIDOC ## Tauri Opener Plugin ### Description Provides OS-level integration for opening external resources such as URLs in the default browser, files with their default applications, executing system commands, and showing files in the file explorer. ### Initialization ```rust .plugin(tauri_plugin_opener::init()) ``` ### Frontend API ```typescript import { open } from "@tauri-apps/plugin-opener"; // Open a URL await open("https://example.com"); // Open a file await open("/path/to/file.txt"); // Open with specific app await open("https://example.com", "firefox"); ``` ### Capabilities Requires the `opener:default` capability, defined in `src-tauri/capabilities/default.json`. ``` -------------------------------- ### Prerender Options Interface Source: https://github.com/kvnxiao/tauri-tanstack-start-react-template/blob/main/_autodocs/types.md Specifies configuration options for prerendering, including whether it's enabled, how subfolder indexes are handled, and optional settings for link crawling, output path, and retry mechanisms. ```typescript // TanStack Start prerender options interface PrerenderOptions { enabled: boolean; autoSubfolderIndex: boolean; crawlLinks?: boolean; outputPath?: string; retryCount?: number; retryDelay?: number; } ``` -------------------------------- ### Open External Resources with Tauri Opener Plugin Source: https://github.com/kvnxiao/tauri-tanstack-start-react-template/blob/main/_autodocs/api-reference/tauri-integration.md Use the frontend API of the `tauri_plugin_opener` to open URLs, files, or specific applications. Ensure the `opener:default` capability is enabled in your `capabilities.json`. ```typescript import { open } from "@tauri-apps/plugin-opener"; // Open a URL await open("https://example.com"); // Open a file await open("/path/to/file.txt"); // Open with specific app await open("https://example.com", "firefox"); ``` -------------------------------- ### Tauri Application Architecture Source: https://github.com/kvnxiao/tauri-tanstack-start-react-template/blob/main/_autodocs/README.md This diagram illustrates the high-level architecture of the Tauri application, showing the interaction between the frontend (React, TanStack) and the backend (Rust), as well as the build system and output formats. ```text ┌─────────────────────────────────────────────────────────┐ │ Tauri Application │ │ (Native Desktop App) │ └──────────┬────────────────────────────────┬─────────────┘ │ │ ┌──────▼──────────┐ ┌──────────▼──────┐ │ Frontend │ │ Backend │ │ (TypeScript) │ │ (Rust) │ ├─────────────────┤ ├─────────────────┤ │ React 19 │◄──IPC───►│ Tauri 2.0 │ │ TanStack Start │(JSON-RPC)│ Cargo │ │ TanStack Router │ │ std lib │ │ TailwindCSS 4 │ └─────────────────┘ └─────────────────┘ │ ┌────▼─────────────┐ │ Build System │ ├──────────────────┤ │ Vite (frontend) │ │ Cargo (backend) │ │ Tauri bundler │ └──────────────────┘ │ ┌────▼─────────────────┐ │ Output (Per Platform)│ ├───────────────────────┤ │ macOS: .dmg │ │ Windows: .msi │ │ Linux: .AppImage │ └───────────────────────┘ ``` -------------------------------- ### File Route Head Configuration Source: https://github.com/kvnxiao/tauri-tanstack-start-react-template/blob/main/_autodocs/api-reference/tanstack-router.md Configure meta tags for specific file routes. These values will merge with and override the root route's head configuration. ```typescript export const Route = createFileRoute("/about")({ head: () => ({ meta: [ { title: "About Us" }, { name: "description", content: "Learn about our company" }, ], }), component: AboutPage, }); ``` -------------------------------- ### Check Formatting and Linting Source: https://github.com/kvnxiao/tauri-tanstack-start-react-template/blob/main/_autodocs/PROJECT_OVERVIEW.md Use this script to check the TypeScript code formatting and linting rules using Biome. ```bash biome check ``` -------------------------------- ### Generate Tauri Context at Compile Time Source: https://github.com/kvnxiao/tauri-tanstack-start-react-template/blob/main/_autodocs/api-reference/tauri-integration.md Use the `tauri::generate_context!` macro to load configuration from `tauri.conf.json` during the build process. This embeds configuration values like window settings and app identifiers. ```rust .run(tauri::generate_context!()) ``` -------------------------------- ### Route Configuration Source: https://github.com/kvnxiao/tauri-tanstack-start-react-template/blob/main/_autodocs/api-reference/routes.md Configuration for the root route, including head metadata and the component to render. This defines the global settings for the application's head section and the main layout component. ```APIDOC ## Route: `Route` ### Description Defines the root route configuration, including head metadata and the main layout component. ### Signature ```typescript export const Route = createRootRoute({ head: () => ({ meta: [ { charSet: "utf-8", }, { name: "viewport", content: "width=device-width, initial-scale=1", }, { title: "Tauri + TanStack Start", }, ], links: [ { rel: "stylesheet", href: appCss, }, ], }), component: RootComponent, }); ``` ### Configuration | Option | Type | Value | Description | |-------------|---------------|-----------------|--------------------------------------------------| | `head` | function | Returns head metadata object | Defines document title, meta tags, and stylesheets | | `component` | React.FC | `RootComponent` | The layout component to render | ### Head Metadata | Meta Attribute | Value | Purpose | |----------------|------------------------------------------|------------------------------------------| | `charSet` | `utf-8` | Document character encoding | | `viewport` | `width=device-width, initial-scale=1` | Responsive viewport configuration | | `title` | `Tauri + TanStack Start` | Document title (browser tab) | | `links[0].rel` | `stylesheet` | CSS stylesheet | | `links[0].href`| `appCss` (imported from `styles.css?url`)| Global styles with Tailwind imports | ``` -------------------------------- ### Tauri Configuration Interface Source: https://github.com/kvnxiao/tauri-tanstack-start-react-template/blob/main/_autodocs/types.md Defines the structure for the `tauri.conf.json` file, outlining essential application settings for build, app, and bundle configurations. ```typescript interface TauriConfig { $schema: string; productName: string; version: string; identifier: string; build: { beforeDevCommand: string; devUrl: string; beforeBuildCommand: string; frontendDist: string; }; app: { windows: Array<{ title: string; width: number; height: number; }>; security: { csp: null | string; }; }; bundle: { active: boolean; targets: string; icon: string[]; }; } ```