### Multi-Environment Configuration Setup Source: https://github.com/dickwu/tauri-notice-window/blob/main/_autodocs/configuration.md Example demonstrating how to set up notice window configurations differently for development and production environments using environment variables. ```typescript // config/notice.config.ts import type { NoticeConfig } from 'tauri-notice-window' export const getNoticeConfig = (): Partial => { const isDev = process.env.NODE_ENV === 'development' return { routePrefix: '/notice', defaultWidth: 400, defaultHeight: 300, notFoundUrl: isDev ? '/notice/dev-error' : '/notice/404', loadTimeout: isDev ? 10000 : 4000, autoSize: true, maxWidth: isDev ? 1200 : 600, maxHeight: isDev ? 1200 : 800, } } ``` ```typescript // app/layout.tsx import { initializeNoticeSystem, setNoticeConfig } from 'tauri-notice-window' import { getNoticeConfig } from '@/config/notice.config' export default function RootLayout({ children }) { useEffect(() => { setNoticeConfig(getNoticeConfig()) initializeNoticeSystem() }, []) return {children} } ``` -------------------------------- ### Cold Start Flow Diagram Source: https://github.com/dickwu/tauri-notice-window/blob/main/FLOW_DIAGRAM.md Details the initialization process when the application restarts, including database setup, notice window system initialization, and loading messages from the database. ```text ┌─────────────────────────────────────────────────────────────────┐ │ App Restart │ │ initializeNoticeSystem() │ └────────────────────────────┬────────────────────────────────────┘ │ ▼ ┌─────────────────────────────────────────────────────────────────┐ │ 1. initializeDatabase() │ │ └─► new NoticeDatabase(databaseName) │ │ │ │ 2. initializeNoticeWindowSystem() │ │ └─► Subscribe to store changes │ │ └─► Auto-create windows on currentMessage update │ │ │ │ 3. store.initializeFromDatabase() │ │ └─► Load: getPendingMessages() from DB │ │ └─► Set: queue = pendingMessages │ │ └─► Auto: showNext() if queue not empty │ │ │ └────────────────────────────┬────────────────────────────────────┘ │ └─► Now in Runtime Mode (Zustand is boss) ``` -------------------------------- ### Install tauri-notice-window Source: https://github.com/dickwu/tauri-notice-window/blob/main/EXAMPLES.md Install the library using npm. This is the first step before integrating it into your application. ```bash npm install tauri-notice-window ``` -------------------------------- ### Tauri Permissions Setup for Notice Windows Source: https://github.com/dickwu/tauri-notice-window/blob/main/README.md Configure Tauri permissions for notice windows by creating a capabilities file. This example includes basic window and webview permissions. ```json { "$schema": "../gen/schemas/desktop-schema.json", "identifier": "notice", "description": "Capability for notice windows", "windows": ["notice-*"], "permissions": [ "core:default", "core:window:allow-close", "core:window:allow-show", "core:window:allow-unminimize", "core:window:allow-set-always-on-top", "core:window:allow-center", "core:webview:allow-webview-close" ] } ``` -------------------------------- ### WindowPosition Examples Source: https://github.com/dickwu/tauri-notice-window/blob/main/_autodocs/types.md Demonstrates various ways to configure window positioning using presets and custom coordinates. ```typescript // Position at right-bottom with 20px padding (default) { position: 'right-bottom' } ``` ```typescript // Position at top-right with 10px padding { position: 'right-top', padding: 10 } ``` ```typescript // Custom absolute coordinates { x: 100, y: 100 } ``` ```typescript // Centered on screen { position: 'center' } ``` -------------------------------- ### Configuration: Setting and Getting Notice Config Source: https://github.com/dickwu/tauri-notice-window/blob/main/_autodocs/index.md Provides examples for setting and retrieving the library's configuration using `setNoticeConfig` and `getNoticeConfig`. This allows customization of behavior like the route prefix. ```typescript import { setNoticeConfig, getNoticeConfig } from 'tauri-notice-window' setNoticeConfig({ routePrefix: '/notifications' }) const config = getNoticeConfig() ``` -------------------------------- ### NoticeStackWindowOptions Example Source: https://github.com/dickwu/tauri-notice-window/blob/main/_autodocs/types.md An example demonstrating how to configure NoticeStackWindowOptions. This shows settings for size, decorations, resizability, and window positioning. ```typescript const options: NoticeStackWindowOptions = { width: 380, height: 520, decorations: false, resizable: true, alwaysOnTop: true, position: { position: 'right-bottom', padding: 20 }, } ``` -------------------------------- ### Install Dependencies Source: https://github.com/dickwu/tauri-notice-window/blob/main/CONTRIBUTING.md Install project dependencies using npm. ```bash npm install ``` -------------------------------- ### React Router Setup for Notice Routes Source: https://github.com/dickwu/tauri-notice-window/blob/main/_autodocs/examples-and-patterns.md Defines routes for your notice windows using React Router. This example includes routes for a general notice, an announcement, an alert, and a 404 page. ```typescript } /> } /> } /> } /> ``` -------------------------------- ### Basic Stack Page UI Example Source: https://github.com/dickwu/tauri-notice-window/blob/main/_autodocs/stack-mode.md Build the user interface for the stack notification window using the useNoticeStack hook. This example demonstrates rendering notifications, handling actions like clearing all, and dismissing individual items. ```typescript // routes/notice/stack/page.tsx or app/notices/stack/page.tsx import { useNoticeStack } from 'tauri-notice-window' export default function NoticeStackPage() { const { items, total, removeItem, clearAll, closeWindow } = useNoticeStack() return (

