### Install Dependencies, Configure, and Start Dev Server Source: https://github.com/snapcast/snapweb/blob/develop/_autodocs/ARCHITECTURE.md Commands to install project dependencies, optionally configure the local server host, and start the development server. ```bash # Install dependencies npm ci # Configure local server (optional) echo 'VITE_APP_SNAPSERVER_HOST = localhost:1780' > .env.local # Start dev server npm run dev ``` -------------------------------- ### Snapcast Quick Start Example Source: https://github.com/snapcast/snapweb/blob/develop/_autodocs/ARCHITECTURE.md A comprehensive example demonstrating how to connect to a Snapcast server, listen for state changes, control volume, and manage audio playback. ```typescript import { config } from './config'; import { SnapControl, Snapcast } from './snapcontrol'; import { SnapStream } from './snapstream'; // Configure server config.baseUrl = 'ws://localhost:1780'; // Create control API const snapControl = new SnapControl(); // Listen for state changes snapControl.onChange = (control, server) => { console.log(`${server.groups.length} groups, ${server.streams.length} streams`); // Iterate all clients for (const group of server.groups) { for (const client of group.clients) { console.log(`${client.getName()}: ${client.config.volume.percent}%`); } } }; // Listen for connection changes snapControl.onConnectionChanged = (control, connected, error) => { if (connected) { console.log('Connected to Snapcast server'); } else { console.log('Disconnected:', error); } }; // Connect to server snapControl.connect(config.baseUrl); // Control volume after connected setTimeout(() => { snapControl.setVolume('client-id', 50); }, 1000); // Start audio playback const snapStream = new SnapStream(config.baseUrl); snapStream.resume(); // Required for autoplay policy // Stop everything window.addEventListener('beforeunload', () => { snapControl.disconnect(); snapStream.stop(); }); ``` -------------------------------- ### Complete Configuration Setup Example Source: https://github.com/snapcast/snapweb/blob/develop/_autodocs/api-reference/Configuration-API.md Demonstrates how to initialize Snapweb configuration on first launch by checking for existing persistent values and setting defaults if necessary. It also shows how user preferences like theme changes are handled and automatically persisted. ```typescript import { config, Theme, getPersistentValue, setPersistentValue } from './config'; // On first launch if (!getPersistentValue('snapserver.host')) { // Set defaults config.baseUrl = 'ws://localhost:1780'; config.theme = Theme.System; config.showOffline = false; } // On user preference change function handleThemeChange(newTheme: Theme) { config.theme = newTheme; // Automatically persisted } // Access current configuration console.log('Current server:', config.baseUrl); console.log('Current theme:', config.theme); console.log('Show offline:', config.showOffline); ``` -------------------------------- ### Example: Get and Set Theme Source: https://github.com/snapcast/snapweb/blob/develop/_autodocs/configuration.md Shows how to import configuration and theme enums, retrieve the current theme, and set it to dark or system preference. Values are persisted. ```typescript import { config, Theme } from './config'; // Get current theme const currentTheme = config.theme; console.log(currentTheme); // "system" or "light" or "dark" // Set to dark theme config.theme = Theme.Dark; // Set to system preference config.theme = Theme.System; ``` -------------------------------- ### Setup VITE_APP_SNAPSERVER_HOST Environment Variable Source: https://github.com/snapcast/snapweb/blob/develop/_autodocs/configuration.md Example of how to set the `VITE_APP_SNAPSERVER_HOST` environment variable in a `.env.local` file for local development. ```bash # In .env.local echo 'VITE_APP_SNAPSERVER_HOST = localhost:1780' > .env.local ``` -------------------------------- ### Install Dependencies Source: https://github.com/snapcast/snapweb/blob/develop/_autodocs/GETTING-STARTED.md Installs all necessary packages for the project using npm. This is the first step in setting up the development environment. ```bash # Install dependencies npm install ``` -------------------------------- ### Example: Get and Set Server URL Source: https://github.com/snapcast/snapweb/blob/develop/_autodocs/configuration.md Demonstrates how to retrieve the current server URL and how to set a new one. The protocol (ws:// or wss://) is automatically determined by the page's protocol. ```typescript // Get current server URL const url = config.baseUrl; console.log(url); // "ws://localhost:1780" // Set new server URL config.baseUrl = 'wss://snapserver.example.com:1780'; // Auto-constructs protocol based on current page // https://page.html -> wss://snapserver.example.com // http://page.html -> ws://snapserver.example.com ``` -------------------------------- ### Example: Get and Set Show Offline Clients Source: https://github.com/snapcast/snapweb/blob/develop/_autodocs/configuration.md Demonstrates retrieving the current state of the `showOffline` setting and how to enable or disable the display of offline clients. Values are persisted. ```typescript // Get current setting const show = config.showOffline; console.log(show); // true or false // Enable showing offline clients config.showOffline = true; // Disable showing offline clients config.showOffline = false; ``` -------------------------------- ### Example Properties Object Source: https://github.com/snapcast/snapweb/blob/develop/_autodocs/types.md Demonstrates an example of the Properties object, showing current playback status, volume, control capabilities, and metadata for the playing track. ```typescript { playbackStatus: 'playing', volume: 100, canControl: true, canSeek: true, metadata: { title: 'Close Your Eyes', artist: ['Felix Jaehn'], album: 'BREATHE' } } ``` -------------------------------- ### Install Project Dependencies Source: https://github.com/snapcast/snapweb/blob/develop/README.md Install all necessary project dependencies using npm ci. This command ensures that the exact versions specified in the package-lock.json are installed. ```bash npm ci ``` -------------------------------- ### Example API Reference Format Source: https://github.com/snapcast/snapweb/blob/develop/_autodocs/README.md Illustrates the standard format for API reference entries, including method signatures, parameter tables, return types, error conditions, code examples, and source location. ```markdown ### methodName(param: Type): ReturnType Description of what it does. | Parameter | Type | Default | Description | |-----------|------|---------|-------------| | param | Type | — | Description | **Returns**: ReturnType **Behavior**: How it works **Throws**: Error conditions **Example**: ```typescript // Usage code ``` **Source**: src/file.ts:123 ``` -------------------------------- ### Start Development Server Source: https://github.com/snapcast/snapweb/blob/develop/_autodocs/GETTING-STARTED.md Launches the local development server, typically used for active development and testing. It usually includes hot-reloading and other development-specific features. ```bash # Start dev server npm run dev ``` -------------------------------- ### Host Example JSON Source: https://github.com/snapcast/snapweb/blob/develop/_autodocs/types.md An example JSON object representing a Host. This format is used for serializing and deserializing host information. ```json { "arch": "armv7l", "ip": "192.168.0.3", "mac": "dc:a6:32:3f:bd:1c", "name": "raspberrypi", "os": "Raspbian GNU/Linux 11 (bullseye)" } ``` -------------------------------- ### Example: Show Offline Clients Usage Source: https://github.com/snapcast/snapweb/blob/develop/_autodocs/api-reference/Configuration-API.md Demonstrates reading and toggling the showOffline configuration setting. This affects client filtering in the UI. ```typescript import { config } from './config'; // Read setting if (config.showOffline) { console.log('Showing offline clients'); } // Enable showing offline clients config.showOffline = true; // Disable config.showOffline = false; ``` -------------------------------- ### Example: Theme Enum Usage Source: https://github.com/snapcast/snapweb/blob/develop/_autodocs/api-reference/Configuration-API.md Demonstrates setting the theme using the Theme enum and checking the current theme. Also shows how to cycle through available themes. ```typescript import { config, Theme } from './config'; // Set dark theme config.theme = Theme.Dark; // Check if dark if (config.theme === Theme.Dark) { console.log('Dark theme enabled'); } // Cycle through themes const themes = [Theme.System, Theme.Light, Theme.Dark]; const currentIndex = themes.indexOf(config.theme); const nextIndex = (currentIndex + 1) % themes.length; config.theme = themes[nextIndex]; ``` -------------------------------- ### Example: Theme Usage Source: https://github.com/snapcast/snapweb/blob/develop/_autodocs/api-reference/Configuration-API.md Demonstrates reading and setting the theme preference using the Theme enum. Includes logic for switching themes based on user preference. ```typescript import { config, Theme } from './config'; // Read theme const theme = config.theme; // Set to dark config.theme = Theme.Dark; // Set to system default config.theme = Theme.System; // Switch based on user preference if (userPrefersDark) { config.theme = Theme.Dark; } ``` -------------------------------- ### JSON-RPC Request Format for Client.SetVolume Source: https://github.com/snapcast/snapweb/blob/develop/_autodocs/ARCHITECTURE.md Example of a JSON-RPC request to set the volume for a specific client. ```json { "jsonrpc": "2.0", "id": 1, "method": "Client.SetVolume", "params": { "id": "client-id", "volume": { "muted": false, "percent": 75 } } } ``` -------------------------------- ### Run Local Development Server Source: https://github.com/snapcast/snapweb/blob/develop/README.md Start the local web server with a watcher for development. This command builds the project and watches for file changes, automatically reloading the server. ```bash npm run dev ``` -------------------------------- ### Example: Base URL Usage Source: https://github.com/snapcast/snapweb/blob/develop/_autodocs/api-reference/Configuration-API.md Demonstrates reading and updating the baseUrl configuration property. The setter can accept a secure WebSocket URL. ```typescript // Read current server const currentServer = config.baseUrl; console.log(currentServer); // "ws://localhost:1780" // Change server config.baseUrl = 'wss://snapcast.example.com:1780'; // Automatically uses secure WS if HTTPS // Auto-constructs from environment at build time ``` -------------------------------- ### Example Metadata JSON Source: https://github.com/snapcast/snapweb/blob/develop/_autodocs/types.md Illustrates the expected JSON format for the Metadata object, including track details and artwork URL. ```json { "title": "Close Your Eyes", "artist": ["Felix Jaehn", "VIZE", "Miss Li"], "album": "BREATHE", "artUrl": "http://i.scdn.co/image/ab67616d00001e02...", "duration": 159.96 } ``` -------------------------------- ### config.theme Source: https://github.com/snapcast/snapweb/blob/develop/_autodocs/api-reference/Configuration-API.md Gets or sets the UI theme preference, allowing selection between system default, light, or dark themes. ```APIDOC ## Property: theme ### Description Gets or sets the UI theme preference, allowing selection between system default, light, or dark themes. ### Type `Theme` (string enum) ### Values - `Theme.System` ("system") - Follow OS preference - `Theme.Light` ("light") - Force light theme - `Theme.Dark` ("dark") - Force dark theme ### Getter ```typescript const currentTheme: Theme = config.theme; ``` ### Setter ```typescript config.theme = Theme.Dark; ``` ### Default `Theme.System` ### Storage Key `theme` ### Example ```typescript import { config, Theme } from './config'; // Read theme const theme = config.theme; // Set to dark config.theme = Theme.Dark; // Set to system default config.theme = Theme.System; ``` ### Integration Used by Material-UI ThemeProvider in SnapWeb component. ``` -------------------------------- ### Stream Audio with SnapStream Source: https://github.com/snapcast/snapweb/blob/develop/_autodocs/GETTING-STARTED.md Demonstrates how to create, resume, and stop audio streams using the SnapStream class. It also shows how to get the unique client ID. ```typescript import { SnapStream } from './snapstream'; // Create audio stream (independent of control) const stream = new SnapStream('ws://localhost:1780'); // Resume playback (required for autoplay policy) stream.resume(); // Stop playback and close connection stream.stop(); // Get unique client ID const clientId = SnapStream.getClientId(); console.log('Client ID:', clientId); ``` -------------------------------- ### Example Stream JSON Source: https://github.com/snapcast/snapweb/blob/develop/_autodocs/types.md Illustrates the expected JSON format for a Stream object, showing its ID, status, URI details, and properties. ```json { "id": "Spotify", "status": "idle", "uri": { "raw": "spotify:...", "scheme": "spotify", "host": "", "path": "...", "fragment": "", "query": "" }, "properties": { "playbackStatus": "paused", "volume": 100, "canControl": true } } ``` -------------------------------- ### Data Flow Example: Changing Volume Source: https://github.com/snapcast/snapweb/blob/develop/_autodocs/ARCHITECTURE.md Illustrates the sequence of operations from user interaction to UI re-rendering when changing audio volume. ```typescript // 1. User interaction handleVolumeChange(75) // 2. Component calls API snapControl.setVolume('client-id', 75) // 3. SnapControl updates local state client.config.volume.percent = 75 // 4. SnapControl sends request sendRequest('Client.SetVolume', { id: 'client-id', volume: { muted: false, percent: 75 } }) // 5. Server processes and broadcasts notification notify('Client.OnVolumeChanged', { id: 'client-id', volume: { muted: false, percent: 75 } }) // 6. SnapControl receives and handles server.getClient('client-id').config.volume = { muted: false, percent: 75 } // 7. Invoke callback if (onChange) { onChange(this, this.server) } // 8. React component updates setServer(newServerState) // 9. UI re-renders ``` -------------------------------- ### JSON-RPC Response Format Source: https://github.com/snapcast/snapweb/blob/develop/_autodocs/ARCHITECTURE.md Example of a standard JSON-RPC response indicating a successful operation. ```json { "jsonrpc": "2.0", "id": 1, "result": { "server": { /* complete server state */ } } } ``` -------------------------------- ### config.baseUrl Source: https://github.com/snapcast/snapweb/blob/develop/_autodocs/api-reference/Configuration-API.md Gets or sets the Snapcast server WebSocket URL. It can be configured via environment variables or directly set. ```APIDOC ## Property: baseUrl ### Description Gets or sets the Snapcast server WebSocket URL. It can be configured via environment variables or directly set. ### Type `string` ### Getter ```typescript const url: string = config.baseUrl; ``` ### Setter ```typescript config.baseUrl = 'ws://192.168.1.100:1780'; ``` ### Default Logic - Environment variable `VITE_APP_SNAPSERVER_HOST` if set - Otherwise: auto-constructed from current location - Protocol: `wss://` if page is HTTPS, else `ws://` - Host: `window.location.host` ### Storage Key `snapserver.host` ### Example ```typescript // Read current server const currentServer = config.baseUrl; console.log(currentServer); // "ws://localhost:1780" // Change server config.baseUrl = 'wss://snapcast.example.com:1780'; ``` ``` -------------------------------- ### Instantiate Snapcast Group Class Source: https://github.com/snapcast/snapweb/blob/develop/_autodocs/api-reference/Snapcast-Classes.md Provides an example of creating a Group object with sample JSON data and accessing the number of clients within the group. ```typescript const groupJson = { id: "e02e0600-e68c-b128-147b-58ca0a063ecf", name: "Living Room Group", stream_id: "Spotify", muted: false, clients: [ /* ... client objects ... */ ] }; const group = new Snapcast.Group(groupJson); console.log(group.clients.length); // Number of clients ``` -------------------------------- ### Complete Data Model Traversal Example Source: https://github.com/snapcast/snapweb/blob/develop/_autodocs/api-reference/Snapcast-Classes.md Connects to a Snapcast server and traverses the entire data model, logging information about groups, clients, streams, and their properties. This is useful for monitoring and debugging. ```typescript import { Snapcast, SnapControl } from './snapcontrol'; const snapControl = new SnapControl(); snapControl.onChange = (control, server) => { // Iterate all groups for (const group of server.groups) { console.log(`Group: ${group.name}`); // Iterate clients in group for (const client of group.clients) { console.log(` Client: ${client.getName()}`); console.log(` Volume: ${client.config.volume.percent}%`); console.log(` Muted: ${client.config.volume.muted}`); console.log(` Connected: ${client.connected}`); } // Get current stream for group const stream = server.getStream(group.stream_id); if (stream) { console.log(` Stream: ${stream.id}`); console.log(` Status: ${stream.status}`); console.log(` Playing: ${stream.properties.playbackStatus}`); if (stream.properties.metadata) { const meta = stream.properties.metadata; console.log(` Now playing: ${meta.title} by ${meta.artist?.join(', ')}`); } } } }; snapControl.connect('ws://localhost:1780'); ``` -------------------------------- ### Get Base URL Source: https://github.com/snapcast/snapweb/blob/develop/_autodocs/api-reference/Configuration-API.md Retrieve the current Snapcast server WebSocket URL from the configuration. ```typescript const url: string = config.baseUrl; ``` -------------------------------- ### JSON-RPC Notification Format for Client.OnVolumeChanged Source: https://github.com/snapcast/snapweb/blob/develop/_autodocs/ARCHITECTURE.md Example of a JSON-RPC notification broadcasted when a client's volume changes. ```json { "jsonrpc": "2.0", "method": "Client.OnVolumeChanged", "params": { "id": "client-id", "volume": { "muted": false, "percent": 75 } } } ``` -------------------------------- ### Manage Snapweb Settings in React Components Source: https://github.com/snapcast/snapweb/blob/develop/_autodocs/configuration.md Integrate Snapweb configuration into React components using local state management. This example demonstrates how to update the theme and server URL via user interactions. ```typescript import { useState, useEffect } from 'react'; import { config, Theme } from '../config'; export function SettingsPanel() { const [theme, setTheme] = useState(config.theme); const [serverUrl, setServerUrl] = useState(config.baseUrl); const handleThemeChange = (newTheme: Theme) => { config.theme = newTheme; setTheme(newTheme); }; const handleServerUrlChange = (url: string) => { config.baseUrl = url; setServerUrl(url); }; return (
handleServerUrlChange(e.target.value)} />
); } ``` -------------------------------- ### Set Snapserver Host Environment Variable Source: https://github.com/snapcast/snapweb/blob/develop/README.md Configure the local environment variable for the Snapserver host before starting development. This is typically done using a .env.local file. ```bash echo 'VITE_APP_SNAPSERVER_HOST = localhost:1780' > .env.local ``` -------------------------------- ### Configure Local Server (Development) Source: https://github.com/snapcast/snapweb/blob/develop/_autodocs/GETTING-STARTED.md Sets the local Snapcast server host and port for the development environment by creating a `.env.local` file. This is optional and useful for local testing. ```bash # Configure local server (optional) echo 'VITE_APP_SNAPSERVER_HOST = localhost:1780' > .env.local ``` -------------------------------- ### Get Client ID Source: https://github.com/snapcast/snapweb/blob/develop/_autodocs/api-reference/SnapStream.md Gets or generates a unique client ID for this browser instance. It stores the ID in localStorage for subsequent calls. ```typescript const clientId = SnapStream.getClientId(); console.log('Unique client ID:', clientId); ``` -------------------------------- ### Configure Snapweb Application Source: https://github.com/snapcast/snapweb/blob/develop/_autodocs/configuration.md Set up the application's base URL, theme, and offline client visibility on startup. This snippet also shows how to access current configuration values and update them. ```typescript import { config, Theme, getPersistentValue, setPersistentValue } from './config'; // Configure on startup config.baseUrl = 'ws://snapserver.local:1780'; config.theme = Theme.Dark; config.showOffline = true; // React to configuration changes const currentTheme = config.theme; const serverUrl = config.baseUrl; // Access raw values const rawTheme = getPersistentValue('theme', Theme.System); // Update configuration config.theme = Theme.System; ``` -------------------------------- ### Get Theme Preference Source: https://github.com/snapcast/snapweb/blob/develop/_autodocs/api-reference/Configuration-API.md Retrieve the current UI theme preference from the configuration. ```typescript const currentTheme: Theme = config.theme; ``` -------------------------------- ### Initialize SnapControl and Listen for Updates Source: https://github.com/snapcast/snapweb/blob/develop/_autodocs/INDEX.md Instantiate SnapControl, set up an event handler for state changes, and connect to the Snapcast server. ```typescript import { SnapControl } from './snapcontrol'; const control = new SnapControl(); control.onChange = (_ctrl, server) => { // React to state changes }; control.connect('ws://localhost:1780'); ``` -------------------------------- ### Build for Production Source: https://github.com/snapcast/snapweb/blob/develop/_autodocs/ARCHITECTURE.md Command to build the project for production deployment. ```bash # Build for production npm run build ``` -------------------------------- ### Build for Production Source: https://github.com/snapcast/snapweb/blob/develop/_autodocs/GETTING-STARTED.md Creates an optimized build of the application for deployment. The output is typically placed in a 'dist/' directory. ```bash # Build optimized version npm run build ``` -------------------------------- ### Get Stream Information Source: https://github.com/snapcast/snapweb/blob/develop/_autodocs/INDEX.md Retrieve details about a specific audio stream, such as its playback status and metadata. ```typescript const stream = control.getStream('Spotify'); console.log(stream.properties.playbackStatus); console.log(stream.properties.metadata?.title); ``` -------------------------------- ### config.showOffline Source: https://github.com/snapcast/snapweb/blob/develop/_autodocs/api-reference/Configuration-API.md Gets or sets a boolean value indicating whether to display offline clients in the UI. Defaults to false. ```APIDOC ## Property: showOffline ### Description Gets or sets a boolean value indicating whether to display offline clients in the UI. Defaults to false. ### Type `boolean` ### Getter ```typescript const show: boolean = config.showOffline; ``` ### Setter ```typescript config.showOffline = true; ``` ### Default `false` ### Storage Key `showoffline` ### Internal Storage Format Stored as string "true" or "false", converted to boolean on access ### Example ```typescript import { config } from './config'; // Read setting if (config.showOffline) { console.log('Showing offline clients'); } // Enable showing offline clients config.showOffline = true; // Disable config.showOffline = false; ``` ### Usage Component filters clients based on this setting before rendering. ``` -------------------------------- ### Instantiate Snapcast Host Class Source: https://github.com/snapcast/snapweb/blob/develop/_autodocs/api-reference/Snapcast-Classes.md Demonstrates how to create a new Host object using its constructor with sample JSON data. Accesses the 'name' property after instantiation. ```typescript const hostJson = { arch: "armv7l", ip: "192.168.0.3", mac: "dc:a6:32:3f:bd:1c", name: "raspberrypi", os: "Raspbian GNU/Linux 11 (bullseye)" }; const host = new Snapcast.Host(hostJson); console.log(host.name); // "raspberrypi" ``` -------------------------------- ### Build for Production Source: https://github.com/snapcast/snapweb/blob/develop/README.md Build the Snapweb project for production deployment. This command generates optimized static assets in the 'dist' directory. ```bash npm run build ``` -------------------------------- ### Instantiate Snapcast Client Class Source: https://github.com/snapcast/snapweb/blob/develop/_autodocs/api-reference/Snapcast-Classes.md Illustrates creating a Client object with sample JSON data and retrieving its display name using the `getName` method. ```typescript const clientJson = { id: "dc:a6:32:3f:bd:1c", host: { /* ... */ }, snapclient: { name: "Snapclient", protocolVersion: 2, version: "0.26.0" }, config: { instance: 1, latency: 0, name: "Living Room", volume: { muted: false, percent: 75 } }, lastSeen: { sec: 1659107106, usec: 967903 }, connected: true }; const client = new Snapcast.Client(clientJson); console.log(client.getName()); // "Living Room" ``` -------------------------------- ### SnapStream.getClientId() Source: https://github.com/snapcast/snapweb/blob/develop/_autodocs/api-reference/SnapStream.md Gets or generates a unique client ID for this browser instance. It uses localStorage to store and retrieve the ID. ```APIDOC ## getClientId() ### Description Gets or generates a unique client ID for this browser instance. ### Method getClientId ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body None ### Request Example ```typescript const clientId = SnapStream.getClientId(); console.log('Unique client ID:', clientId); ``` ### Response #### Success Response (200) string (UUID v4) #### Response Example ```json { "example": "a1b2c3d4-e5f6-7890-1234-567890abcdef" } ``` ``` -------------------------------- ### Get UI Theme Preference Source: https://github.com/snapcast/snapweb/blob/develop/_autodocs/configuration.md Retrieve the current UI theme setting. The theme can be system-default, light, or dark. ```typescript config.theme ``` -------------------------------- ### Connect to Snapcast Server Source: https://github.com/snapcast/snapweb/blob/develop/_autodocs/api-reference/SnapControl.md Establishes a WebSocket connection to the Snapcast server. Set up the onConnectionChanged callback to monitor connection status. ```typescript snapControl.connect('ws://localhost:1780'); snapControl.onConnectionChanged = (control, connected, error) => { if (connected) { console.log('Connected to Snapcast server'); } else { console.log('Disconnected:', error); } }; ``` -------------------------------- ### Get Client Display Name Source: https://github.com/snapcast/snapweb/blob/develop/_autodocs/api-reference/Snapcast-Classes.md Demonstrates using the `getName` method on a Client object to retrieve its configured display name. ```typescript const client = new Snapcast.Client(clientJson); const name = client.getName(); // "Living Room" ``` -------------------------------- ### Connect and Listen to SnapControl Events Source: https://github.com/snapcast/snapweb/blob/develop/_autodocs/GETTING-STARTED.md Initialize SnapControl, connect to the server, and set up listeners for state and connection changes. ```typescript import { SnapControl } from './snapcontrol'; const control = new SnapControl(); control.connect('ws://localhost:1780'); // Listen for state updates control.onChange = (ctrl, server) => { console.log(`Server has ${server.groups.length} groups`); }; // Set volume control.setVolume('client-id', 75); // Mute a group control.muteGroup('group-id', true); ``` ```typescript import { SnapControl, Snapcast } from './snapcontrol'; import { config } from './config'; // Create control instance const snapControl = new SnapControl(); // Configure server URL config.baseUrl = 'ws://192.168.1.100:1780'; // Connect to server snapControl.connect(config.baseUrl); ``` ```typescript // Called when server state changes snapControl.onChange = (control, server) => { console.log('Server state updated'); console.log(`Groups: ${server.groups.length}`); console.log(`Streams: ${server.streams.length}`); }; // Called when connection state changes snapControl.onConnectionChanged = (control, connected, error) => { if (connected) { console.log('✓ Connected to Snapcast server'); } else { console.log('✗ Disconnected:', error || 'Unknown error'); } }; ``` -------------------------------- ### Get Currently Playing Track Title Source: https://github.com/snapcast/snapweb/blob/develop/_autodocs/ARCHITECTURE.md Retrieves the title of the currently playing track for the first group's stream. ```typescript const streamId = snapControl.server.groups[0].stream_id; const stream = snapControl.getStream(streamId); const title = stream.properties.metadata?.title || 'Unknown'; ``` -------------------------------- ### Snapweb Initialization Flow Source: https://github.com/snapcast/snapweb/blob/develop/_autodocs/ARCHITECTURE.md The sequence of events during the initial startup of the Snapweb application. ```mermaid graph TD Application Start ↓ config.ts loads persistent settings ↓ SnapWeb component mounts ↓ SnapControl instance created ↓ SnapStream instance created (if playing) ↓ Connect to Snapcast server via WebSocket ``` -------------------------------- ### Get Show Offline Clients Setting Source: https://github.com/snapcast/snapweb/blob/develop/_autodocs/configuration.md Retrieve the boolean value indicating whether offline clients should be displayed in the UI. ```typescript config.showOffline ``` -------------------------------- ### SnapStream Constructor Source: https://github.com/snapcast/snapweb/blob/develop/_autodocs/api-reference/SnapStream.md Creates a new SnapStream instance and initializes audio playback. It connects to the Snapcast server via WebSocket and sets up audio context and time synchronization. ```APIDOC ## SnapStream Constructor ### Description Creates a new SnapStream instance and initializes audio playback. ### Method constructor ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body None ### Request Example ```typescript import { SnapStream } from './snapstream'; const snapStream = new SnapStream('ws://localhost:1780'); ``` ### Response #### Success Response (200) SnapStream instance #### Response Example ```typescript // SnapStream instance is returned ``` ### Throws Displays an alert if the Web Audio API is not supported by the browser. ``` -------------------------------- ### connect(baseUrl: string) Source: https://github.com/snapcast/snapweb/blob/develop/_autodocs/api-reference/SnapControl.md Establishes a WebSocket connection to the Snapcast server. It handles disconnection of existing connections and sets up event handlers for connection status. ```APIDOC ## connect(baseUrl: string) ### Description Establishes a WebSocket connection to the Snapcast server. ### Method connect ### Parameters #### Path Parameters - **baseUrl** (string) - Required - Base URL of the Snapcast server (e.g., `ws://localhost:1780`) ### Returns void ### Behavior - Disconnects any existing connection - Creates a WebSocket to `baseUrl + '/jsonrpc'` - Sets up event handlers for messages, opens, errors, and closes - On open: Sends initial `Server.GetStatus` request - On close/error: Attempts reconnection after 1 second - Calls `onConnectionChanged` callback when connection state changes ### Example ```typescript snapControl.connect('ws://localhost:1780'); snapControl.onConnectionChanged = (control, connected, error) => { if (connected) { console.log('Connected to Snapcast server'); } else { console.log('Disconnected:', error); } }; ``` ``` -------------------------------- ### Instantiate SnapStream Source: https://github.com/snapcast/snapweb/blob/develop/_autodocs/api-reference/SnapStream.md Creates a new SnapStream instance and initializes audio playback. The baseUrl parameter is the base URL of the Snapcast server. ```typescript import { SnapStream } from './snapstream'; const snapStream = new SnapStream('ws://localhost:1780'); ``` -------------------------------- ### Get Group Volume Source: https://github.com/snapcast/snapweb/blob/develop/_autodocs/api-reference/SnapControl.md Calculates the average volume for a group, optionally considering only online clients. Returns 0 if the group has no clients. ```typescript const group = snapControl.getGroup('e02e0600-e68c-b128-147b-58ca0a063ecf'); const avgVolume = snapControl.getGroupVolume(group, true); console.log('Average volume (online only):', avgVolume); ``` -------------------------------- ### Configure Snapcast Server Host via Environment Variable Source: https://github.com/snapcast/snapweb/blob/develop/_autodocs/api-reference/Configuration-API.md Set the `VITE_APP_SNAPSERVER_HOST` environment variable to configure the default Snapcast server address during build time. This can be set in a `.env.local` file. At runtime, access it via `import.meta.env.VITE_APP_SNAPSERVER_HOST`. ```bash VITE_APP_SNAPSERVER_HOST = localhost:1780 VITE_APP_SNAPSERVER_HOST = snapcast.example.com:1780 ``` ```typescript const host = import.meta.env.VITE_APP_SNAPSERVER_HOST; ``` -------------------------------- ### Get Persistent Value from LocalStorage Source: https://github.com/snapcast/snapweb/blob/develop/_autodocs/configuration.md Retrieves a value from browser localStorage using a specified key. Provides a fallback to a default value if the key is not found. ```typescript import { getPersistentValue } from './config'; // Get value with default const host = getPersistentValue('snapserver.host', 'ws://localhost:1780'); // Use without default const theme = getPersistentValue('theme'); ``` -------------------------------- ### Snapcast Audio Streaming Flow Source: https://github.com/snapcast/snapweb/blob/develop/_autodocs/ARCHITECTURE.md Outlines the steps involved in setting up audio streaming, decoding, and playback using SnapStream. ```mermaid graph TD SnapStream.constructor(baseUrl) ↓ WebSocket opens to /stream endpoint ↓ Send HelloMessage (handshake) ↓ Start time synchronization loop ↓ Receive CodecMessage (FLAC/Opus/PCM) ↓ Initialize decoder ↓ Create Web Audio API context ↓ Receive PcmChunkMessage (audio data) ↓ Decode and buffer audio ↓ Play buffers through Web Audio API ``` -------------------------------- ### Get Stream from Client ID Source: https://github.com/snapcast/snapweb/blob/develop/_autodocs/api-reference/SnapControl.md Retrieves the stream that is currently playing within the group associated with the specified client. Throws an error if the client or its group is not found. ```typescript const stream = snapControl.getStreamFromClient('dc:a6:32:3f:bd:1c'); console.log('Stream ID:', stream.id); ``` -------------------------------- ### Instantiate Snapcast Metadata Source: https://github.com/snapcast/snapweb/blob/develop/_autodocs/api-reference/Snapcast-Classes.md Create a Metadata object by passing a JSON object containing track details like title, artist, album, artwork URL, and duration. ```typescript import { Snapcast } from './snapcontrol'; const metaJson = { title: "Close Your Eyes", artist: ["Felix Jaehn", "VIZE", "Miss Li"], album: "BREATHE", artUrl: "http://example.com/art.jpg", duration: 159.96 }; const metadata = new Snapcast.Metadata(metaJson); console.log(metadata.title); // "Close Your Eyes" ``` -------------------------------- ### Set Default Snapcast Server Host Environment Variable Source: https://github.com/snapcast/snapweb/blob/develop/_autodocs/configuration.md Configure the default Snapcast server host using a Vite environment variable. This is typically set in a `.env.local` file. ```bash VITE_APP_SNAPSERVER_HOST=localhost:1780 ``` ```bash VITE_APP_SNAPSERVER_HOST=snapserver.example.com:1780 ``` -------------------------------- ### Get Snapcast Stream by ID Source: https://github.com/snapcast/snapweb/blob/develop/_autodocs/api-reference/SnapControl.md Retrieves a specific stream object from the server's current state using its unique ID. Throws an error if the stream is not found. ```typescript const stream = snapControl.getStream('default'); console.log(stream.status); ``` -------------------------------- ### Get Snapcast Group by ID Source: https://github.com/snapcast/snapweb/blob/develop/_autodocs/api-reference/SnapControl.md Retrieves a specific group object from the server's current state using its unique ID. Throws an error if the group is not found. ```typescript const group = snapControl.getGroup('e02e0600-e68c-b128-147b-58ca0a063ecf'); console.log(group.name); ``` -------------------------------- ### SnapWeb Module Dependencies Source: https://github.com/snapcast/snapweb/blob/develop/_autodocs/INDEX.md Outlines the module dependencies within the SnapWeb project, showing how React components interact with control and streaming modules. ```text SnapWeb (React component) ├── SnapControl (server control) │ ├── Snapcast.* (data models) │ └── config (settings) └── SnapStream (audio playback) ├── Web Audio API ├── Decoders (FLAC, Opus, PCM) └── TimeProvider (synchronization) ``` -------------------------------- ### Get Snapcast Client by ID Source: https://github.com/snapcast/snapweb/blob/develop/_autodocs/api-reference/SnapControl.md Retrieves a specific client object from the server's current state using its unique ID. Throws an error if the client is not found. ```typescript try { const client = snapControl.getClient('dc:a6:32:3f:bd:1c'); console.log(client.getName()); } catch (e) { console.error('Client not found'); } ``` -------------------------------- ### Get Persistent Value with Fallback Chain Source: https://github.com/snapcast/snapweb/blob/develop/_autodocs/api-reference/Configuration-API.md Demonstrates retrieving a value by trying multiple localStorage keys in sequence, falling back to a hardcoded default if none are found. ```typescript // Try specific key, fall back to general const host = getPersistentValue('snapserver.host') || getPersistentValue('server.host') || 'ws://localhost:1780'; ``` -------------------------------- ### Instantiate Snapcast Server Source: https://github.com/snapcast/snapweb/blob/develop/_autodocs/api-reference/Snapcast-Classes.md Initialize a Server object to represent the overall Snapcast server state. It can be created empty or with an existing JSON response from a GetStatus call. ```typescript import { Snapcast } from './snapcontrol'; // Empty server const server = new Snapcast.Server(); // Initialize with data const server = new Snapcast.Server(jsonResponse); ``` -------------------------------- ### Get Snapcast Server Base URL Source: https://github.com/snapcast/snapweb/blob/develop/_autodocs/configuration.md Access the current WebSocket URL for the Snapcast server. This value is automatically constructed based on environment variables or the current location. ```typescript config.baseUrl ``` -------------------------------- ### SnapWeb Project File Organization Source: https://github.com/snapcast/snapweb/blob/develop/_autodocs/INDEX.md Illustrates the directory structure of the SnapWeb project, including main markdown files and the API reference directory. ```text output/ ├── INDEX.md # This file ├── GETTING-STARTED.md # Introduction and quick start ├── ARCHITECTURE.md # System design and architecture ├── types.md # Type definitions reference ├── configuration.md # Configuration options ├── api-reference/ │ ├── SnapControl.md # Server control API │ ├── SnapStream.md # Audio streaming API │ ├── Snapcast-Classes.md # Data model classes │ └── Configuration-API.md # Configuration API └── (This document structure) ``` -------------------------------- ### Control Group Settings Source: https://github.com/snapcast/snapweb/blob/develop/_autodocs/GETTING-STARTED.md Manage group-level settings such as muting, switching streams, and assigning clients. Also includes functionality to get the average volume of online clients in a group. ```typescript // Get a group const group = snapControl.getGroup('group-id'); // Mute entire group snapControl.muteGroup('group-id', true); // Unmute snapControl.muteGroup('group-id', false); // Get average volume of online clients const volume = snapControl.getGroupVolume(group, true); console.log(`Group average volume: ${volume}%`); // Switch stream snapControl.setStream('group-id', 'Spotify'); // Change clients in group snapControl.setClients('group-id', ['client1', 'client2', 'client3']); ``` -------------------------------- ### Set Environment Variables for Development Source: https://github.com/snapcast/snapweb/blob/develop/_autodocs/configuration.md Configure development environment variables for Snapweb by creating a `.env.local` file in the project root. This allows customization of the server host, application name, and version. ```bash VITE_APP_SNAPSERVER_HOST=localhost:1780 VITE_APP_NAME=Snapweb VITE_APP_VERSION=0.9.3 ``` ```bash npm run dev ``` -------------------------------- ### Monitor Specific Server Changes Source: https://github.com/snapcast/snapweb/blob/develop/_autodocs/GETTING-STARTED.md Sets up a callback to detect and log new clients connecting to the Snapcast server. It compares the current server state with the previous one to identify changes. Initialize `previousServer` with a Snapcast.Server instance. ```typescript let previousServer = new Snapcast.Server(); snapControl.onChange = (control, newServer) => { // Detect new client const newClients = newServer.groups .flatMap(g => g.clients) .filter(c => !previousServer.getClient(c.id)); if (newClients.length > 0) { console.log('New clients connected:', newClients.map(c => c.getName())); } previousServer = newServer; }; ``` -------------------------------- ### Configure Snapweb Settings Source: https://github.com/snapcast/snapweb/blob/develop/_autodocs/GETTING-STARTED.md Manage persistent settings like the server URL and theme using the configuration API, which stores data in localStorage. ```typescript import { config, Theme } from './config'; config.baseUrl = 'ws://localhost:1780'; config.theme = Theme.Dark; config.showOffline = true; ``` -------------------------------- ### ServerSettingsMessage Source: https://github.com/snapcast/snapweb/blob/develop/_autodocs/api-reference/SnapStream.md Contains server configuration settings related to audio buffering, latency, and volume control. ```APIDOC ## Class: ServerSettingsMessage (extends BaseMessage) ### Description Server configuration for audio buffering and volume. ### Properties - **bufferMs** (number): Server buffer duration in milliseconds. - **latency** (number): Additional latency in milliseconds. - **volumePercent** (number): Volume level (0-100). - **muted** (boolean): Mute state of the server. ``` -------------------------------- ### Instantiate Snapcast Properties Source: https://github.com/snapcast/snapweb/blob/develop/_autodocs/api-reference/Snapcast-Classes.md Initialize a Properties object with a JSON payload detailing playback status, volume, and control capabilities. This is useful for representing the current state of an audio stream. ```typescript import { Snapcast } from './snapcontrol'; const propsJson = { playbackStatus: "playing", volume: 100, canControl: true, canSeek: true, canPlay: true, canPause: true, canGoNext: true, canGoPrevious: true, loopStatus: "none", shuffle: false, metadata: { /* ... */ } }; const props = new Snapcast.Properties(propsJson); console.log(props.playbackStatus); // "playing" ``` -------------------------------- ### Check Server Status (Troubleshooting) Source: https://github.com/snapcast/snapweb/blob/develop/_autodocs/GETTING-STARTED.md Verifies if the Snapcast server is running and accessible on the default port. This is a common step for diagnosing connection issues. ```bash snapserver -h ``` -------------------------------- ### Snapcast.Host Class Source: https://github.com/snapcast/snapweb/blob/develop/_autodocs/api-reference/Snapcast-Classes.md Represents information about a physical or virtual device. It includes properties like architecture, IP address, MAC address, name, and operating system. ```APIDOC ## Class: Host Represents information about a physical or virtual device. **Namespace**: `Snapcast.Host` ### Constructor ```typescript constructor(json: any) ``` **Parameters**: - **json** (any): Object with arch, ip, mac, name, os properties **Example**: ```typescript const hostJson = { arch: "armv7l", ip: "192.168.0.3", mac: "dc:a6:32:3f:bd:1c", name: "raspberrypi", os: "Raspbian GNU/Linux 11 (bullseye)" }; const host = new Snapcast.Host(hostJson); console.log(host.name); // "raspberrypi" ``` ### Properties - **arch** (string): CPU architecture (e.g., "armv7l", "web", "arm64-v8a") - **ip** (string): IP address (IPv4 or IPv6) - **mac** (string): MAC address (00:00:00:00:00:00 for web clients) - **name** (string): Hostname or device name - **os** (string): Operating system string ### Methods #### fromJson(json: any): void Parses JSON object into Host properties. **Example**: ```typescript const host = new Snapcast.Host({}); host.fromJson(jsonData); ``` ``` -------------------------------- ### Import Configuration Object Source: https://github.com/snapcast/snapweb/blob/develop/_autodocs/api-reference/Configuration-API.md Import the main configuration object and the Theme enum from the config module. ```typescript import { config, Theme } from './config'; ``` -------------------------------- ### SnapControl Constructor Source: https://github.com/snapcast/snapweb/blob/develop/_autodocs/api-reference/SnapControl.md Creates a new SnapControl instance with default state. No parameters are required. ```APIDOC ## SnapControl Constructor ### Description Creates a new SnapControl instance with default state. ### Parameters **No parameters** ### Returns SnapControl instance ### Example ```typescript import { SnapControl } from './snapcontrol'; const snapControl = new SnapControl(); ``` ``` -------------------------------- ### VITE_APP_SNAPSERVER_HOST Source: https://github.com/snapcast/snapweb/blob/develop/_autodocs/api-reference/Configuration-API.md Configures the default Snapcast server address at build time. This environment variable specifies the hostname and port for the server, allowing for flexible deployment configurations. ```APIDOC ## Environment Variable: VITE_APP_SNAPSERVER_HOST Default Snapcast server address. ### Format `hostname:port` ### Example .env.local ```bash VITE_APP_SNAPSERVER_HOST = localhost:1780 VITE_APP_SNAPSERVER_HOST = snapcast.example.com:1780 ``` ### Runtime Access ```typescript const host = import.meta.env.VITE_APP_SNAPSERVER_HOST; ``` ### Default Behavior If not set, uses `window.location.host` (current page host) ``` -------------------------------- ### Snapweb Module Structure Source: https://github.com/snapcast/snapweb/blob/develop/_autodocs/ARCHITECTURE.md Overview of the source code directory structure for the Snapweb project. ```tree src/ ├── main.tsx # React entry point ├── config.ts # Configuration management ├── snapcontrol.ts # Control API + data models ├── snapstream.ts # Audio streaming + decoding └── components/ ├── SnapWeb.tsx # Main app component ├── Server.tsx # Server view ├── Group.tsx # Playback group component ├── Client.tsx # Client/device component ├── Settings.tsx # Settings dialog └── AboutDialog.tsx # About dialog ``` -------------------------------- ### Set All Client Volumes Source: https://github.com/snapcast/snapweb/blob/develop/_autodocs/GETTING-STARTED.md Iterates through all connected clients across all groups and sets their volume to a specified level. Ensure snapControl is initialized. ```typescript function setAllVolumes(snapControl, volume) { for (const group of snapControl.server.groups) { for (const client of group.clients) { if (client.connected) { snapControl.setVolume(client.id, volume); } } } } // Usage setAllVolumes(snapControl, 50); ``` -------------------------------- ### Server Class Source: https://github.com/snapcast/snapweb/blob/develop/_autodocs/api-reference/Snapcast-Classes.md The root object representing the complete Snapcast server state. It can be initialized with server state data from a `GetStatus` response or as an empty object. ```APIDOC ## Class: Server Root object representing complete Snapcast server state. **Namespace**: `Snapcast.Server` ### Constructor ```typescript constructor(json?: any) ``` | Parameter | Type | Optional | Description | |-----------|------|----------|-------------| | json | any | ✓ | Server state from GetStatus response | ``` -------------------------------- ### Snapcast Server Connection Flow Source: https://github.com/snapcast/snapweb/blob/develop/_autodocs/ARCHITECTURE.md Details the process of establishing a WebSocket connection to the Snapcast server and retrieving initial status. ```mermaid graph TD SnapControl.connect(baseUrl) ↓ WebSocket opens to /jsonrpc endpoint ↓ Send Server.GetStatus request ↓ Server responds with complete state ↓ Parse into Snapcast.Server object ↓ Invoke onChange callback ↓ React components update UI ``` -------------------------------- ### Receive and Play Audio with SnapStream Source: https://github.com/snapcast/snapweb/blob/develop/_autodocs/GETTING-STARTED.md Instantiate SnapStream to receive audio from the Snapcast server. Note that browser autoplay policies may require user interaction to resume playback. ```typescript import { SnapStream } from './snapstream'; const stream = new SnapStream('ws://localhost:1780'); // Browser autoplay policy requires user interaction stream.resume(); ``` -------------------------------- ### Class Hierarchy Overview Source: https://github.com/snapcast/snapweb/blob/develop/_autodocs/types.md Provides a visual representation of the class hierarchy in Snapcast, showing relationships between Host, Client, Group, Metadata, Properties, Stream, Server, and SnapControl. ```plaintext Host Client ├─ host: Host └─ lastSeen: { sec, usec } Group └─ clients: Client[] Metadata Properties ├─ playbackStatus: PlaybackStatus └─ metadata?: Metadata Stream ├─ uri: { raw, scheme, host, path, fragment, query } └─ properties: Properties Server ├─ groups: Group[] ├─ server.host: Host ├─ server.snapserver: { ... } └─ streams: Stream[] SnapControl └─ server: Server ``` -------------------------------- ### Find and Control a Client by Name Source: https://github.com/snapcast/snapweb/blob/develop/_autodocs/GETTING-STARTED.md A utility function to find a client by its name and set its volume. This pattern is useful for targeted client control within the Snapcast system. ```typescript function setClientVolumeByName(snapControl, clientName, volume) { const client = snapControl.server.groups .flatMap(g => g.clients) .find(c => c.getName() === clientName); if (client) { snapControl.setVolume(client.id, volume); return true; } return false; } // Usage setClientVolumeByName(snapControl, 'Living Room', 75); ``` -------------------------------- ### Access VITE_APP_SNAPSERVER_HOST at Runtime Source: https://github.com/snapcast/snapweb/blob/develop/_autodocs/configuration.md Demonstrates how to access the `VITE_APP_SNAPSERVER_HOST` environment variable within your TypeScript code using `import.meta.env`. ```typescript import.meta.env.VITE_APP_SNAPSERVER_HOST ```