| 1 | # HTMX WebSocket Extension - Interactive Demo |
| 2 | |
| 3 | A beautiful, comprehensive demonstration of the `hx-ws` extension showcasing real-time bidirectional communication with WebSockets. |
| 4 | |
| 5 | ## 🚀 Quick Start |
| 6 | |
| 7 | 1. **Install dependencies** (if you haven't already): |
| 8 | ```bash |
| 9 | npm install ws |
| 10 | ``` |
| 11 | |
| 12 | 2. **Start the WebSocket server**: |
| 13 | ```bash |
| 14 | node test/manual/ws-server.js |
| 15 | ``` |
| 16 | |
| 17 | 3. **Open your browser**: |
| 18 | Navigate to `http://localhost:8080` |
| 19 | |
| 20 | ## 🎯 What's Included |
| 21 | |
| 22 | ### 1. **Live Chat** |
| 23 | - Send and receive messages in real-time |
| 24 | - See your messages and bot responses instantly |
| 25 | - Demonstrates `hx-ws:send` with form submission |
| 26 | |
| 27 | ### 2. **Live Notifications** |
| 28 | - Receive random notifications every 5-8 seconds |
| 29 | - Shows real-time server push |
| 30 | - Uses `beforeend` swap to prepend new notifications |
| 31 | |
| 32 | ### 3. **Shared Counter** |
| 33 | - Multiple clients share the same counter state |
| 34 | - Increment, decrement, or reset from any client |
| 35 | - All connected clients see updates instantly |
| 36 | - Demonstrates bi-directional communication |
| 37 | |
| 38 | ### 4. **Stock Ticker** |
| 39 | - Live updating stock prices |
| 40 | - Prices change every 2-3 seconds |
| 41 | - Shows percentage changes with color coding |
| 42 | - Demonstrates continuous server streaming |
| 43 | |
| 44 | ### 5. **System Dashboard** |
| 45 | - Real-time system metrics (CPU, Memory, Disk) |
| 46 | - Multiple partial updates in a single message |
| 47 | - Updates every second |
| 48 | - Shows using multiple `<hx-partial>` elements |
| 49 | |
| 50 | ### 6. **Event Log** |
| 51 | - See all WebSocket events in real-time |
| 52 | - Connection, disconnection, messages, errors |
| 53 | - Demonstrates event listeners for debugging |
| 54 | |
| 55 | ## 💡 Features Demonstrated |
| 56 | |
| 57 | - **Connection Management**: `hx-ws:connect` with different URLs |
| 58 | - **Message Sending**: `hx-ws:send` with forms and buttons |
| 59 | - **Partial Updates**: Using `<hx-partial>` elements for targeted swaps |
| 60 | - **Multiple Connections**: Each demo card maintains its own WebSocket |
| 61 | - **Event Handling**: Custom event listeners for debugging |
| 62 | - **Reconnection**: Automatic reconnection on disconnect (try stopping the server!) |
| 63 | - **Swap Strategies**: Different `hx-swap` values (innerHTML, beforeend, etc.) |
| 64 | |
| 65 | ## 🎨 Key Concepts |
| 66 | |
| 67 | ### HTML Partial Format |
| 68 | |
| 69 | Server messages use this format: |
| 70 | |
| 71 | ```json |
| 72 | { |
| 73 | "channel": "ui", |
| 74 | "format": "html", |
| 75 | "payload": "<hx-partial id=\"target-id\">Content</hx-partial>" |
| 76 | } |
| 77 | ``` |
| 78 | |
| 79 | ### Request/Response Pattern |
| 80 | |
| 81 | Client sends: |
| 82 | ```json |
| 83 | { |
| 84 | "type": "request", |
| 85 | "request_id": "uuid-here", |
| 86 | "values": { |
| 87 | "message": "Hello!" |
| 88 | } |
| 89 | } |
| 90 | ``` |
| 91 | |
| 92 | Server responds with matching `request_id` to target the originating element. |
| 93 | |
| 94 | ### Multiple Partials |
| 95 | |
| 96 | Send multiple updates in one message: |
| 97 | |
| 98 | ```html |
| 99 | <hx-partial id="cpu">CPU: 45%</hx-partial> |
| 100 | <hx-partial id="memory">Memory: 62%</hx-partial> |
| 101 | <hx-partial id="disk">Disk: 73%</hx-partial> |
| 102 | ``` |
| 103 | |
| 104 | ## 🔧 Configuration |
| 105 | |
| 106 | The extension respects these config options: |
| 107 | |
| 108 | ```javascript |
| 109 | htmx.config.ws = { |
| 110 | reconnect: true, // Auto-reconnect on disconnect |
| 111 | reconnectDelay: 500, // Initial delay (ms) |
| 112 | reconnectMaxDelay: 60000, // Max delay (ms) |
| 113 | reconnectMaxAttempts: Infinity,// Max reconnect attempts |
| 114 | reconnectJitter: 0.3, // Jitter factor (0-1) |
| 115 | pauseOnBackground: true // Pause connection when tab is backgrounded |
| 116 | }; |
| 117 | ``` |
| 118 | |
| 119 | ## 🎓 Learning Points |
| 120 | |
| 121 | 1. **Connection Pooling**: Multiple elements can share the same WebSocket connection |
| 122 | 2. **Bi-directional**: Both client and server can initiate messages |
| 123 | 3. **Event-Driven**: Rich event system for monitoring and debugging |
| 124 | 4. **Swap Strategies**: Flexible content replacement strategies |
| 125 | 5. **Graceful Degradation**: Automatic reconnection and error handling |
| 126 | |
| 127 | ## 📚 Code Examples |
| 128 | |
| 129 | ### Basic Connection |
| 130 | ```html |
| 131 | <div hx-ws:connect="ws://localhost:8080/chat" hx-trigger="load"> |
| 132 | <div id="messages"></div> |
| 133 | </div> |
| 134 | ``` |
| 135 | |
| 136 | ### Sending Messages |
| 137 | ```html |
| 138 | <form hx-ws:send hx-trigger="submit"> |
| 139 | <input name="message" type="text"> |
| 140 | <button type="submit">Send</button> |
| 141 | </form> |
| 142 | ``` |
| 143 | |
| 144 | ### Button Actions |
| 145 | ```html |
| 146 | <button hx-ws:send='{"action":"increment"}' hx-trigger="click"> |
| 147 | Increment |
| 148 | </button> |
| 149 | ``` |
| 150 | |
| 151 | ### Multiple Targets |
| 152 | ```html |
| 153 | <div hx-ws:connect="ws://localhost:8080/dashboard" hx-trigger="load"> |
| 154 | <div id="cpu"></div> |
| 155 | <div id="memory"></div> |
| 156 | <div id="disk"></div> |
| 157 | </div> |
| 158 | ``` |
| 159 | |
| 160 | ## 🐛 Debugging |
| 161 | |
| 162 | The demo includes a live event log that shows: |
| 163 | - Connection events (`htmx:before:ws:connection`, `htmx:after:ws:connection`) |
| 164 | - Message events (`htmx:before:ws:send`, `htmx:after:ws:message`) |
| 165 | - Error events (`htmx:ws:error`, `htmx:ws:close`) |
| 166 | |
| 167 | ## 🤝 Contributing |
| 168 | |
| 169 | Try modifying the demos to learn: |
| 170 | - Change swap strategies (`hx-swap="beforeend"`) |
| 171 | - Add new message types |
| 172 | - Implement custom channels |
| 173 | - Add authentication |
| 174 | - Create new demo cards |
| 175 | |
| 176 | ## 📖 Documentation |
| 177 | |
| 178 | For full documentation, visit: |
| 179 | - [HTMX WebSocket Extension Docs](https://htmx.org/extensions/websockets/) |
| 180 | - [WebSocket API](https://developer.mozilla.org/en-US/docs/Web/API/WebSocket) |
| 181 | |
| 182 | ## 🎉 Have Fun! |
| 183 | |
| 184 | Open multiple browser windows to see real-time synchronization in action. The shared counter and chat work across all connected clients! |
| 185 |