Notifications ({total})

{total > 0 && }
{items.length === 0 ? (

No notifications

) : ( items.map((item) => (
{item.title} {item.type}
{typeof item.data === 'string' ? item.data : JSON.stringify(item.data)}
)) )}
) } ``` -------------------------------- ### Tauri Notice Window Test Suites Source: https://github.com/dickwu/tauri-notice-window/blob/main/IMPLEMENTATION_SUMMARY.md Demonstrates testing scenarios for the Tauri notice window, including basic operations, queue management, and cold start behavior. Ensure the notice system is initialized before running cold start tests. ```typescript // Test Suite 1: Basic Operations await showNotice({ id: '1', title: 'Test', type: 'alert', data: {} }) await deleteMessageById('1') // Expected: Window closes immediately // Test Suite 2: Queue Management await showNotice({ id: '1', title: 'First', type: 'alert', data: {} }) await showNotice({ id: '2', title: 'Second', type: 'alert', data: {} }) await deleteMessageById('2') // Delete before showing // Expected: Only message '1' shows // Test Suite 3: Cold Start await showNotice({ id: '1', title: 'Test', type: 'alert', data: {} }) // Close app // Restart app await initializeNoticeSystem() // Expected: Message '1' shows automatically ``` -------------------------------- ### Basic Setup with Default 404 Source: https://github.com/dickwu/tauri-notice-window/blob/main/README.md Configures the notice system to use the default '/404' fallback route for unsupported notification types. Ensure 'tauri-notice-window' is imported. ```typescript import { initializeNoticeSystem, setNoticeConfig } from 'tauri-notice-window' // Use default /404 fallback setNoticeConfig({ routePrefix: '/notice', // notFoundUrl defaults to '/404' if not specified }) initializeNoticeSystem() ``` -------------------------------- ### StackedNotification Example Source: https://github.com/dickwu/tauri-notice-window/blob/main/_autodocs/types.md An example of how to create a StackedNotification object. This demonstrates the required and optional fields for a notification item. ```typescript const item: StackedNotification = { id: 'stack-123', uuid: 'uuid-456', type: 'alert', routeType: 'alert', title: 'System Alert', data: { message: 'Something happened' }, receivedAt: Date.now(), } ``` -------------------------------- ### Basic Notice Page Example Source: https://github.com/dickwu/tauri-notice-window/blob/main/_autodocs/notice-layout-component.md Demonstrates a basic implementation of the NoticeLayout component to display a message title, content, and a close button. ```typescript import { NoticeLayout, useCloseNotice } from 'tauri-notice-window' export default function AnnouncementNotice() { const { closeNotice } = useCloseNotice() return ( {(message) => (

{message.title}

{message.data.content}
)}
) } ``` -------------------------------- ### React Router Notice Routes Source: https://github.com/dickwu/tauri-notice-window/blob/main/README.md Example of setting up routes for different notice types using React Router. ```typescript } /> } /> } /> ``` -------------------------------- ### Subscription Optimization: Better Example with Selectors Source: https://github.com/dickwu/tauri-notice-window/blob/main/docs/ZUSTAND_SYNC_INTEGRATION.md Demonstrates the most efficient way to subscribe to Zustand store changes using selectors, further optimizing re-renders. ```typescript // ✅ Better - Use selectors const queueLength = useMessageQueueStore(messageQueueSelectors.queueLength) ``` -------------------------------- ### Multi-Environment Notice Configuration Source: https://github.com/dickwu/tauri-notice-window/blob/main/README.md Configure notice system settings differently for development and production environments. This example uses a separate config file and initializes the system in the root layout. ```typescript // config/notice.config.ts export const getNoticeConfig = () => { const isDev = process.env.NODE_ENV === 'development' return { routePrefix: '/notice', notFoundUrl: isDev ? '/notice/dev-404' // Detailed error in dev : '/notice/404', // Simple error in production defaultWidth: 400, defaultHeight: 300, } } ``` ```typescript // app/layout.tsx import { initializeNoticeSystem, setNoticeConfig } from 'tauri-notice-window' import { getNoticeConfig } from '@/config/notice.config' export default function RootLayout({ children }) { useEffect(() => { setNoticeConfig(getNoticeConfig()) initializeNoticeSystem() }, []) return {children} } ``` ```typescript // app/notice/dev-404/page.tsx (Development-only) export default function DevNotFound() { const { closeNotice } = useCloseNotice() const { currentMessage } = useMessageQueue() return (

🔧 Development Error

Invalid Notice Route

Route Attempted: /notice/{currentMessage?.type}

Message ID: {currentMessage?.id}

Title: {currentMessage?.title}

