### Setup Hydra Project Source: https://github.com/hydra-synth/hydra/blob/main/_autodocs/INDEX.md Clone the repository, navigate to the directory, install dependencies, and start the development server. ```bash git clone cd hydra npm install npm run dev ``` -------------------------------- ### Load Example Sketch Source: https://github.com/hydra-synth/hydra/blob/main/_autodocs/api-reference/extension-store.md Emits an event to load a specific example sketch by its URL. Requires the index of the extension and the index of the example within that extension's examples array. ```javascript emitter.emit('extensions: load example', extensionIndex, exampleIndex) ``` ```javascript // Load first example of second extension emitter.emit('extensions: load example', 1, 0) ``` -------------------------------- ### List Connected Peers Example Source: https://github.com/hydra-synth/hydra/blob/main/_autodocs/api-reference/patch-bay.md Example of logging the list of connected peers and their nicknames to the console. The output is a map of peer IDs to their respective nicknames. ```javascript const connectedPeers = pb.list() console.log('Available sources:', connectedPeers) // Output: { 'peer123': 'alice', 'peer456': 'bob' } ``` -------------------------------- ### Initiate Connection to Peer Source Example Source: https://github.com/hydra-synth/hydra/blob/main/_autodocs/api-reference/patch-bay.md Example of initiating a connection to a peer named 'alice' and handling the received stream by creating a video element and playing the stream. ```javascript pb.initSource('alice', (stream) => { const video = document.createElement('video') video.srcObject = stream video.play() }) ``` -------------------------------- ### Example Entry Structure Source: https://github.com/hydra-synth/hydra/blob/main/_autodocs/api-reference/extension-store.md Defines the full data structure for an example entry in the store, including name, description, thumbnail, example URLs, and related extensions. ```javascript { name: "Kaleidoscope", description: "Beautiful kaleidoscopic patterns", thumbnail: "kaleid.png", examples: [ "/?code=...", "/?code=..." ], related: ["pixelate", "rotate"] } ``` -------------------------------- ### Example Workflow: User Interaction with Extension Store Source: https://github.com/hydra-synth/hydra/blob/main/_autodocs/api-reference/extension-store.md This snippet outlines a typical user interaction workflow within the Extension Store, from selecting a category to adding an example to the editor. ```javascript // 1. User clicks "Examples" category emitter.emit('extensions: select category', 2) // → Fetches examples.json // 2. User clicks an example thumbnail // → Gallery loads example code // 3. User clicks "Add to Editor" button emitter.emit('extensions: add to editor', 0) // → Example code added to top of editor ``` -------------------------------- ### Example Entry Format Source: https://github.com/hydra-synth/hydra/blob/main/_autodocs/api-reference/extension-store.md Specifies the format for an individual example entry, including its name, description, thumbnail, an array of sketch URLs, and an optional load code snippet. ```javascript { name: string, // Example name description: string, // What the example demonstrates thumbnail: string, // Preview image examples: [string], // Array of example sketch URLs load: string // Optional: code to load } ``` -------------------------------- ### Run Hydra Dev Environment Source: https://github.com/hydra-synth/hydra/blob/main/README.md Starts the development server for Hydra. Requires dependencies to be installed. ```bash npm dev ``` -------------------------------- ### Set Peer Nickname Example Source: https://github.com/hydra-synth/hydra/blob/main/_autodocs/api-reference/patch-bay.md Example of setting a peer's nickname to 'alice'. This allows other peers to connect to 'alice' using this nickname. ```javascript pb.setName('alice') // Other peers can now connect to 'alice' ``` -------------------------------- ### HydraCanvas Constructor Example Source: https://github.com/hydra-synth/hydra/blob/main/_autodocs/api-reference/hydra-component.md Example of instantiating the HydraCanvas with a specific ID, application state, and emit function. ```javascript const hydra = new HydraCanvas('hydra-ui', appState, emit) ``` -------------------------------- ### extensions: load example Source: https://github.com/hydra-synth/hydra/blob/main/_autodocs/api-reference/extension-store.md Loads a specific example sketch from an extension by its URL. The UI automatically switches away from the extensions panel after loading. ```APIDOC ## extensions: load example ### Description Loads an example sketch by its URL. It finds the example entry, processes its URL, and emits an event to load and evaluate the code, automatically switching the UI context. ### Method EMIT ### Parameters #### Path Parameters - **extensionIndex** (number, required): Index of the extension in the current category. - **exampleIndex** (number, required): Index of the example within the extension's examples array. ### Returns undefined ### Request Example ```javascript // Load first example of second extension emitter.emit('extensions: load example', 1, 0) ``` ``` -------------------------------- ### Tone.js Synth Example Source: https://github.com/hydra-synth/hydra/blob/main/README.md Creates a Tone.js synthesizer and triggers a note. ```javascript synth = new Tone.Synth().toDestination(); synth.triggerAttackRelease("C4", "8n"); ``` -------------------------------- ### List Peers Example Source: https://github.com/hydra-synth/hydra/blob/main/_autodocs/types.md An example of listing available peers in the PatchBay network. The function returns an object mapping peer IDs to their nicknames. ```javascript const peers = pb.list() // Returns: { 'peer123': 'alice', 'peer456': 'bob' } ``` -------------------------------- ### Gallery Sketch Example Source: https://github.com/hydra-synth/hydra/blob/main/_autodocs/types.md An example of creating and setting a sketch object in the gallery. The 'code' property is Base64-encoded JavaScript. ```javascript const sketch = { sketch_id: 'abc123', code: 'b3NjKCkub3V0KCk=', parent: 'parent123' } gallery.setSketch(sketch) ``` -------------------------------- ### Get Example Sketch by ID Source: https://github.com/hydra-synth/hydra/blob/main/_autodocs/api-reference/gallery.md Retrieves a specific example sketch from the gallery using its unique identifier. This is an internal method primarily used during the sketch loading process. ```javascript const example = gallery.getExampleById(sketchId) ``` -------------------------------- ### REPLEvalInfo Example Source: https://github.com/hydra-synth/hydra/blob/main/_autodocs/types.md Shows how to use the REPLEvalInfo callback to handle evaluation results, including error checking. ```javascript repl.eval('osc().out()', (info) => { if (info.isError) { console.error(info.errorMessage) } }) ``` -------------------------------- ### Gallery Code Parameter Example Source: https://github.com/hydra-synth/hydra/blob/main/_autodocs/configuration.md Shows an example of encoding a Hydra code string using the `encodeBase64` function and constructing a gallery URL with the encoded code. ```javascript const code = 'osc(20).rotate(0.5).out()' const encoded = gallery.encodeBase64(code) // Result: "b3NjKDIwKS5yb3RhdGUoMC41KS5vdXQoKQ==" // URL: /?code=b3NjKDIwKS5yb3RhdGUoMC41KS5vdXQoKQ== ``` -------------------------------- ### Install Hydra Dependencies Source: https://github.com/hydra-synth/hydra/blob/main/README.md Installs project dependencies using npm. Requires Node.js and npm to be installed. ```bash npm install ``` -------------------------------- ### Examples Category Structure Source: https://github.com/hydra-synth/hydra/blob/main/_autodocs/api-reference/extension-store.md Defines the structure for the 'examples' category, used for curated example sketches. It includes name, slug, an empty entries array, and a hasLoaded flag. ```javascript { name: 'examples', slug: 'examples', entries: [], hasLoaded: false } ``` -------------------------------- ### CodeMirror Position Example Source: https://github.com/hydra-synth/hydra/blob/main/_autodocs/types.md Illustrates how to create and use a Position object with editor functions. ```javascript const pos = { line: 5, ch: 10 } editor.flashCode(pos, { line: 10, ch: 0 }) ``` -------------------------------- ### CodeBlock Example Source: https://github.com/hydra-synth/hydra/blob/main/_autodocs/types.md Demonstrates retrieving the current code block from the editor and accessing its text content. ```javascript const block = editor.getCurrentBlock() console.log(block.text) // Code in current block emitter.emit('repl: eval', block.text) ``` -------------------------------- ### System Test Example Source: https://github.com/hydra-synth/hydra/blob/main/_autodocs/architecture.md Illustrates a system test involving emitting a 'load and eval code' event and verifying the outcome. ```javascript emitter.emit('load and eval code', code) // Verify: editor loaded, code executed, no errors ``` -------------------------------- ### setRandomSketch() Source: https://github.com/hydra-synth/hydra/blob/main/_autodocs/api-reference/gallery.md Loads a random sketch from examples or generates a random one if no examples are available. It ensures a different example than the previously loaded one is selected. ```APIDOC ## setRandomSketch() ### Description Loads a random sketch from examples or generates a random one if no examples are available. It ensures a different example than the previously loaded one is selected. ### Method JavaScript Function Call ### Endpoint N/A ### Parameters None ### Request Example ```javascript gallery.setRandomSketch() ``` ### Response #### Success Response - undefined ### Response Example ```javascript // No specific output, modifies internal state ``` ``` -------------------------------- ### Instantiate Gallery with Callback Source: https://github.com/hydra-synth/hydra/blob/main/_autodocs/api-reference/gallery.md Example of instantiating the Gallery class with a specific callback function. This callback logs information about the loaded sketch, such as whether it was found and the length of its code. ```javascript const gallery = new Gallery((code, found) => { console.log('Sketch loaded:', found ? 'from server' : 'from URL') console.log('Code length:', code.length) }, state, emitter) ``` -------------------------------- ### Hydra Rendering Example Source: https://github.com/hydra-synth/hydra/blob/main/_autodocs/api-reference/hydra-component.md Example of using the Hydra synth engine to generate output. This code is typically run after the engine has been loaded and is accessible globally. ```javascript // Called automatically by Choo on component mount // User code accesses via: window.hydraSynth osc(20).out() ``` -------------------------------- ### Integration Test Example Source: https://github.com/hydra-synth/hydra/blob/main/_autodocs/architecture.md Shows an integration test simulating an event emission and checking for state changes. ```javascript emitter.emit('repl: eval', 'osc().out()') expect(state.errorMessage).toBe('') ``` -------------------------------- ### Unit Test Example Source: https://github.com/hydra-synth/hydra/blob/main/_autodocs/architecture.md Demonstrates a unit test for a function, likely involving encoding data. ```javascript expect(gallery.encodeBase64('test')).toBe('...') ``` -------------------------------- ### Initialize Specific Webcam Source: https://github.com/hydra-synth/hydra/blob/main/README.md Initializes a specific webcam using an index, useful when multiple cameras are connected. The index starts from 0. ```javascript s0.initCam(1) // initialize a webcam in source buffer s0 ``` -------------------------------- ### Initialize PatchBay with Hydra Source: https://github.com/hydra-synth/hydra/blob/main/_autodocs/api-reference/patch-bay.md Example of initializing PatchBay within a Hydra application. It connects to a specified signaling server and room, with options to make the PatchBay instance globally accessible. ```javascript const hydra = new Hydra({ canvas: element }) const pb = new PBLive() pb.init(hydra.captureStream, { server: 'https://patch-bay.glitch.me/', room: 'collaborative-session', makeGlobal: true }) ``` -------------------------------- ### Bash Code Block Example Source: https://github.com/hydra-synth/hydra/blob/main/_autodocs/DOCUMENTATION_SUMMARY.md Bash commands are presented in fenced code blocks marked with 'bash'. ```bash ```bash ... ``` ``` -------------------------------- ### Accessing Extension Entry Load Code Source: https://github.com/hydra-synth/hydra/blob/main/_autodocs/types.md Example demonstrating how to retrieve the 'load' property from an extension entry, which contains the code snippet to be added to the editor. ```javascript const ext = state.extensions.categories[0].entries[0] console.log(ext.load) // Code to add to editor ``` -------------------------------- ### Load Random Sketch Source: https://github.com/hydra-synth/hydra/blob/main/_autodocs/api-reference/gallery.md Loads a random sketch from available examples or generates a new random visualization if no examples are present. Ensures a different sketch is loaded than the previously selected one. ```javascript gallery.setRandomSketch() ``` ```javascript gallery.setRandomSketch() // Loads random example or generates random osc visualization ``` -------------------------------- ### Instantiate HydraCanvas Component Source: https://github.com/hydra-synth/hydra/blob/main/_autodocs/api-reference/hydra-component.md Import and create a new instance of the HydraCanvas component. This is typically done during application setup. ```javascript import HydraCanvas from './src/views/Hydra.js' const component = new HydraCanvas('hydra-canvas', state, emit) ``` -------------------------------- ### Import and Register Extension Store Source: https://github.com/hydra-synth/hydra/blob/main/_autodocs/api-reference/extension-store.md Import the extension store module and register it with the Choo application. This is the initial setup for enabling the extension system. ```javascript import extensionStore from './src/stores/extension-store.js' // Registered with Choo app.use(extensionStore) ``` -------------------------------- ### flashCode(start, end) Source: https://github.com/hydra-synth/hydra/blob/main/_autodocs/api-reference/editor.md Highlights a specified section of code within the editor for a duration of 300ms, providing visual feedback. If no parameters are provided, it highlights all code. ```APIDOC ## flashCode(start, end) ### Description Highlights a section of code with visual feedback for 300ms. ### Parameters #### Path Parameters - **start** (object, optional) - CodeMirror position `{line: number, ch: number}` - **end** (object, optional) - CodeMirror position `{line: number, ch: number}` ### Default Behavior - Highlights all code from first to last line ### Example ```javascript // Highlight specific lines editor.flashCode( {line: 0, ch: 0}, {line: 5, ch: 0} ) ``` ``` -------------------------------- ### Configure Code Formatting Settings Source: https://github.com/hydra-synth/hydra/blob/main/_autodocs/configuration.md Example of configuring code formatting settings using the beautify library. These settings control indentation, line breaks for chained methods, and the use of tabs. ```javascript editor.formatCode() // Uses these settings: const formatted = beautify(code, { indent_size: 2, break_chained_methods: true, indent_with_tabs: true }) ``` -------------------------------- ### PatchBay Initialization in Hydra Source: https://github.com/hydra-synth/hydra/blob/main/_autodocs/api-reference/patch-bay.md Initializes the PatchBay instance and integrates it with Hydra. This setup enables core functionalities like setting names and connecting to streams. ```javascript // In Hydra.js this.pb = new PatchBay() hydraOptions.pb = this.pb this.hydra = new Hydra(hydraOptions) this.pb.init(this.hydra.captureStream, { server: this.state.serverURL, room: 'iclc' }) window.pb = this.pb ``` -------------------------------- ### Mutator Undo/Redo Operations Source: https://github.com/hydra-synth/hydra/blob/main/_autodocs/api-reference/mutator.md Illustrates how to use the Mutator's undo/redo system to manage state history. Shows examples of mutating, undoing, and redoing operations. ```javascript mutator.mutate({}) mutator.mutate({}) mutator.doUndo() mutator.doUndo() mutator.doRedo() mutator.doRedo() ``` -------------------------------- ### Configure CodeMirror Editor Theme Source: https://github.com/hydra-synth/hydra/blob/main/_autodocs/configuration.md Example of configuring the CodeMirror theme for the editor. The theme option in the editor constructor determines the visual appearance of the code editor. ```javascript const opts = { theme: 'tomorrow-night-eighties', // ... } ``` -------------------------------- ### Set Extension Repository Base URL Source: https://github.com/hydra-synth/hydra/blob/main/_autodocs/configuration.md Defines the base URL for fetching extension metadata and thumbnails. Used for user extensions, third-party libraries, and examples. ```javascript const BASE_URL = "https://raw.githubusercontent.com/hydra-synth/hydra-extensions/main/" ``` -------------------------------- ### init(stream, options) Source: https://github.com/hydra-synth/hydra/blob/main/_autodocs/api-reference/patch-bay.md Initializes the PatchBay connection to the signaling server and joins a specified room. ```APIDOC ## init(stream, options) ### Description Initializes the PatchBay connection to signaling server. ### Method `init` ### Parameters - `stream` (MediaStream): Canvas capture stream to broadcast - `options` (object): - `server` (string): Signaling server URL - `room` (string): Room name to join - `makeGlobal` (boolean, default: true): Expose as `window.pb` - `setTitle` (boolean, default: true): Update page title with nickname ### Returns undefined ### Behavior - Creates socket.io connection to signaling server - Joins specified room with unique peer ID - Registers event listeners for peer discovery - Restores previous session ID if available - Sets initial peer name to session nickname or ID ### Example ```javascript const hydra = new Hydra({ canvas: element }) const pb = new PBLive() pb.init(hydra.captureStream, { server: 'https://patch-bay.glitch.me/', room: 'collaborative-session', makeGlobal: true }) ``` ``` -------------------------------- ### Initialize and Render Webcam Source: https://github.com/hydra-synth/hydra/blob/main/README.md Initializes the webcam in source buffer s0 and renders its output. Ensure your browser has camera permissions enabled. ```javascript s0.initCam() // initialize a webcam in source buffer s0 src(s0).out() // render source buffer s0 ``` -------------------------------- ### Initialize Desktop Screen Capture Source: https://github.com/hydra-synth/hydra/blob/main/README.md Opens a dialog to select a screen tab for input texture. Requires `s0` to be initialized. ```javascript s0.initScreen() src(s0).out() ``` -------------------------------- ### Set VITE_SERVER_URL Environment Variable Source: https://github.com/hydra-synth/hydra/blob/main/_autodocs/configuration.md Example of setting the VITE_SERVER_URL environment variable in a .env file to enable backend server features. This is used to configure the backend server URL for gallery and networking. ```bash # Create .env file in project root echo 'VITE_SERVER_URL=http://localhost:8000' > .env npm run dev ``` -------------------------------- ### Initialize p5.js Instance Source: https://github.com/hydra-synth/hydra/blob/main/README.md Initializes a new p5.js instance in instance mode. This should typically be called only once. ```javascript p5 = new P5() // {width: window.innerWidth, height:window.innerHeight, mode: 'P2D'} ``` -------------------------------- ### Initialize and Render Video Source Source: https://github.com/hydra-synth/hydra/blob/main/README.md Initializes a video file as a source in buffer s0 and renders it. Ensure the video URL is accessible. ```javascript s0.initVideo("https://media.giphy.com/media/AS9LIFttYzkc0/giphy.mp4") src(s0).out() ``` -------------------------------- ### Import and Initialize Gallery Source: https://github.com/hydra-synth/hydra/blob/main/_autodocs/api-reference/gallery.md Import the Gallery class and create a new instance. The constructor requires a callback function for sketch loading, the application state, and an event emitter. ```javascript import Gallery from './src/stores/gallery.js' const gallery = new Gallery(callback, state, emitter) ``` -------------------------------- ### initSource(nick, callback) Source: https://github.com/hydra-synth/hydra/blob/main/_autodocs/api-reference/patch-bay.md Initiates a connection to a specific peer identified by their nickname and provides a callback for handling the incoming media stream. ```APIDOC ## initSource(nick, callback) ### Description Initiates connection to a specific peer source. ### Method `initSource` ### Parameters - `nick` (string): Nickname of peer to connect to - `callback` (function, optional): Called when stream is ready ### Returns undefined ### Behavior - Looks up peer ID from nickname - Initiates WebRTC connection to that peer - Requests video/audio from peer - Calls callback when media stream is received ### Example ```javascript pb.initSource('alice', (stream) => { // Handle incoming stream }) ``` ``` -------------------------------- ### Initialize and Render Image Source Source: https://github.com/hydra-synth/hydra/blob/main/README.md Initializes an image file as a source in buffer s0 and renders it. Ensure the image URL is accessible. ```javascript s0.initImage("https://upload.wikimedia.org/wikipedia/commons/2/25/Hydra-Foto.jpg") src(s0).out() ``` -------------------------------- ### Import and Initialize Editor Source: https://github.com/hydra-synth/hydra/blob/main/_autodocs/api-reference/editor.md Import the Editor class and create a new instance, mounting it to a specified parent HTML element. ```javascript import Editor from './src/views/editor/editor.js' // Constructor const editor = new Editor(parentElement) ``` -------------------------------- ### Extension Entry Interface Source: https://github.com/hydra-synth/hydra/blob/main/_autodocs/types.md Defines the structure for an individual extension or example entry, including its name, description, author, loadable code, thumbnail, and optional examples or tags. Accessed via state.extensions.categories[index].entries[i]. ```typescript interface ExtensionEntry { name: string // Extension/example name description: string // Description text author?: string // Author information load: string // Code snippet to insert into editor thumbnail: string // URL to preview image examples?: string[] // Array of example sketch URLs (for examples category) tags?: string[] // Optional tags/categories } ``` -------------------------------- ### Import REPL Module Source: https://github.com/hydra-synth/hydra/blob/main/_autodocs/api-reference/repl.md Import the REPL singleton object from its source path. This is the entry point for using the evaluation engine. ```javascript import repl from './src/stores/repl-v2.js' repl.eval(code, callback) ``` -------------------------------- ### JavaScript Class Naming Convention Source: https://github.com/hydra-synth/hydra/blob/main/_autodocs/DOCUMENTATION_SUMMARY.md Classes follow the PascalCase convention, for example, 'Editor' or 'Gallery'. ```javascript Editor ``` ```javascript Gallery ``` -------------------------------- ### Instantiate Editor with HTML Element Source: https://github.com/hydra-synth/hydra/blob/main/_autodocs/api-reference/editor.md Create an Editor instance by passing a query selector for the target HTML element where the editor will be mounted. ```javascript const textArea = document.querySelector('textarea') const editor = new Editor(textArea) ``` -------------------------------- ### Listen for 'ready' Event Source: https://github.com/hydra-synth/hydra/blob/main/_autodocs/api-reference/patch-bay.md Fired when connected to signaling server and ready to receive peers. Use this to log connection status and retrieve the peer ID. ```javascript pb.on('ready', () => { console.log('Connected to server, peer ID:', pb.id) }) ``` -------------------------------- ### ui: show extensions Source: https://github.com/hydra-synth/hydra/blob/main/_autodocs/api-reference/store.md Shows the extensions panel and the info panel simultaneously, and loads extensions. ```APIDOC ## ui: show extensions ### Description Shows the extensions panel and info panel together. ### Method EMIT ### Behavior - Sets `state.showExtensions` to true - Sets `state.showInfo` to true - Emits 'extensions: select category' to load extensions - Triggers render ``` -------------------------------- ### JavaScript Code Block Example Source: https://github.com/hydra-synth/hydra/blob/main/_autodocs/DOCUMENTATION_SUMMARY.md JavaScript code is enclosed in fenced code blocks marked with 'javascript'. ```javascript ```javascript ... ``` ``` -------------------------------- ### Clear p5.js Canvas Source: https://github.com/hydra-synth/hydra/blob/main/README.md Clears the p5.js canvas. In live coding, setup functions can be called directly. ```javascript p5.clear() ``` -------------------------------- ### CodeBlock Interface Source: https://github.com/hydra-synth/hydra/blob/main/_autodocs/types.md Represents a block of code within the editor, including its start and end positions and text content. ```typescript interface CodeBlock { start: Position // Starting position of block end: Position // Ending position of block text: string // Content of the block } ``` -------------------------------- ### Initialize Three.js Scene Source: https://github.com/hydra-synth/hydra/blob/main/README.md Sets up a basic Three.js scene, camera, and renderer. The 'update' function is reserved for per-frame rendering. ```javascript scene = new THREE.Scene() camera = new THREE.PerspectiveCamera(75, window.innerWidth / window.innerHeight, 0.1, 1000) renderer = new THREE.WebGLRenderer() renderer.setSize(width, height) geometry = new THREE.BoxGeometry() material = new THREE.MeshBasicMaterial({color: 0x00ff00}) cube = new THREE.Mesh(geometry, material); scene.add(cube) camera.position.z = 1.5 ``` -------------------------------- ### Build Commands for Vite Source: https://github.com/hydra-synth/hydra/blob/main/_autodocs/configuration.md Common npm commands for building the project for production or running the development server. ```bash npm run build # Production build ``` ```bash npm run dev # Development server ``` -------------------------------- ### Accessing PatchBay Session Nickname Source: https://github.com/hydra-synth/hydra/blob/main/_autodocs/types.md Example of how to access the previously set nickname from a PatchBay session, which is auto-loaded from sessionStorage on initialization. ```javascript // Auto-loaded from sessionStorage on initialization pb.session.nick // Previously set nickname ``` -------------------------------- ### TypeScript Interface Code Block Example Source: https://github.com/hydra-synth/hydra/blob/main/_autodocs/DOCUMENTATION_SUMMARY.md TypeScript interfaces are documented using fenced code blocks marked with 'typescript'. ```typescript ```typescript ... ``` ``` -------------------------------- ### initRtcPeer Source: https://github.com/hydra-synth/hydra/blob/main/_autodocs/api-reference/patch-bay.md Creates a WebRTC connection to a specific peer. This method is essential for establishing new communication channels. ```APIDOC ## initRtcPeer(id, opts) ### Description Creates WebRTC connection to a peer. ### Method Not applicable (Method of a class instance) ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body - **id** (string) - Required - Peer ID to connect to - **opts** (object) - Required - SimplePeer options ### Request Example ```javascript pb.initRtcPeer('peer123', { initiator: true, stream: mediaStream }) ``` ### Response #### Success Response (200) None #### Response Example None ``` -------------------------------- ### Composite Webcam and Gradient Source: https://github.com/hydra-synth/hydra/blob/main/README.md Initializes the webcam in buffer o0 and composites it with a gradient in buffer o1 using the 'diff' operation, then renders o1. This demonstrates combining different sources. ```javascript s0.initCam() // initialize a webcam in source buffer s0 src(s0).out(o0) // set the source of o0 to render the buffer containing the webcam osc(10, 0.2, 0.8).diff(o0).out(o1) // initialize a gradient in output buffer o1, composite with the contents of o0 render(o1) // render o1 to the screen ``` -------------------------------- ### Get and Flash Current Line Source: https://github.com/hydra-synth/hydra/blob/main/_autodocs/api-reference/editor.md Retrieve the code from the current line where the cursor is positioned and provide visual feedback by flashing the line. ```javascript const line = editor.getLine() // Line is executed and highlighted ``` -------------------------------- ### Get Editor Value Source: https://github.com/hydra-synth/hydra/blob/main/_autodocs/api-reference/editor.md Retrieve the current text content of the editor using the getValue method. This is useful for accessing user-inputted code. ```javascript const currentCode = editor.getValue() console.log('Current code:', currentCode) ``` -------------------------------- ### Listen for 'new peer' Event Source: https://github.com/hydra-synth/hydra/blob/main/_autodocs/api-reference/patch-bay.md Fired when a new peer joins the room. Logs the new peer's ID to the console. ```javascript pb.on('new peer', (peerId) => { console.log('New peer joined:', peerId) }) ``` -------------------------------- ### Build Hydra Project Source: https://github.com/hydra-synth/hydra/blob/main/_autodocs/INDEX.md Run the build script to compile the project for production. ```bash npm run build ``` -------------------------------- ### Configure Backend Server URL Source: https://github.com/hydra-synth/hydra/blob/main/_autodocs/api-reference/store.md Read the backend server URL from the `VITE_SERVER_URL` environment variable at build time. If undefined, the application runs in local-only mode. ```javascript const SERVER_URL = import.meta.env.VITE_SERVER_URL ``` -------------------------------- ### Hydra Synth Initialization Options Source: https://github.com/hydra-synth/hydra/blob/main/_autodocs/types.md Defines the options for initializing a new Hydra instance. Use this to configure canvas, audio detection, and GPU precision. ```typescript interface HydraOptions { canvas: HTMLCanvasElement // Target canvas element detectAudio: boolean // Enable audio input analysis precision?: 'highp' | 'mediump' // GPU precision level pb?: PatchBayInstance // Optional PatchBay networking } ``` ```javascript const hydraOptions = { canvas: canvasElement, detectAudio: true, precision: 'mediump' } const hydra = new Hydra(hydraOptions) ``` -------------------------------- ### Initialize PatchBay with Room Source: https://github.com/hydra-synth/hydra/blob/main/_autodocs/configuration.md Initializes the patch-bay connection, specifying the signaling server URL and a room name for peer discovery. Peers in the same room can connect. ```javascript this.pb.init(this.hydra.captureStream, { server: this.state.serverURL, room: 'iclc' }) ``` -------------------------------- ### Initialize WebRTC Peer Connection Source: https://github.com/hydra-synth/hydra/blob/main/_autodocs/api-reference/patch-bay.md Creates a WebRTC connection to a specific peer. Requires the peer ID and optional configuration like initiator and stream. ```javascript pb.initRtcPeer('peer123', { initiator: true, stream: mediaStream }) ``` -------------------------------- ### Network Request Monitoring Source: https://github.com/hydra-synth/hydra/blob/main/_autodocs/errors.md Example network requests to monitor in the browser's DevTools Network tab for debugging. This helps in identifying issues with API calls. ```text POST /sketch POST /image POST /sketchById GET extensions.json ``` -------------------------------- ### CodeMirror Editor Initialization Options Source: https://github.com/hydra-synth/hydra/blob/main/_autodocs/api-reference/editor.md Configuration object for initializing the CodeMirror editor. Sets the theme, language mode, line wrapping, and custom keymaps. ```javascript const opts = { theme: 'tomorrow-night-eighties', mode: { name: 'javascript', globalVars: true }, lineWrapping: true, styleSelectedText: true, extraKeys: extraKeys // Custom keymap } ``` -------------------------------- ### GalleryState Interface Definition Source: https://github.com/hydra-synth/hydra/blob/main/_autodocs/types.md Defines the overall state of the gallery, including lists of sketches and examples, the current sketch, and application state references. Accessed via state.gallery. ```typescript interface GalleryState { sketches: Sketch[] // Sketches loaded from server examples: Sketch[] // Built-in example sketches current: Sketch | null // Currently active sketch code: string | null // Current sketch code (decoded) exampleIndex: number | null // Index of last loaded example state: object // Reference to app state emitter: object // Choo event emitter serverURL: string // Backend server URL url: string // Current shareable URL searchParams: URLSearchParams // Parsed URL parameters } ``` -------------------------------- ### ui: show info Source: https://github.com/hydra-synth/hydra/blob/main/_autodocs/api-reference/store.md Shows the info panel and hides the extensions panel, as they are mutually exclusive. ```APIDOC ## ui: show info ### Description Shows the info panel. ### Method EMIT ### Behavior - Sets `state.showInfo` to true - Hides extensions panel (mutual exclusivity) ``` -------------------------------- ### Initiate Connection to Peer Source Source: https://github.com/hydra-synth/hydra/blob/main/_autodocs/api-reference/patch-bay.md Initiate a WebRTC connection to a specific peer identified by their nickname. A callback function is provided to handle the incoming media stream. ```javascript pb.initSource('alice', (stream) => { // Handle incoming stream }) ``` -------------------------------- ### AST Mutation Process with Acorn and Astring Source: https://github.com/hydra-synth/hydra/blob/main/_autodocs/api-reference/mutator.md Demonstrates the steps involved in transforming code using Abstract Syntax Tree (AST) manipulation. This includes parsing code, finding literal nodes, modifying a random literal, and regenerating the code. ```javascript // 1. Parse to AST let ast = Parser.parse(code, { locations: true, onComment }) // 2. Find Literal nodes let literals = [] walk(ast, (node) => { if (node.type === 'Literal') { literals.push(node) } }) // 3. Modify random literal let target = literals[Math.random() * literals.length] target.value = newRandomValue() // 4. Regenerate code let newCode = generate(ast) ``` -------------------------------- ### Default Canvas Element Creation Source: https://github.com/hydra-synth/hydra/blob/main/_autodocs/api-reference/hydra-component.md Creates the canvas element using default dimensions, which are the current window's inner width and height. This is a typical setup during initialization. ```javascript const canvas = component.createElement({ width: window.innerWidth, height: window.innerHeight }) ``` -------------------------------- ### Get Current Code Block Source: https://github.com/hydra-synth/hydra/blob/main/_autodocs/api-reference/editor.md Identify and retrieve the entire block of contiguous code where the cursor is located, delimited by blank lines. The block is also visually flashed. ```javascript const block = editor.getCurrentBlock() console.log('Block code:', block.text) emitter.emit('repl: eval', block.text) ``` -------------------------------- ### Show Info Panel Source: https://github.com/hydra-synth/hydra/blob/main/_autodocs/api-reference/store.md Explicitly shows the information panel by setting the `showInfo` state to true. This action also hides the extensions panel. ```javascript emitter.emit('ui: show info') ``` -------------------------------- ### Use Audio FFT Data Source: https://github.com/hydra-synth/hydra/blob/main/_autodocs/configuration.md Example of using the detected audio FFT data to control visual parameters. The 'a.fft[0]' value is used to modulate the frequency of an oscillator. ```javascript a.setBins(16) osc(() => a.fft[0] * 100).out() ``` -------------------------------- ### Choo Component Lifecycle Methods Source: https://github.com/hydra-synth/hydra/blob/main/_autodocs/architecture.md Understand the lifecycle of Choo components, from initialization in the constructor to mounting with `load()`, re-rendering with `update()`, and DOM creation with `createElement()`. ```javascript class Component { constructor(id, state, emit) { /* init */ } load(element) { /* mount */ } update(state) { /* re-render */ } createElement(options) { /* DOM */ } } ``` -------------------------------- ### Update Component State Source: https://github.com/hydra-synth/hydra/blob/main/_autodocs/api-reference/hydra-component.md Example of the update method, which is part of the Choo lifecycle. This method typically returns false as Hydra rendering is driven by the synth engine, not Choo re-renders. ```javascript const shouldRerender = component.update(newState) ``` -------------------------------- ### Initialize Hydra with PatchBay Networking Source: https://github.com/hydra-synth/hydra/blob/main/_autodocs/api-reference/hydra-component.md Initializes Hydra, setting up PatchBay for WebRTC networking if a server URL is provided. This enables peer-to-peer connections and exposes PatchBay globally. ```javascript if (this.state.serverURL === null) { // Local only mode this.hydra = new Hydra(hydraOptions) } else { // Enable networking this.pb = new PatchBay() hydraOptions.pb = this.pb this.hydra = new Hydra(hydraOptions) this.pb.init(this.hydra.captureStream, { server: this.state.serverURL, room: 'iclc' }) window.pb = this.pb } ``` -------------------------------- ### Clear Editor and Reset State Source: https://github.com/hydra-synth/hydra/blob/main/_autodocs/api-reference/store.md Resets the Hydra editor to its initial state by stopping all audio, clearing the canvas, resetting global variables, and clearing the URL. Use this to start a new session. ```javascript emitter.emit('clear all') ``` -------------------------------- ### Custom Signaling Server Configuration Source: https://github.com/hydra-synth/hydra/blob/main/_autodocs/api-reference/patch-bay.md Demonstrates how to override the default signaling server when initializing PatchBay. Provide your custom server URL to the 'server' option. ```javascript pb.init(stream, { server: 'https://custom-signaling-server.com' }) ``` -------------------------------- ### Deploy Hydra Project Source: https://github.com/hydra-synth/hydra/blob/main/_autodocs/INDEX.md Execute the publish script to push the built project to gh-pages for deployment. ```bash npm run publish # Push to gh-pages ``` -------------------------------- ### Define and Use Global Functions Source: https://github.com/hydra-synth/hydra/blob/main/_autodocs/api-reference/repl.md Define a function within the REPL and then call it. The function becomes globally available after definition. ```javascript repl.eval( ` function myPattern() { return osc(20).rotate(0.5) } myPattern().out() `, (info) => { if (!info.isError) { // Function is now global window.myPattern().out(o1) } }) ``` -------------------------------- ### Gallery Constructor Source: https://github.com/hydra-synth/hydra/blob/main/_autodocs/api-reference/gallery.md Initializes the Gallery class, managing sketch lifecycle operations. It takes a callback function, the application state, and an event emitter as arguments. ```APIDOC ## Constructor Gallery ### Description Initializes the Gallery class, managing sketch lifecycle operations. It takes a callback function, the application state, and an event emitter as arguments. ### Parameters #### Constructor Parameters - `callback` (function) - Required - Called when a sketch is loaded from URL. - `state` (object) - Required - Choo application state. - `emitter` (object) - Required - Choo event emitter for state updates. ### Callback Signature ```javascript (code: string, foundSketch: boolean) => { // code: The loaded sketch code // foundSketch: Whether sketch was found in database } ``` ### Behavior - Loads examples from `examples.json`. - Checks URL for sketch codes on initialization. - Sets up popstate listener for browser navigation. - Initializes with random sketch if no code in URL. ### Example ```javascript const gallery = new Gallery((code, found) => { console.log('Sketch loaded:', found ? 'from server' : 'from URL') console.log('Code length:', code.length) }, state, emitter) ``` ``` -------------------------------- ### Gallery Constructor Parameters Source: https://github.com/hydra-synth/hydra/blob/main/_autodocs/api-reference/gallery.md The Gallery constructor accepts a callback function, the application state object, and a Choo event emitter. The callback is invoked when a sketch is successfully loaded. ```javascript constructor(callback, state, emitter) ``` -------------------------------- ### Render Oscillator with Parameters Source: https://github.com/hydra-synth/hydra/blob/main/README.md Renders an oscillator with specified frequency, sync, and RGB offset. Use this to create basic visual patterns. ```javascript osc(20, 0.1, 0.8).out() ``` -------------------------------- ### Render Remote Stream Source: https://github.com/hydra-synth/hydra/blob/main/README.md Initializes a remote stream and renders it to the screen. Connections may take a few seconds. ```javascript s0.initStream("myGraphics") src(s0).out() ``` -------------------------------- ### Render All Output Buffers Source: https://github.com/hydra-synth/hydra/blob/main/README.md Renders all defined output buffers (o0, o1, o2, o3) to the screen. This is useful for visualizing all concurrent outputs. ```javascript render() ``` -------------------------------- ### Vite Build Configuration Source: https://github.com/hydra-synth/hydra/blob/main/_autodocs/configuration.md Basic Vite configuration file. Modify this file for custom build settings. ```javascript export default { // Build settings } ``` -------------------------------- ### Initialize PatchBay Connection Source: https://github.com/hydra-synth/hydra/blob/main/_autodocs/api-reference/patch-bay.md Initialize the PatchBay connection to a signaling server, joining a specific room. This method sets up the WebRTC connection and event listeners. ```javascript pb.init(captureStream, { server: 'https://patch-bay.example.com', room: 'iclc', makeGlobal: true, setTitle: true }) ``` -------------------------------- ### Fetching and Processing Extension Data Source: https://github.com/hydra-synth/hydra/blob/main/_autodocs/api-reference/extension-store.md Demonstrates how to fetch extension data from a JSON URL and append thumbnail URLs using the base URL. This is useful for loading extension information. ```javascript fetch('https://raw.githubusercontent.com/hydra-synth/hydra-extensions/main/extensions.json') .then(res => res.json()) .then(entries => { // entries is array of extension objects // Add thumbnail URLs entries.forEach(ext => { ext.thumbnail = BASE_URL + 'thumbnails/' + ext.thumbnail }) }) ``` -------------------------------- ### Listen for 'got video' Event Source: https://github.com/hydra-synth/hydra/blob/main/_autodocs/api-reference/patch-bay.md Fired when a video stream is received from a peer. Appends the video element to the document body. ```javascript pb.on('got video', (nickname, videoElement) => { console.log('Received video from:', nickname) document.body.appendChild(videoElement) }) ``` -------------------------------- ### Use p5.js Canvas as Hydra Source Source: https://github.com/hydra-synth/hydra/blob/main/README.md Initializes Hydra's source `s0` using the p5.js canvas element. ```javascript s0.init({src: p5.canvas}) ``` -------------------------------- ### Load Custom Language Translations Source: https://github.com/hydra-synth/hydra/blob/main/_autodocs/configuration.md Demonstrates how to use the 'l10n-url' URL parameter to load translation files from a custom location instead of the default GitHub repository. ```url https://hydra.ojack.xyz/?l10n-lang=es&l10n-url=https://example.com/translations.json ``` -------------------------------- ### Initialize Hydra Component Source: https://github.com/hydra-synth/hydra/blob/main/_autodocs/api-reference/hydra-component.md Initializes the Hydra component with specified options. Ensure the canvas element and precision are correctly set. ```javascript const hydraOptions = { detectAudio: true, canvas: canvasElement, precision: 'mediump' | 'highp' } // Optional networking if (serverURL) { hydraOptions.pb = patchBayInstance } this.hydra = new Hydra(hydraOptions) ``` -------------------------------- ### Establish WebSocket Connection Source: https://github.com/hydra-synth/hydra/blob/main/_autodocs/errors.md This code establishes a WebSocket connection using socket.io. Error handling for connection failures is implicitly managed by the socket.io client library. ```javascript this.signaller = io(options.server) // Implicit error handling by socket.io this.signaller.on('ready', () => { // Connected }) ``` -------------------------------- ### setSketchFromURL(path, callback) Source: https://github.com/hydra-synth/hydra/blob/main/_autodocs/api-reference/gallery.md Loads a sketch from URL query parameters or by fetching from the server using a sketch ID. It supports decoding base64 code and loading by ID, with an optional callback for handling the loaded data. ```APIDOC ## setSketchFromURL(path, callback) ### Description Loads a sketch from URL query parameters or loads from server by ID. ### Method N/A (JavaScript method) ### Parameters - **path** (string, optional): URL search string (default: `window.location.search`) - **callback** (function, optional): Called with loaded code and status ### Callback Signature ```javascript (code, foundSketch) => { // code: string - Loaded sketch code // foundSketch: boolean - True if found in database } ``` ### URL Parameters Supported - `code` - Base64-encoded sketch code - `sketch_id` - Server-side sketch identifier - `showCode` or `show-code` - Boolean to show/hide editor ### Behavior - Calls `hush()` and `render(o0)` to reset visuals - Attempts to load by sketch_id first if provided - Falls back to decoding base64 code parameter - Sets random sketch if no parameters found - Hides UI if `showCode=false` ### Example ```javascript // Load sketch from URL gallery.setSketchFromURL('?code=b3NjKCkub3V0KCk=', (code) => { console.log('Code loaded') }) // Load by server sketch ID gallery.setSketchFromURL('?sketch_id=abc123', (code, found) => { if (found) console.log('Found on server') }) ``` ``` -------------------------------- ### Initialize Remote Stream Source Source: https://github.com/hydra-synth/hydra/blob/main/README.md Initializes a remote Hydra stream as a source (`s0`). Ensure the source window is named and accessible. ```javascript s0.initStream("myGraphics") ``` -------------------------------- ### Add Code to Top of Editor Source: https://github.com/hydra-synth/hydra/blob/main/_autodocs/api-reference/editor.md Prepend a given string of code to the beginning of the current editor content using addCodeToTop. ```javascript editor.addCodeToTop('s0.initCam()') // s0.initCam() is now at the top of the editor ``` -------------------------------- ### Editor Integration with Mutator Source: https://github.com/hydra-synth/hydra/blob/main/_autodocs/api-reference/mutator.md Shows how the Editor creates and manages a Mutator instance, and how keybindings trigger mutation operations. ```javascript // In Editor constructor this.mutator = new Mutator(this) // In keymaps if (e == 'editor: randomize') { this.mutator.mutate({ reroll: !evt.shiftKey, changeTransform: evt.metaKey }) } ``` -------------------------------- ### PatchBay Initialization Options Type Source: https://github.com/hydra-synth/hydra/blob/main/_autodocs/types.md Defines the options for initializing the PatchBay library, including server URL, room name, and optional flags for global exposure and window title updates. ```typescript interface PatchBayInitOptions { server: string // Signaling server URL room: string // Room name to join makeGlobal?: boolean // Expose as window.pb (default: true) setTitle?: boolean // Update window title with nickname (default: true) } ``` -------------------------------- ### list() Source: https://github.com/hydra-synth/hydra/blob/main/_autodocs/api-reference/patch-bay.md Returns a list of connected peers along with their assigned nicknames. ```APIDOC ## list() ### Description Returns list of connected peers with their nicknames. ### Method `list` ### Returns object - Map of peer IDs to nicknames ### Example ```javascript const peers = pb.list() ``` ``` -------------------------------- ### clear all Source: https://github.com/hydra-synth/hydra/blob/main/_autodocs/api-reference/store.md Clears the editor, resets global state including audio and speed, clears gallery state, and resets the canvas and URL. ```APIDOC ## clear all ### Description Clears the editor, resets global state, and clears the URL. ### Method EMIT ### Behavior - Executes `hush()` (stops all audio) - Resets `speed` to 1 - Clears the editor content - Clears gallery state - Resets the canvas and URL ### Request Example ```javascript emitter.emit('clear all') ``` ``` -------------------------------- ### Event Handling with Emitter Source: https://github.com/hydra-synth/hydra/blob/main/_autodocs/INDEX.md Defines how to listen for and emit events using Choo's event emitter for pub/sub communication. ```javascript emitter.on('event-name', handler) emitter.emit('event-name', data) ``` -------------------------------- ### Instantiate PBLive Source: https://github.com/hydra-synth/hydra/blob/main/_autodocs/api-reference/patch-bay.md Create a new instance of the PBLive class. This constructor initializes session data and prepares nickname lookup tables. ```javascript const pb = new PBLive() ``` -------------------------------- ### HydraCanvas.load(element) Source: https://github.com/hydra-synth/hydra/blob/main/_autodocs/api-reference/hydra-component.md Initializes the Hydra synth engine and optionally PatchBay when the component is mounted. It also exposes global variables for the synth and P5. ```APIDOC ## Method load(element) ### Description Initializes the Hydra synth engine on component mount. This method sets up the WebGL canvas, detects the environment (e.g., iOS for precision settings), and optionally initializes PatchBay for networking. ### Parameters - `element` (HTMLElement): The parent DOM element that will contain the canvas. ### Returns - `undefined` ### Behavior - Detects iOS and sets appropriate WebGL precision ('highp' or 'mediump'). - Creates and initializes the Hydra synth instance with the provided canvas. - Optionally initializes PatchBay for networking if available. - Exposes global variables: `window.hydraSynth`, `window.P5`. - Emits a 'hydra loaded' event upon successful initialization. ### Example ```javascript // This method is typically called automatically by the Choo framework on component mount. // User code can then interact with the synth via global variables: // window.hydraSynth.osc(20).out(); // If manually calling: // const canvasElement = document.getElementById('hydra-canvas'); // component.load(canvasElement); ``` ``` -------------------------------- ### Select Extension Category Source: https://github.com/hydra-synth/hydra/blob/main/_autodocs/api-reference/extension-store.md Emits an event to load a specific category and switch to it. Accepts an optional index to specify the category. ```javascript emitter.emit('extensions: select category', index) ``` ```javascript // Switch to extensions category emitter.emit('extensions: select category', 0) // Switch to examples category emitter.emit('extensions: select category', 2) ``` -------------------------------- ### Store Module API Source: https://github.com/hydra-synth/hydra/blob/main/_autodocs/FILE_MANIFEST.txt Documentation for the central state management module, including state properties, events, error handling, and integration points. ```APIDOC ## Store Module API Reference ### Description Provides access to the central state management of the Hydra Web Editor. This module handles all state properties, global error events, and environment configurations. ### Module `store.md` ### Key Features - Central state management - State properties table - 12+ key events with examples - Global error handler - Environment variables - Integration points ```