dolphin-client 1.0.2 → 1.0.3

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/README.md CHANGED
@@ -23,7 +23,7 @@ By breathing life back into standard HTML, we have resurrected the simplicity of
23
23
  ## Documentation
24
24
 
25
25
  > [!TIP]
26
- > 📖 Read our comprehensive **[Full Developer Tutorial & Integration Guide](./fulltutorial.md)** for detailed guides, Next.js setups, WebRTC intercoms, global stores, drag-and-drop sortable lists, and real-world examples!
26
+ > 📖 Read our comprehensive **[Full Developer Tutorial & Integration Guide](https://github.com/Phuyalshankar/dolphin-client/blob/main/fulltutorial.md)** for detailed guides, Next.js setups, WebRTC intercoms, global stores, drag-and-drop sortable lists, and real-world examples!
27
27
 
28
28
  ---
29
29
 
@@ -70,7 +70,7 @@ Tired of the command line and `node_modules` clutter? We've got you covered!
70
70
  > [!TIP]
71
71
  > **If the ZIP file download is unavailable:**
72
72
  > You can clone this repository directly or copy the `dist/dolphin-client.js` (or `dist/dolphin-client.min.js`) file from your clone.
73
- > For the premium styling layer, create a `dolphin-css.css` file and add the custom effects (like `.fx-glass` and `.fx-neon`) described in the **[Full Developer Tutorial](./fulltutorial.md)**.
73
+ > For the premium styling layer, create a `dolphin-css.css` file and add the custom effects (like `.fx-glass` and `.fx-neon`) described in the **[Full Developer Tutorial](https://github.com/Phuyalshankar/dolphin-client/blob/main/fulltutorial.md)**.
74
74
 
75
75
  Extract the zip directly inside your project folder to get a clean local directory structure with pre-bundled assets:
76
76
  ```
@@ -0,0 +1,734 @@
1
+ # Dolphin Client 🐬 - Full Developer Tutorial & Integration Guide
2
+
3
+ Welcome to the comprehensive guide for **Dolphin Client**, the ultimate hookless, framework-agnostic real-time reactive DOM-binding library.
4
+
5
+ This tutorial will teach you how to build modern, lightweight, real-time web applications (including WebSockets, REST APIs, and WebRTC Intercom Calling) using **pure HTML, CSS, and Dolphin Client—with ZERO lines of React/Vue/Angular state management code!**
6
+
7
+ ---
8
+
9
+ ## १. Introduction & Hookless Architecture (परिचय र वास्तुकला)
10
+
11
+ In traditional frontend development (React, Next.js, Vue), syncing real-time data with the UI requires heavy state management hooks (`useState`, `useEffect`, `useSyncExternalStore`), virtual DOM diffing, and complex component lifecycles.
12
+
13
+ **Dolphin Client** completely eliminates this framework fatigue through **Direct DOM Reactivity**:
14
+ - **HTML-First Declarative Bindings**: Bind real-time data topics to HTML elements using standard `data-rt-*` and `data-api-*` attributes.
15
+ - **Micro-Templates**: Write dynamic HTML lists directly inside `data-rt-template` attributes.
16
+ - **DOM-Context Drilling (`getClosestContext`)**: Instead of passing props down manually (prop drilling), child elements dynamically crawl *up* the DOM tree to extract parent data.
17
+ - **Framework Agnostic**: Works perfectly in Next.js Server Components, static HTML files, WordPress, jQuery, or any legacy web portal.
18
+
19
+ ---
20
+
21
+ ## २. Installation (इन्स्टलेसन)
22
+
23
+ Install the standalone package via NPM:
24
+
25
+ ```bash
26
+ npm install dolphin-client
27
+ ```
28
+
29
+ ### Script Tag Integration (Browser-Native IIFE)
30
+ For static websites or plain HTML files, copy `node_modules/dolphin-client/dist/dolphin-client.js` and load it via a script tag:
31
+
32
+ ```html
33
+ <script src="dist/dolphin-client.js"></script>
34
+ <script>
35
+ // Access through the global DolphinModule namespace
36
+ const dolphin = new DolphinModule.DolphinClient('http://localhost:3000', 'ROOM_101');
37
+ dolphin.connect();
38
+ </script>
39
+ ```
40
+
41
+ ---
42
+
43
+ ## ३. Core HTML Directives Guide (HTML डाइरेक्टिभ्स निर्देशिका)
44
+
45
+ Dolphin Client automatically scans your HTML document and binds interactive listeners and real-time streams based on custom attributes.
46
+
47
+ ### ३.१. Values & Event Pushes (`data-rt-push`)
48
+ Pushes the inputs of form elements to a WebSocket topic. It automatically registers unified listeners on `['input', 'change', 'keyup', 'paste', 'blur']` to ensure robust value sync across all interactions (typing, select dropdown changes, copying/pasting).
49
+
50
+ ```html
51
+ <!-- Automatically publishes input values in real-time to the chat topic -->
52
+ <input name="chat" data-rt-push="chat/messages/ROOM_101" placeholder="Type a message..." />
53
+ ```
54
+
55
+ ### ३.२. Unified Interaction Bindings (`data-rt-[event]` and `data-api-[event]`)
56
+ Allows triggering realtime publishes or HTTP API requests on **any** standard browser event (`click`, `change`, `keydown`, `keyup`, `dblclick`, `focus`, `blur`, `mouseenter`, `mouseleave`).
57
+
58
+ ```html
59
+ <!-- Publishes payload on double click -->
60
+ <div data-rt-dblclick="sensor/trigger" data-rt-payload='{"status": "alert"}'>Double Click Me</div>
61
+
62
+ <!-- Triggers an API request on select dropdown change -->
63
+ <select data-api-change="POST /api/settings" data-api-payload='{"theme": "dark"}' data-api-result="settings/status">
64
+ <option value="dark">Dark Theme</option>
65
+ <option value="light">Light Theme</option>
66
+ </select>
67
+ ```
68
+
69
+ ### ३.३. Svelte-Style Block Conditionals & Loops (कन्डिसनल र लुप ब्लकहरू)
70
+ When data arrives via HTTP API or WebSockets, Dolphin compiles your templates on-the-fly. In addition to standard double mustache (`{{key}}`) replacements, Dolphin Client v2.0 features a fully integrated **Svelte-Style Template Compiler** natively running in the browser:
71
+
72
+ - **`{#if expression}` / `{:else if expression}` / `{:else}` / `{/if}`**: Compile Svelte-style conditional flows. You can nest `{#if}` statements to arbitrary levels!
73
+ - **`{#each expression as item}`** or **`{#each expression as item, index}`**: Loop over arrays dynamically. The optional `index` variable starts at `0` and increments automatically.
74
+ - **Single Curly `{expression}` and Double Curly `{{expression}}`**: Output values safely. Dolphin resolves variable paths, nested object properties (like `user.name`), optional chaining (`?.`), and logical operators.
75
+ - **Dynamic Attribute Interpolation**: Interpolates expressions inside standard HTML attributes dynamically (e.g., `src="{user.avatar}"` or `data-api-click="POST /api/reply/{notification.id}"`).
76
+
77
+ ---
78
+
79
+ ### ३.३.१. Real-World Example 1: Multi-Level Nested Conditionals (User Profile Card)
80
+ This example showcases a full dynamic user profile card. It handles states like:
81
+ 1. **User not logged in**: Displays login input fields.
82
+ 2. **User logged in but unverified**: Displays a warning card with a verification link.
83
+ 3. **User verified but not premium**: Displays their details with an upgrade call-to-action button.
84
+ 4. **User verified and premium**: Highlights their status with a premium badge.
85
+
86
+ ```html
87
+ <div data-api-get="/api/user/profile"
88
+ data-rt-template='
89
+ <div class="profile-container">
90
+ {#if user}
91
+ {#if user.verified}
92
+ <div class="profile-card fx-aurora">
93
+ <img src="{user.avatar}" class="avatar" alt="{user.name}" />
94
+ <h2>{user.name}</h2>
95
+ <p>{user.email}</p>
96
+
97
+ {#if user.premium}
98
+ <div class="premium-badge fx-neon">⭐ Premium Member</div>
99
+ <button class="filled">Access Premium Content</button>
100
+ {:else}
101
+ <div class="upgrade-badge fx-glass">Upgrade to Premium</div>
102
+ <button class="outline">View Plans →</button>
103
+ {/if}
104
+ </div>
105
+ {:else}
106
+ <div class="verify-card fx-glass">
107
+ <h3>Verify Your Account</h3>
108
+ <p>Check your email for verification link</p>
109
+ <button data-api-click="POST /api/resend-verification">
110
+ Resend Email
111
+ </button>
112
+ </div>
113
+ {/if}
114
+ {:else}
115
+ <div class="login-card fx-glass">
116
+ <h3>Login to Continue</h3>
117
+ <input placeholder="Email" />
118
+ <input type="password" placeholder="Password" />
119
+ <button class="filled primary">Login</button>
120
+ <a href="/register">Create Account</a>
121
+ </div>
122
+ {/if}
123
+ </div>
124
+ '></div>
125
+ ```
126
+
127
+ ---
128
+
129
+ ### ३.३.२. Real-World Example 2: List Loops with Loop Indices (Notifications Feed)
130
+ This example displays a dynamic list of real-time notifications. It automatically loops over the list, renders specific markup based on notification types (`message`, `alert`, `update`, etc.), prints the sequential loop index (`#0`, `#1`), and binds dynamic HTTP API action triggers to button clicks:
131
+
132
+ ```html
133
+ <div data-rt-bind="notifications"
134
+ data-rt-template='
135
+ <div class="notifications-container">
136
+ {#if notifications.length > 0}
137
+ <div class="notifications-list">
138
+ <h3>You have {notifications.length} notifications</h3>
139
+
140
+ {#each notifications as notification, index}
141
+ <div class="notification-item fx-glass">
142
+ {#if notification.type === "message"}
143
+ <div class="message-notification">
144
+ <span class="icon">💬</span>
145
+ <div class="content">
146
+ <strong>#{index} from {notification.from}</strong>
147
+ <p>{notification.message}</p>
148
+
149
+ {#if notification.replyNeeded}
150
+ <button data-api-click="POST /api/reply/{notification.id}">
151
+ Reply
152
+ </button>
153
+ {:else}
154
+ <span class="read-status">✓ Read</span>
155
+ {/if}
156
+ </div>
157
+ </div>
158
+
159
+ {:else if notification.type === "alert"}
160
+ <div class="alert-notification fx-neon">
161
+ <span class="icon">⚠️</span>
162
+ <div class="content">
163
+ <strong>#{index} Alert!</strong>
164
+ <p>{notification.message}</p>
165
+
166
+ {#if notification.action}
167
+ <button data-api-click="POST /api/alert/{notification.id}/action">
168
+ {notification.action}
169
+ </button>
170
+ {/if}
171
+ </div>
172
+ </div>
173
+
174
+ {:else if notification.type === "update"}
175
+ <div class="update-notification">
176
+ <span class="icon">🔄</span>
177
+ <div class="content">
178
+ <strong>Update Available (v{notification.version})</strong>
179
+ <p>{notification.message}</p>
180
+
181
+ {#if notification.urgency === "major"}
182
+ <button class="urgent" data-api-click="POST /api/update">
183
+ Update Now
184
+ </button>
185
+ {:else}
186
+ <button data-api-click="POST /api/update/dismiss">
187
+ Dismiss
188
+ </button>
189
+ {/if}
190
+ </div>
191
+ </div>
192
+
193
+ {:else}
194
+ <div class="default-notification">
195
+ <span class="icon">📢</span>
196
+ <div class="content">
197
+ <p>{notification.message}</p>
198
+ </div>
199
+ </div>
200
+ {/if}
201
+ </div>
202
+ {/each}
203
+ </div>
204
+
205
+ {:else}
206
+ <div class="no-notifications fx-glass">
207
+ <div class="empty-icon">🔔</div>
208
+ <h3>No new notifications</h3>
209
+ <p>You are all caught up!</p>
210
+ </div>
211
+ {/if}
212
+ </div>
213
+ '></div>
214
+ ```
215
+
216
+ ---
217
+
218
+ ### ३.३.३. HTML Directives & Sub-bindings (डाइरेक्टिभ्स र सब-बाइन्डिङ)
219
+
220
+ ### ३.४. Browser-Native Template Tags (No Backticks!)
221
+ To completely avoid multi-line strings, backticks (\`...\`), and quote-escaping issues in your HTML attributes, you can point `data-rt-template` directly to a standard browser-native **`<template>` tag selector**:
222
+
223
+ 1. **On your binding container**: Point `data-rt-template` to the CSS ID selector of your template element (e.g. `#device-card`).
224
+ 2. **In your HTML body**: Declare a standard `<template>` tag. It will not render on page load, but Dolphin Client will automatically query it and instantiate it dynamically!
225
+
226
+ ```html
227
+ <!-- 1. Binding Container points to the template selector (Zero Backticks!) -->
228
+ <div data-api-get="/api/devices" data-rt-bind="devices/online" data-rt-template="#device-card"></div>
229
+
230
+ <!-- 2. Browser-Native Template Tag with perfect syntax-highlighting -->
231
+ <template id="device-card">
232
+ <div data-rt-type="context" class="card">
233
+ <span class="status-dot" data-rt-class="bg-emerald-400:isOnline,bg-red-400:isOffline"></span>
234
+ <h3 data-rt-text="id"></h3>
235
+ <img data-rt-attr="src:avatarUrl,alt:id" class="avatar" />
236
+ <button onclick="dialPeer(&apos;{{id}}&apos;)">Call</button>
237
+ </div>
238
+ </template>
239
+ ```
240
+
241
+ Benefits:
242
+ - **Clean Code**: No complex escaping or template literal backticks in HTML attributes.
243
+ - **IDE Support**: Full HTML syntax highlighting and autocomplete inside standard `<template>` tags in modern text editors (VS Code, Cursor).
244
+
245
+ ---
246
+
247
+ ## ४. Parent-Child Context Propagation (`getClosestContext`)
248
+
249
+ When rendering lists dynamically inside templates, child components (like a click button) often need access to their parent's specific item context (like the item `id` or `price`).
250
+
251
+ In Dolphin, you declare **`data-rt-type="context"`** on the parent container. The rendering engine stores the data object directly on the DOM element (`element._rtContext = payload`).
252
+
253
+ When an event triggers on a child element, Dolphin's **`getClosestContext(childElement)`** traverses up the DOM tree (`current = current.parentElement`) to fetch the nearest parent context and dynamically replaces mustaches (`{{variable}}`):
254
+
255
+ ```html
256
+ <div data-rt-bind="store/books" data-rt-template='
257
+ <!-- Parent Context Node -->
258
+ <div data-rt-type="context" class="book-row">
259
+ <h3>{{title}}</h3>
260
+ <!-- Child trigger climbs up to parent context to resolve {{price}} -->
261
+ <button data-api-click="POST /api/cart/add" data-api-payload='{"item": "{{title}}", "price": {{price}}}'>
262
+ Buy for ${{price}}
263
+ </button>
264
+ </div>
265
+ '></div>
266
+ ```
267
+
268
+ ---
269
+
270
+ ## ५. REST + Realtime Hybrid Loading (Offline-First)
271
+
272
+ A major breakthrough in Dolphin Client is **Hybrid REST + Realtime Binding**. It solves the problem where a web page appears empty or broken before the WebSocket (`rt`) connects.
273
+
274
+ If an element has **both** `data-api-get` and `data-rt-bind`:
275
+ 1. **Initial HTTP Fetch (REST Mode)**: On page load, `data-api-get` fetches initial data from the HTTP API. Dolphin immediately routes the HTTP JSON response through the template renderer (`_updateDOM`), rendering fully compiled HTML instantly.
276
+ 2. **WebSocket Takeover (Realtime Mode)**: As soon as the WebSocket connects, any real-time update published to the topic will seamlessly overwrite and update the HTML in real-time.
277
+
278
+ ```html
279
+ <!-- Loads instantly from REST API, updates instantly via WebSockets! -->
280
+ <div data-api-get="/api/devices" data-rt-bind="devices/online" data-rt-template="..."></div>
281
+ ```
282
+
283
+ ---
284
+
285
+ ## ६. Next.js Integration Guide for 100% Pure SEO
286
+
287
+ Next.js Server Components are rendered on the server into pure HTML, which is crucial for full SEO. However, React usually requires `"use client"` for dynamic reactivity.
288
+
289
+ Using **Dolphin Client**, you can build a highly dynamic Next.js application with **ZERO `"use client"` directives**, achieving **100% full SEO score!**
290
+
291
+ ### Step 1: Create a Next.js Server Component (NO `"use client"`)
292
+ Create `app/intercom/page.js`. Fetch the initial data on the server and render the markup with `data-rt-template`:
293
+
294
+ ```jsx
295
+ // app/intercom/page.js
296
+ import Script from 'next/script';
297
+
298
+ async function fetchInitialDevices() {
299
+ const res = await fetch('http://localhost:3000/api/devices', { cache: 'no-store' });
300
+ const data = await res.json();
301
+ return data.devices || [];
302
+ }
303
+
304
+ export default async function IntercomPage() {
305
+ const initialDevices = await fetchInitialDevices();
306
+
307
+ return (
308
+ <div className="container">
309
+ <h1>Dolphin Intercom Console</h1>
310
+
311
+ {/* 1. Renders statically on the server so search engines see it instantly for SEO! */}
312
+ <div id="online-directory" data-rt-bind="devices/online" data-rt-template='
313
+ <div data-rt-type="context" class="card">
314
+ <span class="status-dot"></span>
315
+ <span class="id-label">{{id}}</span>
316
+ <button onclick="window.dialPeer(&apos;{{id}}&apos;)" class="btn">Call</button>
317
+ </div>
318
+ '>
319
+ {/* Server-Side Pre-rendering for search crawlers */}
320
+ {initialDevices.map(device => (
321
+ <div key={device.id} data-rt-type="context" className="card">
322
+ <span className="status-dot"></span>
323
+ <span className="id-label">{device.id}</span>
324
+ <button className="btn">Call</button>
325
+ </div>
326
+ ))}
327
+ </div>
328
+
329
+ {/* 2. Load Dolphin Client statically in the browser */}
330
+ <Script src="/node_modules/dolphin-client/dist/dolphin-client.js" strategy="afterInteractive" />
331
+ <Script src="/init-intercom.js" strategy="afterInteractive" />
332
+ </div>
333
+ );
334
+ }
335
+ ```
336
+
337
+ ### Step 2: Initialize Intercom client-side (`public/init-intercom.js`)
338
+ Create the initialization script in your public folder to configure WebSockets and WebRTC when the browser loads:
339
+
340
+ ```javascript
341
+ // public/init-intercom.js
342
+ document.addEventListener('DOMContentLoaded', () => {
343
+ if (typeof DolphinModule === 'undefined') return;
344
+
345
+ const serverIP = window.location.hostname;
346
+ const deviceId = 'ROOM_101'; // Compute dynamically if needed
347
+
348
+ // Initialize client (auto-scans DOM and registers bindings!)
349
+ const dolphin = new DolphinModule.DolphinClient(`http://${serverIP}:3000`, deviceId);
350
+ window.dolphin = dolphin;
351
+
352
+ dolphin.connect().then(() => {
353
+ console.log("WebSocket connected. Handshaking signaling...");
354
+
355
+ // Subscribe to online device status presence
356
+ dolphin.subscribe('devices/status', (payload) => {
357
+ if (payload && payload.devices) {
358
+ dolphin._updateDOM('devices/online', payload.devices);
359
+ }
360
+ });
361
+ });
362
+ });
363
+ ```
364
+
365
+ ---
366
+
367
+ ## ७. WebRTC Intercom Signaling APIs (वेबआरटिसी कलिङ एपीआई)
368
+
369
+ Dolphin Client has built-in signaling mechanisms for high-performance WebRTC peer connection pipelines.
370
+
371
+ ### ७.१. Setting Up Peer Connection & Handshake
372
+ Here is the clean JS setup to dial and establish an audio/video call using standard signaling:
373
+
374
+ ```javascript
375
+ let localStream = null;
376
+ let peerConnection = null;
377
+
378
+ async function dialPeer(peerId) {
379
+ // 1. Capture local audio/video with robust fallback (handles missing webcams/mics)
380
+ try {
381
+ localStream = await navigator.mediaDevices.getUserMedia({ audio: true, video: true });
382
+ } catch {
383
+ try {
384
+ localStream = await navigator.mediaDevices.getUserMedia({ audio: true, video: false }); // Audio only
385
+ } catch {
386
+ console.warn("No hardware capture devices available");
387
+ }
388
+ }
389
+
390
+ // 2. Initialize Peer Connection
391
+ peerConnection = new RTCPeerConnection({
392
+ iceServers: [{ urls: 'stun:stun.l.google.com:19302' }]
393
+ });
394
+
395
+ // 3. Add local tracks
396
+ if (localStream) {
397
+ localStream.getTracks().forEach(track => peerConnection.addTrack(track, localStream));
398
+ } else {
399
+ // Add receive-only transceivers if local hardware is missing
400
+ peerConnection.addTransceiver('audio', { direction: 'recvonly' });
401
+ peerConnection.addTransceiver('video', { direction: 'recvonly' });
402
+ }
403
+
404
+ // 4. Handle ICE Candidates
405
+ peerConnection.onicecandidate = (event) => {
406
+ if (event.candidate) {
407
+ sendSignal(peerId, 'ICE_CANDIDATE', { candidate: event.candidate });
408
+ }
409
+ };
410
+
411
+ // 5. Play Remote Audio/Video Track with Autoplay bypass
412
+ peerConnection.ontrack = (event) => {
413
+ const remoteVideo = document.getElementById('remote-video');
414
+ if (remoteVideo) {
415
+ remoteVideo.srcObject = event.streams[0];
416
+ remoteVideo.play().catch(e => console.error("Autoplay blocked:", e));
417
+ }
418
+ };
419
+
420
+ // 6. Create SDP Offer & Publish Signaling
421
+ const offer = await peerConnection.createOffer();
422
+ await peerConnection.setLocalDescription(offer);
423
+ sendSignal(peerId, 'INVITE', { sdp: offer.sdp });
424
+ }
425
+
426
+ }
427
+
428
+ function sendSignal(to, type, data) {
429
+ window.dolphin.publish(`phone/signaling/${to}`, {
430
+ from: window.dolphin.deviceId,
431
+ to,
432
+ type,
433
+ data,
434
+ timestamp: Date.now()
435
+ });
436
+ }
437
+ ```
438
+
439
+ ---
440
+
441
+ ## ८. Virtual DOM Reconciliation & RAF Batched Updates (भर्चुअल DOM र ब्याच अपडेट्स)
442
+
443
+ To ensure maximum performance and maintain UI state (like input focus, text selection, and active input cursors) during high-frequency real-time updates, Dolphin Client v2.0 features an automatic, zero-dependency **Virtual DOM Diffing engine** (`diffDOM` & `patchDOM`):
444
+
445
+ - **Automatic Selective Patching**: When new data arrives, Dolphin compiles the template in memory, diffs it against the live DOM, and selectively updates only the modified text, attributes, or nodes instead of wiping the entire container.
446
+ - **60fps Batched Updates (`scheduleDOMUpdate`)**: High-frequency writes are automatically debounced and batched into browser `requestAnimationFrame` render cycles, completely preventing layout thrashing and stutter.
447
+
448
+ ---
449
+
450
+ ## ९. Offline-First Cache & Persistent Mutation Queue (अफ्लाइन-फर्स्ट र सूचिकृत म्यूटेशन)
451
+
452
+ Dolphin Client comes with a native offline-first persistence engine driven by **IndexedDB API**:
453
+
454
+ - **GET Requests Caching**: Successful HTTP GET requests (`data-api-get`) are cached automatically in IndexedDB. If the network goes down, Dolphin serves the last cached value instantly.
455
+ - **Offline Writes Queue**: Form submissions, API clicks, and writes (`POST`, `PUT`, `DELETE`) executed while offline are queued securely in IndexedDB and resolved with a positive mock response.
456
+ - **Automatic Sync Engine**: Once the client reconnects, the sync engine automatically flushes the queue sequentially, triggering conflict callbacks if necessary.
457
+
458
+ ---
459
+
460
+ ## १०. Global Reactive Stores & Declarative Form Validation (ग्लोबल स्टोर र स्वचालित फारम प्रमाणीकरण)
461
+
462
+ Dolphin Client v2.0 provides an elegant, hookless state management and form validation system:
463
+
464
+ ### १०.१. State Directives (`data-store`)
465
+ Manage client-side global reactive stores without writing custom scripts:
466
+
467
+ ```html
468
+ <!-- Initialize/bind an input to automatically write to store "user" at key "name" -->
469
+ <input data-store-write="user.name" placeholder="Enter your name" />
470
+
471
+ <!-- Bind an element to display the name from the store in real-time -->
472
+ <span data-store-read="user.name"></span>
473
+ ```
474
+
475
+ ### १०.१.२. Declarative Store Actions (`data-store-[event]`) - बिना जाभास्क्रिप्ट गणित र सर्तहरू (No-JS Calculations & Conditions)
476
+ Dolphin Client v2.0 ले सिधै HTML बाटै डेटा स्टोर अपडेट गर्ने र जस्तोसुकै जटिल गणितीय हिसाब, लजिकल अपरेटर, र सर्तहरू (conditional statements) चलाउने फिचर प्रदान गर्दछ। यसको लागि तपाईँले कुनै जाभास्क्रिप्ट फङ्सन वा `<script>` ट्याग लेख्नै पर्दैन।
477
+
478
+ तपाईँले `data-store-click`, `data-store-change` जस्ता एट्रिब्युटहरू प्रयोग गरेर सिधै HTML भित्रै जाभास्क्रिप्टका गणितीय सूत्रहरू लेख्न सक्नुहुन्छ:
479
+
480
+ #### क) गणितीय हिसाबहरू (Mathematical Calculations)
481
+ ```html
482
+ <!-- दुईवटा भ्यालु स्वतः गुणन गरेर 'app.total' मा राख्न -->
483
+ <button data-store-click="app.total = app.price * app.quantity">कुल हिसाब निकाल्नुहोस्</button>
484
+
485
+ <!-- १ देखि १०० सम्मको रेन्डम नम्बर स्वतः जेनेरेट गर्न -->
486
+ <button data-store-click="app.randomNum = Math.floor(Math.random() * 100) + 1">Random Number</button>
487
+ ```
488
+
489
+ #### ख) सर्त र निर्णयहरू (Conditions & Ternary Operators)
490
+ Ternary operator (`condition ? true : false`) वा बहु-लाइन `if/else` सर्तहरू सिधै HTML बाटै चल्छन्:
491
+ ```html
492
+ <!-- यदि स्कोर ५० वा सोभन्दा बढी भए 'Passed' नत्र 'Failed' सेट गर्न -->
493
+ <button data-store-click="app.result = (app.score >= 50) ? 'Passed' : 'Failed'">नतिजा हेर्नुहोस्</button>
494
+
495
+ <!-- यदि काउन्ट १० भन्दा सानो भए बढाउने, नत्र ० मा फर्काउने -->
496
+ <button data-store-click="if (app.count < 10) { app.count++ } else { app.count = 0 }">Incrementor</button>
497
+ ```
498
+
499
+ #### ग) अन-अफ टगल गर्ने (Boolean / Toggle Logic)
500
+ डार्क मोड अन-अफ गर्न वा कुनै स्टेटलाई स्वतः उल्टो (toggle) बनाउन:
501
+ ```html
502
+ <!-- darkMode को भ्यालु true भए false र false भए true बनाउन -->
503
+ <button data-store-click="app.darkMode = !app.darkMode">डार्क मोड अन/अफ</button>
504
+ ```
505
+
506
+ ### १०.२. Declarative Validations (`data-validate`)
507
+ Apply robust validation rules to inputs and forms instantly. Tagged invalid inputs automatically receive `.invalid` classes and publish error text:
508
+
509
+ - **`required`**: Checks for non-empty input.
510
+ - **`email`**: Validates standard email address formats.
511
+ - **`min:N`**: Enforces a minimum length of N characters.
512
+ - **`match:inputName`**: Compares value (e.g. for Password Confirmations).
513
+
514
+ ```html
515
+ <form id="signup-form">
516
+ <!-- Validates in real-time on keypress/blur and outputs error to topic errors/email -->
517
+ <input name="email" data-validate="required,email" placeholder="Your Email" />
518
+
519
+ <input name="password" type="password" data-validate="required,min:8" placeholder="Password" />
520
+ <input name="confirm" type="password" data-validate="match:password" placeholder="Confirm Password" />
521
+
522
+ <button type="submit">Sign Up</button>
523
+ </form>
524
+ ```
525
+
526
+ ---
527
+
528
+ ## ११. Animations, Accessibility (a11y), and Internationalization (i18n)
529
+
530
+ Dolphin Client incorporates built-in UI polish tools to make apps fluid, accessible, and global:
531
+
532
+ ### ११.१. Staggered Animations
533
+ Trigger animations on lists automatically using the Web Animations API:
534
+
535
+ ```javascript
536
+ // Add fluid staggers to list containers easily
537
+ dolphin.staggerListItems(document.getElementById('list-container'), '.item-class', 50);
538
+ ```
539
+
540
+ ### ११.२. Automated Accessibility (a11y)
541
+ Easily implement accessible widgets and focus traps:
542
+
543
+ - **Modal Trap (`data-rt-a11y-focus-trap`)**: Confines `Tab` keyboard focus inside the visible modal container.
544
+ - **Keyboard List Navigation (`data-rt-keynav`)**: Enables users to traverse lists using `ArrowUp` / `ArrowDown` and click using `Enter`.
545
+ - **`autoAriaModal(el, isOpen)`**: Dynamically sets `role="dialog"`, `aria-modal="true"`, and `aria-hidden` tags.
546
+
547
+ ```html
548
+ <!-- Modal box equipped with focus trap and keyboard accessibility -->
549
+ <div id="settings-modal" data-rt-a11y-focus-trap data-rt-keynav tabindex="-1">
550
+ <button class="close-btn">Close</button>
551
+ <ul class="options-list">
552
+ <li tabindex="0" class="active">Dark Mode</li>
553
+ <li tabindex="0">Light Mode</li>
554
+ </ul>
555
+ </div>
556
+ ```
557
+
558
+ ### ११.३. Dynamic Translation Engine (i18n)
559
+ Provide multi-language dictionary translations seamlessly. Dotted nested keys (e.g. `auth.login`) and JSON interpolation parameter injection are fully supported:
560
+
561
+ ```html
562
+ <!-- Embed dictionary data directly in HTML -->
563
+ <script type="application/json" data-i18n-dict="en">
564
+ {
565
+ "welcome": "Hello {{name}}! Welcome back.",
566
+ "auth": { "login": "Log In" }
567
+ }
568
+ </script>
569
+
570
+ <script type="application/json" data-i18n-dict="ne">
571
+ {
572
+ "welcome": "नमस्ते {{name}}! स्वागत छ।",
573
+ "auth": { "login": "लग-इन" }
574
+ }
575
+ </script>
576
+
577
+ <!-- Render translations automatically -->
578
+ <h1 data-i18n-key="welcome" data-i18n-params='{"name": "Ram"}'></h1>
579
+ <button data-i18n-key="auth.login"></button>
580
+
581
+ <!-- Switch languages dynamically on click -->
582
+ <button data-i18n-switch="ne">नेपाली</button>
583
+ <button data-i18n-switch="en">English</button>
584
+ ```
585
+
586
+ ---
587
+
588
+ ## १२. Drag-and-Drop, Sortable Lists, and Real-time Collaboration (CRDT)
589
+
590
+ Build multi-player collaborative interfaces declarative:
591
+
592
+ ### १२.१. Declarative Drag & Drop
593
+ Move items between sections and sync updates across devices instantly:
594
+
595
+ ```html
596
+ <!-- Draggable Card publishes payload to WS -->
597
+ <div data-drag='{"id": 105, "title": "Buy milk"}' draggable="true">Card Item</div>
598
+
599
+ <!-- Drop Zone accepts draggable data and publishes to "tasks/moved" topic -->
600
+ <div data-drop="tasks/moved">Drop Here</div>
601
+ ```
602
+
603
+ ### १२.२. Sortable Lists
604
+ Drag to reorder lists in real-time. Dolphin automatically calculates elements midpoints during `dragover`, reorganizes children, and publishes the new index orders:
605
+
606
+ ```html
607
+ <!-- Sortable container publishes new order map to "tasks/order" -->
608
+ <ul data-sortable="tasks/order">
609
+ <li data-drag='{"id": 1}' draggable="true">Task A</li>
610
+ <li data-drag='{"id": 2}' draggable="true">Task B</li>
611
+ <li data-drag='{"id": 3}' draggable="true">Task C</li>
612
+ </ul>
613
+ ```
614
+
615
+ ### १२.३. Collaborative Cursor Sharing & CRDT Document Sync
616
+ Broaden your app into a cooperative space:
617
+
618
+ - **Shared Mouse Cursors (`data-rt-cursor-share`)**: Automatically tracks mouse movements relative to a container, publishes cursor ratio coordinates, and draws colored cursor circles for remote users.
619
+ - **Typing Indicators (`data-rt-typing`)**: Broadcasts typing statuses in real-time.
620
+ - **Vector Clock CRDT Sync (`data-rt-crdt`)**: Resolves concurrent writing conflicts on text inputs using timestamps while preserving caret focus selections.
621
+
622
+ ```html
623
+ <!-- Real-time Collaborative Board with cursors and typing indicator -->
624
+ <div data-rt-cursor-share="room_1" class="board-canvas">
625
+ <input data-rt-typing="room_1" placeholder="Typing indicator active..." />
626
+
627
+ <!-- Collaborative CRDT synced textarea -->
628
+ <textarea data-rt-crdt="shared_doc" placeholder="Type here concurrently..."></textarea>
629
+ </div>
630
+ ```
631
+
632
+ ---
633
+
634
+ ## १३. Standalone Testing Utilities (DolphinTestUtils)
635
+
636
+ For continuous integration (CI) and automated tests, Dolphin Client v2.0 exposes a clean standalone testing bundle inside [src/testing.ts](./src/testing.ts):
637
+
638
+ - **`DolphinTestUtils.mockWebSocket()`**: Injects a high-fidelity WebSocket mock constructor that captures outbound payloads into `sentMessages`, mimics connection state transitions, and manages message broadcasting.
639
+ - **Event Simulators**: Programmatically trigger `click` and `change` inputs to test DOM directives in Node.js/Jest environments with zero headless browser requirements.
640
+
641
+ ```javascript
642
+ const { DolphinTestUtils } = require('dolphin-client/dist/testing');
643
+
644
+ // Mock standard WebSocket environment cleanly
645
+ const mockWS = DolphinTestUtils.mockWebSocket();
646
+
647
+ // Trigger connection opening
648
+ mockWS.onopen();
649
+
650
+ // Validate published messages
651
+ dolphin.publish('test/topic', { ok: true });
652
+ expect(mockWS.sentMessages).toContain(JSON.stringify({ topic: 'test/topic', payload: { ok: true } }));
653
+ ```
654
+
655
+ ---
656
+
657
+ ## १४. Styling with DolphinCSS - Premium Aesthetics (DolphinCSS सँग स्टाइलिङ)
658
+
659
+ To make your hookless real-time applications look breathtakingly premium and modern, you can seamlessly combine **Dolphin Client v2.0** with **DolphinCSS**, our advanced visual-first CSS utility framework.
660
+
661
+ DolphinCSS replaces the need to write dozens of Tailwind utility classes by exposing pre-built global components, neon glows, and gorgeous modern effects out-of-the-box.
662
+
663
+ ### १४.१. Integration Setup
664
+ Import the DolphinCSS stylesheet directly inside your browser index or main entrypoint:
665
+
666
+ ```html
667
+ <!-- Import DolphinCSS stylesheet for world-class styling -->
668
+ <link rel="stylesheet" href="path/to/dolphincss/dolphin-css.css">
669
+ ```
670
+
671
+ ### १४.२. Premium Visual Effects (`fx-*`)
672
+ Combine these high-end visual decorators on any card, dialog, input, or container:
673
+ - **`fx-glass`**: Classic frosted glassmorphism with dynamic backdrop blur.
674
+ - **`fx-crystal`**: Ultra-clear crystalline border with inner shadows.
675
+ - **`fx-neon`**: Cyberpunk glowing borders and drop shadows.
676
+ - **`fx-aurora`**: Frosted northern-lights color depth gradient.
677
+ - **`fx-float`**: Smooth 3D floating animation on hover.
678
+
679
+ ### १४.३. Building a Reactive, Glowing DolphinCSS Card Component
680
+ Here is a complete, real-world example of how to build a stunning, frosted-glass profile card that updates reactively in real-time via WebSockets:
681
+
682
+ ```html
683
+ <!-- Loads profile instantly from REST, updates instantly via WebSocket topic "user/profile" -->
684
+ <div
685
+ data-api-get="/api/profile"
686
+ data-rt-bind="user/profile"
687
+ data-rt-template='
688
+ <div data-rt-type="context" class="fx-glass card p-8 border border-white/20 rounded-2xl max-w-sm hover-jelly transition-all duration-300 relative overflow-hidden">
689
+ <!-- Glow background decoration -->
690
+ <div class="absolute top-0 right-0 w-32 h-32 bg-primary-500/20 rounded-full blur-2xl"></div>
691
+
692
+ <!-- Profile Header -->
693
+ <div class="flex-left gap-4 mb-4 relative z-10">
694
+ <div class="w-16 h-16 rounded-full border-2 border-primary-400 overflow-hidden shadow-lg p-0.5">
695
+ <img data-rt-attr="src:avatarUrl,alt:name" class="w-full h-full rounded-full object-cover" />
696
+ </div>
697
+ <div>
698
+ <h3 data-rt-text="name" class="text-xl font-bold text-white m-0"></h3>
699
+ <p data-rt-text="role" class="text-primary-300 text-sm font-medium"></p>
700
+ </div>
701
+ </div>
702
+
703
+ <!-- Bio Description -->
704
+ <p data-rt-text="bio" class="text-white/70 text-sm leading-relaxed mb-6 relative z-10"></p>
705
+
706
+ <!-- Actions Section -->
707
+ <div class="flex-between relative z-10">
708
+ <div class="flex gap-2">
709
+ <span class="px-3 py-1 rounded-full bg-white/10 text-xs font-medium text-white/90">Dolphin</span>
710
+ <span class="px-3 py-1 rounded-full bg-white/10 text-xs font-medium text-white/90">React-Less</span>
711
+ </div>
712
+ <!-- Pulsing glowing green success action button -->
713
+ <button class="circle filled success-500 text-white p-2 glow glow-pulse hover:scale-110 transition-all flex-center">
714
+ <svg class="w-4 h-4" fill="none" stroke="currentColor" viewBox="0 0 24 24">
715
+ <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M9 5l7 7-7 7" />
716
+ </svg>
717
+ </button>
718
+ </div>
719
+ </div>
720
+ '
721
+ ></div>
722
+ ```
723
+
724
+ By marrying the **reactive strength of Dolphin Client** with the **premium design aesthetics of DolphinCSS**, you can build state-of-the-art, lightning-fast interfaces that look premium and responsive.
725
+
726
+ ---
727
+
728
+ ## १५. Production Best Practices (उत्कृष्ट अभ्यासहरू)
729
+
730
+ - **Strict Environment Security**: During native app packaging, always map standard Android/iOS run-time device permissions. Native apps do not suffer from browser HTTP context locks!
731
+ - **Auto Reconnect Policy**: Dolphin Client has an exponentional backoff reconnect strategy built-in. Set `maxReconnect` options to customize connection retry budgets.
732
+ - **Graceful Hardware Fallbacks**: Always test your WebRTC systems with receive-only transceivers (`recvonly`) so desktop terminals with no microphoness/cameras can still receive and play signals properly.
733
+
734
+ Enjoy building hookless, lightning-fast, and premium real-time applications with **Dolphin Client**! 🐬
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "dolphin-client",
3
- "version": "1.0.2",
3
+ "version": "1.0.3",
4
4
  "description": "HTML is back! Hookless, framework-agnostic real-time reactive DOM-binding client for Dolphin Server with WebSockets, WebRTC signaling, and offline REST API fallbacks.",
5
5
  "type": "module",
6
6
  "main": "./dist/index.cjs",
@@ -16,7 +16,8 @@
16
16
  "files": [
17
17
  "dist",
18
18
  "README.md",
19
- "LICENSE"
19
+ "LICENSE",
20
+ "fulltutorial.md"
20
21
  ],
21
22
  "scripts": {
22
23
  "build": "npm run build:iife && npm run build:min && npm run build:esm && npm run build:cjs && tsc",