How to fix:

  1. Create route at: app/notice/{currentMessage?.type}/page.tsx
  2. Or update message.type to match existing route
) } ``` -------------------------------- ### Subscription Optimization: Good Example Source: https://github.com/dickwu/tauri-notice-window/blob/main/docs/ZUSTAND_SYNC_INTEGRATION.md Shows a better approach to subscribing to Zustand store changes by selecting specific state slices, reducing re-renders. ```typescript // ✅ Good - Only re-renders when queue changes const queue = useMessageQueueStore((state) => state.queue) ``` -------------------------------- ### Example MessageType Object Source: https://github.com/dickwu/tauri-notice-window/blob/main/_autodocs/types.md Illustrates how to construct a MessageType object for displaying a system alert with custom data and window dimensions. ```typescript const message: MessageType = { id: 'msg-123', title: 'System Alert', type: 'announcement', data: { content: 'System will reboot in 1 hour', severity: 'warning' }, min_width: 400, min_height: 200, windowPosition: { position: 'right-top', padding: 20 }, decorations: true, } ``` -------------------------------- ### Configure Notice Window Initialization Source: https://github.com/dickwu/tauri-notice-window/blob/main/README.md Configure the notice window settings, including the route prefix and the URL for the 404 error page. This setup is crucial for the library to correctly handle invalid URLs. ```typescript setNoticeConfig({ routePrefix: '/notice', notFoundUrl: '/notice/404', // or '/404' depending on your routing setup }) ``` -------------------------------- ### Batch Updates: Good Example Source: https://github.com/dickwu/tauri-notice-window/blob/main/docs/ZUSTAND_SYNC_INTEGRATION.md Demonstrates an efficient way to update multiple state fields at once using a single method call, optimizing synchronization. ```typescript // ✅ Good - Single sync store.clearOnLogout() // Updates multiple fields at once ``` -------------------------------- ### Cold Start Mode Data Flow Source: https://github.com/dickwu/tauri-notice-window/blob/main/FLOW_DIAGRAM.md Describes the data flow during a cold start, where IndexedDB loads pending messages into the Zustand store, establishing it as the single source of truth before returning to runtime mode. ```text ╔═══════════════════════════════════════════════════════════════╗ ║ COLD START MODE (App Restart) ║ ╠═══════════════════════════════════════════════════════════════╣ ║ ║ ║ IndexedDB → Zustand Store ║ ║ ────────────────────────── ║ ║ Database loads pending messages into empty store ║ ║ ║ ║ │ ║ ║ │ One-time load ║ ║ ▼ ║ ║ ║ ║ Back to Runtime Mode ║ ║ └─► Zustand is now the boss again ║ ║ ║ ╚═══════════════════════════════════════════════════════════════╝ ``` -------------------------------- ### Testing Cold Start Initialization Source: https://github.com/dickwu/tauri-notice-window/blob/main/ARCHITECTURE.md Illustrates the behavior when the application restarts after being closed with pending notices. The system loads messages from cold storage (DB) and displays them automatically. ```typescript // Close app with pending messages await showNotice({ id: '1', title: 'Pending', type: 'alert', data: {} }) await showNotice({ id: '2', title: 'Pending', type: 'alert', data: {} }) // Close app before showing // Restart app await initializeNoticeSystem() // → Loads messages from DB // → Message '1' shows automatically ``` -------------------------------- ### Subscription Optimization: Bad Example Source: https://github.com/dickwu/tauri-notice-window/blob/main/docs/ZUSTAND_SYNC_INTEGRATION.md Illustrates a suboptimal way to subscribe to Zustand store changes, which can lead to unnecessary re-renders on any state change. ```typescript // ❌ Bad - Re-renders on any state change const store = useMessageQueueStore() ``` -------------------------------- ### Zustand-First Architecture Diagram Source: https://github.com/dickwu/tauri-notice-window/blob/main/IMPLEMENTATION_SUMMARY.md Illustrates the data flow between the Zustand Store and IndexedDB, showing the primary role of the store during runtime and cold starts. ```text Runtime: Zustand Store (boss) → IndexedDB (servant) ↓ All operations here Cold Start: IndexedDB → Loads into → Zustand Store (Back to runtime) ``` -------------------------------- ### Runtime Behavior: Cold Start Source: https://github.com/dickwu/tauri-notice-window/blob/main/_autodocs/index.md Describes the process when the application restarts. Pending messages are loaded from IndexedDB into the Zustand store, and the first message is automatically shown. ```text ┌──────────────────┐ │ IndexedDB │ │ (Load pending │ │ messages) │ └────────┬─────────┘ │ ▼ ┌──────────────────┐ │ Zustand Store │ │ (Populate queue) │ └────────┬─────────┘ │ ▼ Auto-show first message (if any) ``` -------------------------------- ### Initialize Tauri Notice Window System Source: https://github.com/dickwu/tauri-notice-window/blob/main/_autodocs/initialization-functions.md Initializes the complete notice window system. Call this once during application startup. It handles database setup, window management, and loading pending messages. ```typescript export const initializeNoticeSystem = async (): Promise ``` ```typescript import { useEffect } from 'react' import { initializeNoticeSystem, setNoticeConfig } from 'tauri-notice-window' function App() { useEffect(() => { // Optional: Configure before initialization setNoticeConfig({ routePrefix: '/notice', defaultWidth: 400, defaultHeight: 300, notFoundUrl: '/404', loadTimeout: 4000, }) // Initialize the system initializeNoticeSystem() }, []) return } ``` -------------------------------- ### Batch Updates: Bad Example Source: https://github.com/dickwu/tauri-notice-window/blob/main/docs/ZUSTAND_SYNC_INTEGRATION.md Shows an inefficient way of updating multiple state fields individually, leading to multiple synchronization operations. ```typescript // ❌ Bad - Multiple syncs store.setQueue([]) store.setCurrentMessage(null) store.setIsProcessing(false) ``` -------------------------------- ### Tauri Capability Setup for Stack Mode Source: https://github.com/dickwu/tauri-notice-window/blob/main/_autodocs/stack-mode.md This JSON configuration sets up Tauri capabilities for windows with labels matching the 'notice-*' pattern, including default core permissions and specific window event permissions. ```json { "windows": ["notice-*"], "permissions": [ "core:default", "core:window:allow-close", "core:window:allow-show", "core:window:allow-unminimize", "core:window:allow-set-always-on-top", "core:window:allow-center", "core:webview:allow-webview-close" ] } ``` -------------------------------- ### Initialize Notice Window System Source: https://github.com/dickwu/tauri-notice-window/blob/main/_autodocs/utility-functions.md Initializes the notice window system by subscribing to store changes to automatically create and manage windows based on message updates. This function is intended to be called automatically during application setup. ```typescript import { initializeNoticeWindowSystem } from 'tauri-notice-window' initializeNoticeWindowSystem() ``` -------------------------------- ### Next.js App Router Setup for Notice Window Source: https://github.com/dickwu/tauri-notice-window/blob/main/README.md Demonstrates integrating tauri-notice-window with Next.js App Router by configuring the root layout and creating a custom 'not-found' page for notifications. ```typescript // app/layout.tsx import { initializeNoticeSystem, setNoticeConfig } from 'tauri-notice-window' export default function RootLayout({ children }) { useEffect(() => { setNoticeConfig({ routePrefix: '/notice', notFoundUrl: '/notice/not-found', // Next.js App Router style defaultWidth: 400, defaultHeight: 300, }) initializeNoticeSystem() }, []) return {children} } // Create: app/notice/not-found/page.tsx import { useCloseNotice } from 'tauri-notice-window' export default function NoticeNotFound() { const { closeNotice } = useCloseNotice() return (

Page Not Found

The notification page you're looking for doesn't exist.

) } ``` -------------------------------- ### Utility Functions for Window Positioning and Screen Size Source: https://github.com/dickwu/tauri-notice-window/blob/main/_autodocs/index.md Demonstrates the usage of utility functions for calculating window positions, getting logical screen dimensions, and retrieving pending messages. These utilities aid in managing notice windows. ```typescript import { calculateWindowPosition, getLogicalScreenSize, getPendingMessages } from 'tauri-notice-window' const pos = await calculateWindowPosition(400, 300) const screen = await getLogicalScreenSize() const pending = await getPendingMessages() ``` -------------------------------- ### Basic Notice Window Configuration Source: https://github.com/dickwu/tauri-notice-window/blob/main/README.md Configure the notice system with a route prefix, a 404 fallback URL, and default window dimensions. Initialize the notice system after setting the configuration. ```javascript import { BrowserRouter, Routes, Route } from 'react-router-dom' import { initializeNoticeSystem, setNoticeConfig } from 'tauri-notice-window' function App() { useEffect(() => { setNoticeConfig({ routePrefix: '/notice', notFoundUrl: '/notice/404', defaultWidth: 400, defaultHeight: 300, }) initializeNoticeSystem() }, []) return ( {/* Main app routes */} } /> {/* Notice routes */} } /> } /> } /> ) } ``` -------------------------------- ### initializeNoticeSystem() Source: https://github.com/dickwu/tauri-notice-window/blob/main/_autodocs/initialization-functions.md Initialize the complete notice window system. Call once during app startup. ```APIDOC ## initializeNoticeSystem() ### Description Initialize the complete notice window system. Call once during app startup. ### Method `async` ### Parameters None. ### Return `Promise` - Resolves when initialization is complete. ### What it does 1. Initializes the IndexedDB database 2. Sets up the window system (store subscription for auto-creating windows) 3. Loads pending messages from database 4. Auto-shows the first message if any pending messages exist 5. Logs confirmation message to console ### Errors Does not throw. Logs errors to console if initialization steps fail. ### Example ```typescript import { useEffect } from 'react' import { initializeNoticeSystem, setNoticeConfig } from 'tauri-notice-window' function App() { useEffect(() => { // Optional: Configure before initialization setNoticeConfig({ routePrefix: '/notice', defaultWidth: 400, defaultHeight: 300, notFoundUrl: '/404', loadTimeout: 4000, }) // Initialize the system initializeNoticeSystem() }, []) return } ``` ``` -------------------------------- ### Build Library Source: https://github.com/dickwu/tauri-notice-window/blob/main/CONTRIBUTING.md Build the library for production. ```bash npm run build ``` -------------------------------- ### Initialize Notice System with Configuration Source: https://github.com/dickwu/tauri-notice-window/blob/main/EXAMPLES.md Initialize the notice system and optionally configure its behavior like route prefix, database name, window dimensions, and a custom 404 page. ```typescript // app/layout.tsx or App.tsx import { useEffect } from 'react' import { initializeNoticeSystem, setNoticeConfig } from 'tauri-notice-window' export default function RootLayout({ children }) { useEffect(() => { // Optional: Configure setNoticeConfig({ routePrefix: '/notice', databaseName: 'my-app-notices', defaultWidth: 450, defaultHeight: 350, notFoundUrl: '/notice/404', // Custom 404 page }) // Initialize initializeNoticeSystem() }, []) return {children} } ``` -------------------------------- ### WebSocket Integration Example Source: https://github.com/dickwu/tauri-notice-window/blob/main/_autodocs/stack-mode.md Integrate pushing notifications to the stack with a WebSocket message handler. This example shows how to map incoming WebSocket messages to the pushToNoticeStack function. ```typescript import { pushToNoticeStack } from 'tauri-notice-window' socket.on('message', async (message) => { await pushToNoticeStack({ id: String(message.id || message.uuid), uuid: message.uuid ? String(message.uuid) : undefined, type: message.type, routeType: message.type, // Optional: can differ from type title: message.title, data: message.payload, receivedAt: message.timestamp, }) }) ``` -------------------------------- ### initializeNoticeWindowSystem() Source: https://github.com/dickwu/tauri-notice-window/blob/main/_autodocs/utility-functions.md Initializes the notice window system by subscribing to store changes to automatically create and manage notice windows. ```APIDOC ## initializeNoticeWindowSystem() ### Description Initializes the notice window system. Sets up store subscription for auto-creating windows. ### Method ```typescript export function initializeNoticeWindowSystem(): void ``` ### Called by `initializeNoticeSystem()` automatically. ### Request Example ```typescript import { initializeNoticeWindowSystem } from 'tauri-notice-window' initializeNoticeWindowSystem() ``` ``` -------------------------------- ### Initialize Notice System and Set Configuration Source: https://github.com/dickwu/tauri-notice-window/blob/main/_autodocs/index.md Initialize the notice system and configure its behavior, such as route prefix, default dimensions, and timeouts. This should be called once at the application's root. ```typescript import { useEffect } from 'react' import { initializeNoticeSystem, setNoticeConfig } from 'tauri-notice-window' function App() { useEffect(() => { setNoticeConfig({ routePrefix: '/notice', defaultWidth: 400, defaultHeight: 300, notFoundUrl: '/404', loadTimeout: 4000, }) initializeNoticeSystem() }, []) return } ``` -------------------------------- ### getPendingMessages() Source: https://github.com/dickwu/tauri-notice-window/blob/main/_autodocs/initialization-functions.md Gets all pending messages, sorted by their queue position. ```APIDOC ## getPendingMessages() ### Description Get all pending messages sorted by queue position. ### Method `async` ### Return `Promise` ### Example ```typescript import { getPendingMessages } from 'tauri-notice-window' const pending = await getPendingMessages() console.log(`${pending.length} messages pending`) ``` ``` -------------------------------- ### Initialize Message Queue System Source: https://github.com/dickwu/tauri-notice-window/blob/main/docs/MESSAGE_QUEUE.md Sets up the notice window system by subscribing to store changes and restoring pending messages from the database on application startup. ```typescript // In SocketManager.tsx import { useMessageQueueStore } from '@/stores/messageQueueStore' import { initializeNoticeWindowSystem } from '@/utils/noticeWindow' const { initializeFromDatabase } = useMessageQueueStore() // 1. Initialize the notice window system (sets up store subscription) initializeNoticeWindowSystem() // 2. Initialize queue from database (restore pending messages) await initializeFromDatabase() // The store subscription automatically creates windows when currentMessage changes ``` -------------------------------- ### Get Pending Messages Source: https://github.com/dickwu/tauri-notice-window/blob/main/README.md Retrieves all messages that are currently pending and have not been shown or hidden. This is a low-level utility for advanced scenarios. ```typescript import { getPendingMessages } from 'tauri-notice-window' const pending = await getPendingMessages() ``` -------------------------------- ### Database Function: Get Pending Messages Source: https://github.com/dickwu/tauri-notice-window/blob/main/docs/MESSAGE_QUEUE.md Retrieves all messages with `queueStatus === 'pending'`, sorted by `queuePosition` from the database. ```typescript getPendingMessages(): Promise ``` -------------------------------- ### Initialize Notice Window System Source: https://github.com/dickwu/tauri-notice-window/blob/main/docs/ZUSTAND_SYNC_INTEGRATION.md Initializes the notice window system and restores pending messages from the database when the main component mounts. ```typescript // In SocketManager.tsx useEffect(() => { // Initialize window system initializeNoticeWindowSystem() // Restore pending messages from Dexie initializeFromDatabase() }, []) ``` -------------------------------- ### Message Queue Hook Usage Source: https://github.com/dickwu/tauri-notice-window/blob/main/_autodocs/stores.md Example of using the message queue selectors with a hook to subscribe to specific state changes. ```typescript const queueLength = useMessageQueueStore(messageQueueSelectors.queueLength) const currentMessage = useMessageQueueStore(messageQueueSelectors.currentMessage) const isProcessing = useMessageQueueStore(messageQueueSelectors.isProcessing) const queue = useMessageQueueStore(messageQueueSelectors.queue) ``` -------------------------------- ### Configure Notice Window System Source: https://github.com/dickwu/tauri-notice-window/blob/main/README.md Sets up the global configuration for the notice window system. Customize route prefix, database name, window dimensions, and fallback URLs. ```typescript setNoticeConfig({ routePrefix: '/notifications', databaseName: 'my-app-notices', defaultWidth: 500, defaultHeight: 400, notFoundUrl: '/error', // Custom 404 page defaultDecorations: false, // Hide title bar globally loadTimeout: 4000, // Auto-close stuck borderless windows after 4s }) ``` -------------------------------- ### Notice Layout Component Source: https://github.com/dickwu/tauri-notice-window/blob/main/_autodocs/README.md Documentation for the main `NoticeLayout` React component, covering its props, behavior, and various usage examples. ```APIDOC ## NoticeLayout Component ### Description The main React component responsible for rendering the notice window content. It handles auto-sizing, loading states, and integrates with configuration options. ### Method React Component ### Endpoint N/A ### Parameters Props and behavior are detailed in the source documentation, including configuration options. ### Request Example ```jsx ``` ### Response Renders the notice UI. Specific response details depend on the props and configuration. ``` -------------------------------- ### Get Message from Database Source: https://github.com/dickwu/tauri-notice-window/blob/main/_autodocs/initialization-functions.md Retrieves a specific message by its ID directly from the database. This is a low-level utility for querying historical data. ```typescript export async function getMessage(id: string): Promise ``` -------------------------------- ### Clear All Pending and Active Notices Source: https://github.com/dickwu/tauri-notice-window/blob/main/README.md Use the useHideAllNotices hook to get the hideAllNotices function, which clears all notices currently in the queue or displayed. ```typescript const { hideAllNotices } = useHideAllNotices() await hideAllNotices() ``` -------------------------------- ### Initialize Database Source: https://github.com/dickwu/tauri-notice-window/blob/main/README.md Initializes the notice window database. This is typically called automatically by `initializeNoticeSystem()` and is intended for advanced scenarios. ```typescript import { initializeDatabase } from 'tauri-notice-window' const db = initializeDatabase() ``` -------------------------------- ### Delete Message Flow Source: https://github.com/dickwu/tauri-notice-window/blob/main/ARCHITECTURE.md Illustrates the internal flow for deleting a message, starting from a user API call to database deletion and queue removal. ```typescript // User calls: await deleteMessageById('123') // Internal flow: ┌─────────────────────────────────────────────────────────────────┐ │ deleteMessageById('123') - Public API │ └────────────────────────┬────────────────────────────────────────┘ │ ▼ ┌─────────────────────────────────────────────────────────────────┐ │ store.deleteMessage('123') │ │ │ │ 1. Delete from database │ │ └─► await deleteMessageById('123') ← DB function │ │ │ │ 2. Remove from queue │ │ └─► await removeFromQueue('123') │ └────────────────────────┬────────────────────────────────────────┘ │ ▼ ┌─────────────────────────────────────────────────────────────────┐ │ store.removeFromQueue('123') │ │ │ │ 1. Filter out from queue array │ │ └─► queue = queue.filter(m => m.id !== '123') │ │ │ │ 2. Persist updated positions │ │ └─► await persistQueue() │ │ │ │ 3. Check if it was the current message │ │ └─► if (currentMessage?.id === '123'): │ │ └─► clearCurrent() ← Closes window & shows next │ └─────────────────────────────────────────────────────────────────┘ ``` -------------------------------- ### Get Pending Messages Source: https://github.com/dickwu/tauri-notice-window/blob/main/_autodocs/utility-functions.md Retrieves all messages currently in the 'pending' state, sorted by their queue position. Useful for processing messages that are waiting to be shown. ```typescript import { getPendingMessages } from 'tauri-notice-window' const pending = await getPendingMessages() console.log(`${pending.length} messages waiting`) pending.forEach((msg, idx) => { console.log(`${idx + 1}. ${msg.title}`) }) ``` -------------------------------- ### Initialize the Notice System Source: https://github.com/dickwu/tauri-notice-window/blob/main/README.md Call initializeNoticeSystem once during application startup to set up the complete notice system. This is a prerequisite for using other features of the library. ```typescript await initializeNoticeSystem() ``` -------------------------------- ### Get Message by ID Source: https://github.com/dickwu/tauri-notice-window/blob/main/_autodocs/utility-functions.md Retrieves a specific message from the database using its unique ID. This is a low-level function intended for querying historical data. ```typescript import { getMessage } from 'tauri-notice-window' const msg = await getMessage('msg-123') if (msg) { console.log(`Message ${msg.id}: ${msg.title}`) console.log(`Status: ${msg.queueStatus}`) } ``` -------------------------------- ### Initialize Notice System with React Router Source: https://github.com/dickwu/tauri-notice-window/blob/main/EXAMPLES.md Sets up the notice system and defines routes for different notice types within a React application using React Router. Ensure `initializeNoticeSystem` is called once, typically at the app's entry point. ```typescript // App.tsx import { BrowserRouter, Routes, Route } from 'react-router-dom' import { useEffect } from 'react' import { initializeNoticeSystem } from 'tauri-notice-window' import AnnouncementNotice from './notices/AnnouncementNotice' import AlertNotice from './notices/AlertNotice' function App() { useEffect(() => { initializeNoticeSystem() }, []) return ( {/* Main app routes */} } /> {/* Notice routes */} } /> } /> ) } ``` -------------------------------- ### Clone Repository Source: https://github.com/dickwu/tauri-notice-window/blob/main/CONTRIBUTING.md Clone the project repository and navigate into the project directory. ```bash git clone https://github.com/yourusername/tauri-notice-window.git cd tauri-notice-window ``` -------------------------------- ### initializeFromDatabase Source: https://github.com/dickwu/tauri-notice-window/blob/main/docs/MESSAGE_QUEUE.md Restores pending messages from the database when the application starts up. It prevents duplicate initialization, queries the database for pending messages, and restores them to the in-memory queue. ```APIDOC ## initializeFromDatabase(): Promise ### Description Restores pending messages from the database on application startup. This function prevents duplicate initialization, queries the database for messages with 'pending' status, restores them to the in-memory queue, syncs the state to all windows, and auto-shows the first message if any exist. ### Method async ### Parameters None ### Request Example ```typescript // In SocketManager const { initializeFromDatabase } = useMessageQueueStore() await initializeFromDatabase() ``` ### Response #### Success Response (void) This method does not return a value upon successful completion. #### Response Example None ``` -------------------------------- ### Hide a Specific Notice by ID Source: https://github.com/dickwu/tauri-notice-window/blob/main/README.md Use the useHideNotice hook to get the hideNotice function, which hides a specific notice window identified by its message ID. ```typescript const { hideNotice } = useHideNotice() await hideNotice(messageId) ``` -------------------------------- ### Initialize Notice System in Root Layout (Next.js/React) Source: https://github.com/dickwu/tauri-notice-window/blob/main/_autodocs/examples-and-patterns.md Configure and initialize the notice system in your application's root layout. Ensure `setNoticeConfig` is called before `initializeNoticeSystem`. ```typescript // app/layout.tsx (Next.js) or App.tsx (React) import { useEffect } from 'react' import { initializeNoticeSystem, setNoticeConfig } from 'tauri-notice-window' export default function RootLayout({ children }) { useEffect(() => { const setupNoticeSystem = async () => { // Configure setNoticeConfig({ routePrefix: '/notice', defaultWidth: 400, defaultHeight: 300, notFoundUrl: '/notice/404', loadTimeout: 4000, autoSize: true, maxWidth: 600, maxHeight: 800, }) // Initialize await initializeNoticeSystem() } setupNoticeSystem() }, []) return ( <> {children} ) } ``` -------------------------------- ### Styled 404 Component Example Source: https://github.com/dickwu/tauri-notice-window/blob/main/README.md Provides a React component for a styled 404 error page, including dynamic display of queued notifications and inline styling. ```typescript // app/notice/404/page.tsx import { useCloseNotice, useMessageQueue } from 'tauri-notice-window' export default function NotFound() { const { closeNotice } = useCloseNotice() const { queueLength } = useMessageQueue() return (

404

Invalid notification type

{queueLength > 0 && (

{queueLength} more notification{queueLength > 1 ? 's' : ''} in queue

)}
) } ``` -------------------------------- ### useNoticeWindow() Source: https://github.com/dickwu/tauri-notice-window/blob/main/_autodocs/hooks.md Hook to open and show notice windows. It provides a `showNotice` function to enqueue and display messages. ```APIDOC ## useNoticeWindow() ### Description Hook to open and show notice windows. It provides a `showNotice` function to enqueue and display messages. ### Method Signature ```typescript export function useNoticeWindow(): { showNotice: (message: MessageType) => Promise } ``` ### Return Value - `showNotice` (function): Enqueue a message and show it in a notice window. ### Parameters #### showNotice(message) - `message` (MessageType) - Required - Message object to display ### What it does 1. Enqueues the message in Zustand store 2. Checks if message was already shown (rejects if true) 3. Saves to IndexedDB if new message 4. Adds to queue if not already present 5. Automatically shows the message window (or waits if another is displaying) ### Example ```typescript import { useNoticeWindow } from 'tauri-notice-window' function SocketHandler() { const { showNotice } = useNoticeWindow() const handleMessage = async (data) => { await showNotice({ id: data.id, title: data.title, type: 'announcement', // lowercase, matches route data: data.content, min_width: 400, min_height: 300, windowPosition: { position: 'right-top' }, decorations: true, }) } return } ``` ### Advanced: Error handling ```typescript const { showNotice } = useNoticeWindow() try { await showNotice({ id: 'msg-1', title: 'Alert', type: 'alert', data: { message: 'Important' }, }) } catch (error) { console.error('Failed to show notice:', error) } ``` ``` -------------------------------- ### Conditional Rendering Notice Source: https://github.com/dickwu/tauri-notice-window/blob/main/_autodocs/notice-layout-component.md Use this example to render different UI elements within a notice based on the message data, such as error, warning, or informational levels. ```typescript import { NoticeLayout, useCloseNotice } from 'tauri-notice-window' export default function ConditionalNotice() { const { closeNotice } = useCloseNotice() return ( {(message) => { // Render different UI based on message type or data if (message.data.level === 'error') { return (

{message.title}

{message.data.message}

) } if (message.data.level === 'warning') { return (

{message.title}

{message.data.message}

) } return (

{message.title}

{message.data.message}

) }}
) } ``` -------------------------------- ### Open a New Notice Window Source: https://github.com/dickwu/tauri-notice-window/blob/main/README.md Use the useNoticeWindow hook to get the showNotice function, which opens a new, individual notice window when called with a message object. ```typescript const { showNotice } = useNoticeWindow() await showNotice(message) ``` -------------------------------- ### Get Pending Messages from Database Source: https://github.com/dickwu/tauri-notice-window/blob/main/_autodocs/initialization-functions.md Retrieves all pending messages, sorted by their queue position, directly from the database. Use this for debugging or querying current queue status. ```typescript export async function getPendingMessages(): Promise ``` -------------------------------- ### Custom 404 Route Configuration Source: https://github.com/dickwu/tauri-notice-window/blob/main/README.md Sets a custom route for 404 errors within the notice system and provides an example of a React component for this custom error page. ```typescript // With custom 404 page inside notice route setNoticeConfig({ routePrefix: '/notice', notFoundUrl: '/notice/error', }) // Create the error page at /notice/error // app/notice/error/page.tsx import { useCloseNotice } from 'tauri-notice-window' export default function NoticeError() { const { closeNotice } = useCloseNotice() return (

Oops! Something went wrong

This notification type is not supported.

) } ``` -------------------------------- ### Notice Page with Auto-Sizing Context Source: https://github.com/dickwu/tauri-notice-window/blob/main/_autodocs/notice-layout-component.md Shows how to use the `windowReady` state from `useNoticeWindowContext` to conditionally apply viewport-filling CSS classes for responsive layout. ```typescript import { NoticeLayout, useNoticeWindowContext } from 'tauri-notice-window' export default function ResponsiveNotice() { const { windowReady } = useNoticeWindowContext() return ( {(message) => (

{message.title}

{message.data.content}
)}
) } ``` -------------------------------- ### Performance: Window Auto-Sizing Logic Source: https://github.com/dickwu/tauri-notice-window/blob/main/_autodocs/index.md Explains the process of window auto-sizing when `autoSize: true`. The window is initially hidden, content is measured, and then the window is resized and shown. A fallback mechanism exists if measurement exceeds `autoSizeTimeout`. ```text When `autoSize: true`: 1. Window hidden on creation 2. Content measured with two rAF frames 3. Window resized and repositioned 4. Window shown **Fallback:** If measurement takes too long (`autoSizeTimeout`), window shown at max height. ``` -------------------------------- ### Debugging Invalid URLs with Console Warnings Source: https://github.com/dickwu/tauri-notice-window/blob/main/README.md Explains how invalid URL validation failures are logged as console warnings and provides an example of correct configuration and message type for debugging. ```typescript // Console output when validation fails: // ⚠️ Invalid window URL: /notice/?id=123. Using fallback 404 page. // To debug, check: setNoticeConfig({ routePrefix: '/notice', notFoundUrl: '/notice/404', }) // Make sure your message has valid type: await showNotice({ id: '123', title: 'My Notice', type: 'announcement', // Should match a route in your app data: {}, }) ``` -------------------------------- ### Batch Operations on Message Queue Source: https://github.com/dickwu/tauri-notice-window/blob/main/_autodocs/stores.md Examples of performing batch operations on the message queue, such as deleting multiple messages by ID or clearing all messages using a dedicated `clearOnLogout` method. ```typescript const store = useMessageQueueStore.getState() // Delete multiple messages for (const id of messageIdsToDelete) { await store.deleteMessage(id) } // Or clear everything await store.clearOnLogout() ``` -------------------------------- ### Initialization Functions Source: https://github.com/dickwu/tauri-notice-window/blob/main/_autodocs/index.md Functions for initializing the notice system and managing messages. ```APIDOC ## Initialization Functions ### `initializeNoticeSystem()` #### Description Initializes the complete notice system. This function should be called once at application startup. ### `setNoticeConfig(config)` #### Description Configures the behavior of the notice windows. Accepts a configuration object. ### `getNoticeConfig()` #### Description Retrieves the current notice window configuration. ### `deleteMessageById(messageId)` #### Description Deletes a specific message from the queue by its ID. ### `hideMessageById(messageId)` #### Description Hides a specific message by its ID. ### `markMessageAsShown(messageId)` #### Description Marks a specific message as shown by its ID. ```