### Install @sylph/router and @sylph/core Source: https://github.com/sylphxltd/zen/blob/main/docs/modules/_sylph_router.html Instructions on how to install the `@sylph/router` and `@sylph/core` packages using various Node.js package managers. ```Shell npm install @sylph/router @sylph/core # or yarn add @sylph/router @sylph/core # or pnpm add @sylph/router @sylph/core # or bun add @sylph/router @sylph/core ``` -------------------------------- ### Install @sylphlab/zen-draft and @sylphlab/zen-core Source: https://github.com/sylphxltd/zen/blob/main/packages/zen-draft/README.md Instructions for installing the `@sylphlab/zen-draft` and `@sylphlab/zen-core` packages using pnpm, npm, or yarn. ```bash pnpm add @sylphlab/zen-draft @sylphlab/zen-core ``` ```bash npm install @sylphlab/zen-draft @sylphlab/zen-core ``` ```bash yarn add @sylphlab/zen-draft @sylphlab/zen-core ``` -------------------------------- ### Install @sylph/core package Source: https://github.com/sylphxltd/zen/blob/main/packages/zen-core/README.md Instructions to install the @sylph/core package using various Node.js package managers. ```bash npm install @sylph/core # or yarn add @sylph/core # or pnpm add @sylph/core # or bun add @sylph/core ``` -------------------------------- ### Install Zen Package Source: https://github.com/sylphxltd/zen/blob/main/docs/index.html Instructions for installing the @sylph/zen package using common Node.js package managers: npm, yarn, or pnpm. ```bash npm install @sylph/zen # or yarn add @sylph/zen # or pnpm add @sylph/zen ``` -------------------------------- ### Basic Usage of @sylph/router for Route Definition and State Subscription Source: https://github.com/sylphxltd/zen/blob/main/packages/zen-router/README.md This example demonstrates how to define routes, subscribe to the router's state atom, and start listening for history changes. It shows how to use `defineRoutes` to configure paths, `subscribe` to react to URL changes, and `startHistoryListener` to enable SPA navigation. It also illustrates how to extract route parameters and query strings, and update document title based on route data. ```typescript import { $router, defineRoutes, startHistoryListener, open, matchRoutes, RouteConfig } from '@sylph/router'; import { subscribe, get } from '@sylph/core'; // 1. Define your routes // RouteConfig allows arbitrary data associated with a path interface MyRouteConfig extends RouteConfig { componentName: string; title: string; } const routes: MyRouteConfig[] = [ { path: '/', componentName: 'Home', title: 'Homepage' }, { path: '/about', componentName: 'About', title: 'About Us' }, { path: '/users/:id', componentName: 'UserProfile', title: 'User Profile' }, // Dynamic segment { path: '*', componentName: 'NotFound', title: 'Not Found' }, // Catch-all ]; defineRoutes(routes); // 2. Subscribe to the router state atom ($router) const unsubscribeRouter = subscribe($router, (routerState) => { console.log('Path:', routerState.path); console.log('Params:', routerState.params); // e.g., { id: '123' } for /users/123 console.log('Search:', routerState.search); // e.g., { q: 'test' } for /?q=test // You often need to match the current path again to get associated route data const currentMatch = matchRoutes(routerState.path, routes); if (currentMatch) { console.log('Current Component:', (currentMatch.route as MyRouteConfig).componentName); document.title = (currentMatch.route as MyRouteConfig).title; } else { console.log('No matching route component found (404)'); document.title = 'Not Found'; } }); // 3. Start listening to history changes (popstate, link clicks) // Needs to run in a browser environment startHistoryListener(); // 4. Navigate programmatically // open('/about'); // Navigates to /about using pushState // redirect('/users/456?ref=test'); // Navigates using replaceState // Initial state based on current URL (e.g., if loaded at /users/10) const initialState = get($router); console.log('Initial State:', initialState); // To clean up: // unsubscribeRouter(); // stopHistoryListener(); // If needed ``` -------------------------------- ### Install Zen State Management Library Source: https://github.com/sylphxltd/zen/blob/main/README.md Instructions for installing the @sylph/zen package using common JavaScript package managers: npm, yarn, or pnpm. ```bash npm install @sylph/zen ``` ```bash yarn add @sylph/zen ``` ```bash pnpm add @sylph/zen ``` -------------------------------- ### Install @sylph/core Package Source: https://github.com/sylphxltd/zen/blob/main/docs/modules/_sylph_core.html Instructions for installing the @sylph/core library using various popular JavaScript package managers. This provides flexibility for developers to choose their preferred tool for adding the dependency to their project. ```shell npm install @sylph/core # or yarn add @sylph/core # or pnpm add @sylph/core # or bun add @sylph/core ``` -------------------------------- ### Basic Atom State Management Source: https://github.com/sylphxltd/zen/blob/main/docs/index.html Demonstrates the fundamental usage of `atom` for creating reactive state, along with `get`, `set`, and `subscribe` functions to interact with it. Shows how to initialize, update, and listen for changes, including unsubscribing from state updates. ```javascript import { atom, get, set, subscribe } from '@sylph/zen'; const counter = atom(0); const unsubscribe = subscribe(counter, (value, oldValue) => { console.log(`Counter changed from ${oldValue} to ${value}`); }); // Output: Counter changed from undefined to 0 (Initial call) console.log(get(counter)); // Output: 0 set(counter, 1); // Output: Counter changed from 0 to 1 console.log(get(counter)); // Output: 1 set(counter, 1); // No output, value didn't change unsubscribe(); set(counter, 2); // No output, unsubscribed ``` -------------------------------- ### Install @sylph/router and @sylph/core using various package managers Source: https://github.com/sylphxltd/zen/blob/main/packages/zen-router/README.md This snippet provides commands to install the `@sylph/router` and `@sylph/core` packages using common Node.js package managers like npm, yarn, pnpm, and bun. It ensures all necessary dependencies are added to your project for router functionality. ```bash npm install @sylph/router @sylph/core # or yarn add @sylph/router @sylph/core # or pnpm add @sylph/router @sylph/core # or bun add @sylph/router @sylph/core ``` -------------------------------- ### Manage Atom Lifecycles with onMount and onStop in TypeScript Source: https://github.com/sylphxltd/zen/blob/main/packages/zen-core/README.md Illustrates how to use `onMount` to perform setup actions when an atom gains its first subscriber and `onStop` for cleanup when the last subscriber is removed, useful for managing side effects like timers. ```typescript import { atom, onMount, onStop, subscribe, get, set } from '@sylph/core'; const timerAtom = atom(0); let intervalId: ReturnType | undefined; onMount(timerAtom, () => { console.log('Timer atom mounted (first subscriber added)'); intervalId = setInterval(() => { set(timerAtom, get(timerAtom) + 1); // Use functional set/get }, 1000); // Return a cleanup function for onStop return () => { console.log('Timer atom stopped (last subscriber removed)'); if (intervalId) clearInterval(intervalId); intervalId = undefined; }; }); console.log('Subscribing...'); const unsubTimer = subscribe(timerAtom, (value) => { console.log('Timer:', value); }); // Logs: Subscribing... -> Timer atom mounted... -> Timer: 0 -> Timer: 1 ... // setTimeout(() => { // console.log('Unsubscribing...'); // unsubTimer(); // Logs: Unsubscribing... -> Timer atom stopped... // }, 3500); ``` -------------------------------- ### Managing Atom Lifecycles with onMount and onStop Source: https://github.com/sylphxltd/zen/blob/main/docs/modules/_sylph_core.html Explains how to use `onMount` to perform setup actions when an atom gains its first subscriber and `onStop` (via the cleanup function returned by `onMount`) to perform cleanup when the last subscriber is removed. This is useful for managing side effects like timers or event listeners efficiently. ```typescript import { atom, onMount, onStop, subscribe } from '@sylph/core'; const timerAtom = atom(0); onMount(timerAtom, () => { console.log('Timer atom mounted (first subscriber added)'); const intervalId = setInterval(() => { timerAtom.set(timerAtom.get() + 1); }, 1000); // Return a cleanup function for onStop return () => { console.log('Timer atom stopped (last subscriber removed)'); clearInterval(intervalId); }; }); console.log('Subscribing...'); const unsubTimer = subscribe(timerAtom, (value) => { console.log('Timer:', value); }); // Logs: Subscribing... -> Timer atom mounted... -> Timer: 0 -> Timer: 1 ... // setTimeout(() => { // console.log('Unsubscribing...'); // unsubTimer(); // Logs: Unsubscribing... -> Timer atom stopped... // }, 3500); ``` -------------------------------- ### Basic Reactive State with atom Source: https://github.com/sylphxltd/zen/blob/main/README.md Demonstrates the fundamental `atom` primitive for creating reactive state. It shows how to initialize, get, set, and subscribe to an atom's value, including how the initial subscription call works and how unsubscribing stops further notifications. ```typescript import { atom, get, set, subscribe } from '@sylph/zen'; const counter = atom(0); const unsubscribe = subscribe(counter, (value, oldValue) => { console.log(`Counter changed from ${oldValue} to ${value}`); }); // Output: Counter changed from undefined to 0 (Initial call) console.log(get(counter)); // Output: 0 set(counter, 1); // Output: Counter changed from 0 to 1 console.log(get(counter)); // Output: 1 set(counter, 1); // No output, value didn't change unsubscribe(); set(counter, 2); // No output, unsubscribed ``` -------------------------------- ### Using Map for Object State Management Source: https://github.com/sylphxltd/zen/blob/main/docs/modules/_sylph_core.html Illustrates how to use `map` to manage object-like state, `setKey` to update specific properties, and `listenKeys` to subscribe to changes on a subset of keys within the map. It also shows how to retrieve the current state with `get` for direct access. ```typescript import { map, setKey, listenKeys, get } from '@sylph/core'; const user = map({ name: 'Anon', age: 99 }); const unsubscribeKey = listenKeys(user, ['name'], (value) => { console.log('User name changed:', value.name); }); console.log('Initial name:', get(user).name); // Logs: Initial name: Anon setKey(user, 'name', 'Sylph'); // Logs: User name changed: Sylph console.log('Updated name:', get(user).name); // Logs: Updated name: Sylph unsubscribeKey(); ``` -------------------------------- ### Manage Async Operations with Zen's `task` Utility Source: https://github.com/sylphxltd/zen/blob/main/docs/index.html The `task` utility in `@sylph/zen` provides a robust way to handle asynchronous operations, encapsulating loading, error, and data states. This example demonstrates how to define a task, run it with `runTask`, observe its state using `computed` and `subscribe`, and handle both successful outcomes and errors. It also shows how to directly inspect the task's current state with `getTaskState`. ```TypeScript import { task, computed, get, subscribe, runTask, getTaskState } from '@sylph/zen'; const fetchData = async (userId: number): Promise<{ id: number; name: string }> => { // Simulate API call await new Promise(r => setTimeout(r, 50)); if (userId === 0) throw new Error('Invalid ID'); return { id: userId, name: `User ${userId}` }; }; const userTask = task(fetchData); // Use core 'get' to read the task state atom const userStatus = computed([userTask], (state) => { if (state.loading) return 'Loading user...'; if (state.error) return `Error: ${state.error.message}`; if (state.data) return `User Found: ${state.data.name} (ID: ${state.data.id})`; return 'Enter a user ID'; }); // Use core 'subscribe' subscribe(userStatus, status => console.log(status)); // Output: Enter a user ID (Initial call) // Run the task using runTask runTask(userTask, 123) .then(data => console.log('Success:', data)) .catch(err => console.error('Caught Error:', err)); // Output: Loading user... // (after ~50ms) // Output: User Found: User 123 (ID: 123) // Output: Success: { id: 123, name: 'User 123' } // Run with invalid ID runTask(userTask, 0) .catch(err => console.error('Caught Error:', err.message)); // Output: Loading user... // (after ~50ms) // Output: Error: Invalid ID // Output: Caught Error: Invalid ID // You can also get the current state directly console.log(getTaskState(userTask)); // Output: { loading: false, error: Error: Invalid ID, data: undefined } ``` -------------------------------- ### Managing Nested State with DeepMap Source: https://github.com/sylphxltd/zen/blob/main/docs/modules/_sylph_core.html Demonstrates `deepMap` for handling deeply nested object states. It shows how to update specific nested properties using `setPath` and retrieve the current state with `get`, providing a robust way to manage complex configurations. ```typescript import { deepMap, setPath, get } from '@sylph/core'; const settings = deepMap({ user: { theme: 'dark', notifications: true } }); console.log('Initial theme:', get(settings).user.theme); // Logs: Initial theme: dark // Update a nested property setPath(settings, ['user', 'theme'], 'light'); console.log('Updated theme:', get(settings).user.theme); // Logs: Updated theme: light ``` -------------------------------- ### Basic Usage of @sylph/router Source: https://github.com/sylphxltd/zen/blob/main/docs/modules/_sylph_router.html Demonstrates how to create a router, define routes with dynamic segments, and subscribe to route changes using `@sylph/router` and `@sylph/core`. It shows how to access route path, parameters, and associated data. ```TypeScript import { createRouter } from '@sylph/router'; import { subscribe } from '@sylph/core'; // Assuming core is needed for subscribe // Define routes (path: data associated with the route) const routes = { '/': { page: 'home' }, '/about': { page: 'about' }, '/users/:id': { page: 'userProfile' }, // Dynamic segment }; // Create the router atom (defaults to window.location if available) const router = createRouter(routes); // Subscribe to route changes const unsubscribeRouter = subscribe(router, (route) => { if (route) { console.log('Current route:', route.path); console.log('Route params:', route.params); // e.g., { id: '123' } for /users/123 console.log('Route data:', route.data); // e.g., { page: 'userProfile' } } else { console.log('No matching route found (404)'); } }); // To navigate (in a browser environment): // window.history.pushState({}, '', '/users/456'); // To clean up: // unsubscribeRouter(); ``` -------------------------------- ### Initialize Theme and Page Display Source: https://github.com/sylphxltd/zen/blob/main/docs/modules/_sylph_core.html This JavaScript snippet initializes the page theme based on local storage or OS preference and manages the initial display of the body to prevent FOUC (Flash of Unstyled Content). It ensures a smoother user experience by hiding content until the application is ready. ```javascript document.documentElement.dataset.theme = localStorage.getItem("tsd-theme") || "os"; document.body.style.display="none"; setTimeout(() => window.app?app.showPage():document.body.style.removeProperty("display"),500) ``` -------------------------------- ### JavaScript Theme Initialization and Page Display Control Source: https://github.com/sylphxltd/zen/blob/main/docs/hierarchy.html This JavaScript snippet initializes the document's theme based on a value stored in local storage, defaulting to 'os' if not found. It then hides the document body initially and uses a timeout to remove the display property, potentially waiting for an application (window.app) to load and show the page. ```JavaScript document.documentElement.dataset.theme = localStorage.getItem("tsd-theme") || "os";document.body.style.display="none";setTimeout(() => window.app?app.showPage():document.body.style.removeProperty("display"),500) ``` -------------------------------- ### Basic Usage of Atom, Computed, and Subscribe Source: https://github.com/sylphxltd/zen/blob/main/docs/modules/_sylph_core.html Demonstrates the fundamental concepts of @sylph/core: creating a writable `atom` state, deriving a `computed` state from it, and subscribing to state changes using `subscribe`. It also shows how to update an atom and unsubscribe from listeners to manage resource usage. ```typescript import { atom, computed, subscribe } from '@sylph/core'; // Create a writable atom state const count = atom(0); // Create a computed state derived from other atoms const double = computed(count, (value) => value * 2); // Subscribe to changes const unsubscribe = subscribe(double, (value) => { console.log('Double count is now:', value); }); // Update the base atom count.set(1); // Logs: Double count is now: 2 count.set(5); // Logs: Double count is now: 10 // Unsubscribe when no longer needed unsubscribe(); ``` -------------------------------- ### Zen Atom Lifecycle Event Handling with TypeScript Source: https://github.com/sylphxltd/zen/blob/main/README.md This snippet demonstrates how to subscribe to various lifecycle events of a Zen atom, including `onStart` (first listener), `onStop` (last listener), `onSet` (value change outside batch), and `onNotify` (any value change). It shows how to initialize an atom, subscribe to it, set its value, and unsubscribe from both the atom and the event listeners. ```typescript import { atom, set, subscribe, onStart, onStop, onSet, onNotify } from '@sylph/zen'; const myAtom = atom(0); const unsubStart = onStart(myAtom, () => console.log('First listener subscribed!')); const unsubStop = onStop(myAtom, () => console.log('Last listener unsubscribed!')); const unsubSet = onSet(myAtom, (newValue) => console.log(`Setting value to ${newValue}...`)); // Only called outside batch const unsubNotify = onNotify(myAtom, (newValue) => console.log(`Notified with value ${newValue}!`)); const sub1 = subscribe(myAtom, () => {}); // Output: First listener subscribed! // Output: Notified with value 0! (Initial subscribe calls listener, which triggers notify) set(myAtom, 1); // Output: Setting value to 1... // Output: Notified with value 1! sub1(); // Output: Last listener unsubscribed! unsubStart(); unsubStop(); unsubSet(); unsubNotify(); ``` -------------------------------- ### Subscribe to Zen Atom Lifecycle Events Source: https://github.com/sylphxltd/zen/blob/main/docs/index.html This snippet illustrates how to use `@sylph/zen`'s lifecycle event listeners (`onStart`, `onStop`, `onSet`, `onNotify`) to react to changes in an atom's state and listener subscriptions. It demonstrates the order of event firing during initial subscription, value updates, and unsubscription, providing insight into atom behavior. ```TypeScript import { atom, set, subscribe, onStart, onStop, onSet, onNotify } from '@sylph/zen'; const myAtom = atom(0); const unsubStart = onStart(myAtom, () => console.log('First listener subscribed!')); const unsubStop = onStop(myAtom, () => console.log('Last listener unsubscribed!')); const unsubSet = onSet(myAtom, (newValue) => console.log(`Setting value to ${newValue}...`)); // Only called outside batch const unsubNotify = onNotify(myAtom, (newValue) => console.log(`Notified with value ${newValue}!`)); const sub1 = subscribe(myAtom, () => {}); // Output: First listener subscribed! // Output: Notified with value 0! (Initial subscribe calls listener, which triggers notify) set(myAtom, 1); // Output: Setting value to 1... // Output: Notified with value 1! sub1(); // Output: Last listener unsubscribed! unsubStart(); unsubStop(); unsubSet(); unsubNotify(); ``` -------------------------------- ### Manage object state with map in Zen Source: https://github.com/sylphxltd/zen/blob/main/docs/index.html Illustrates the `map` function for optimized object state management, allowing updates and subscriptions to individual keys. It shows how to subscribe to the entire map, listen to specific key changes, and update keys or the whole object. ```javascript import { map, get, subscribe, setMapKey, setMapValue, listenMapKeys } from '@sylph/zen'; const profile = map({ name: 'John', age: 30, city: 'New York' }); const unsub = subscribe(profile, value => console.log('Profile updated:', value)); // Output: Profile updated: { name: 'John', age: 30, city: 'New York' } (Initial call) // Listen to specific key changes const unsubAge = listenMapKeys(profile, ['age'], (value, key, fullObject) => { console.log(`Key '${key}' changed to: ${value}`);}); setMapKey(profile, 'age', 31); // Output: Key 'age' changed to: 31 // Output: Profile updated: { name: 'John', age: 31, city: 'New York' } setMapKey(profile, 'name', 'Jane'); // Output: Profile updated: { name: 'Jane', age: 31, city: 'New York' } // (Age listener not called) setMapValue(profile, { name: 'Peter', age: 40, city: 'London' }); // Update whole object // Output: Key 'age' changed to: 40 // Output: Profile updated: { name: 'Peter', age: 40, city: 'London' } unsub(); unsubAge(); ``` -------------------------------- ### Basic State Management with Atom and Computed in TypeScript Source: https://github.com/sylphxltd/zen/blob/main/packages/zen-core/README.md Demonstrates how to create writable atoms, derive computed states, subscribe to changes, and update atom values using the functional API. ```typescript import { atom, computed, subscribe, get, set } from '@sylph/core'; // Create a writable atom state const count = atom(0); // Create a computed state derived from other atoms const double = computed(count, (value) => value * 2); // Subscribe to changes const unsubscribe = subscribe(double, (value) => { console.log('Double count is now:', value); }); // Read current value console.log('Initial count:', get(count)); // Logs: Initial count: 0 console.log('Initial double:', get(double)); // Logs: Initial double: 0 // Update the base atom using the functional API set(count, 1); // Logs: Double count is now: 2 set(count, 5); // Logs: Double count is now: 10 // Unsubscribe when no longer needed unsubscribe(); ``` -------------------------------- ### Batch State Updates for Performance in TypeScript Source: https://github.com/sylphxltd/zen/blob/main/packages/zen-core/README.md Explains how to use `batch` to group multiple state updates, ensuring that subscribers are notified only once after all batched updates are complete, optimizing performance. ```typescript import { atom, computed, batch, subscribe, set } from '@sylph/core'; const firstName = atom('John'); const lastName = atom('Doe'); const fullName = computed([firstName, lastName], (f, l) => `${f} ${l}`); const unsubscribeBatch = subscribe(fullName, (value) => { // This listener will only run ONCE after the batch console.log('Full name updated:', value); }); batch(() => { set(firstName, 'Jane'); set(lastName, 'Smith'); // fullName listener is not triggered here yet }); // Logs: Full name updated: Jane Smith unsubscribeBatch(); ``` -------------------------------- ### Derived State with computed Source: https://github.com/sylphxltd/zen/blob/main/README.md Illustrates how to use the `computed` primitive to create derived state based on one or multiple `atom`s. It demonstrates how changes in the source atoms automatically trigger updates in the computed values and their subscribers, highlighting the granular nature of subscriptions. ```typescript import { atom, computed, get, set, subscribe } from '@sylph/zen'; const count = atom(10); const message = atom(' apples'); // Computed value based on count const double = computed([count], (value) => value * 2); // Computed value based on multiple atoms const fullMessage = computed([count, message], (num, msg) => `${num}${msg}`); const unsubDouble = subscribe(double, value => console.log('Double:', value)); // Output: Double: 20 (Initial call) const unsubMsg = subscribe(fullMessage, value => console.log('Message:', value)); // Output: Message: 10 apples (Initial call) console.log(get(double)); // Output: 20 console.log(get(fullMessage)); // Output: 10 apples set(count, 15); // Output: Double: 30 // Output: Message: 15 apples set(message, ' oranges'); // Output: Message: 15 oranges // (Double listener not called as 'double' didn't change) unsubDouble(); unsubMsg(); ``` -------------------------------- ### Handling Asynchronous Operations with Task Source: https://github.com/sylphxltd/zen/blob/main/docs/modules/_sylph_core.html Illustrates the `task` primitive for managing asynchronous operations like API calls. It shows how to define a task, run it with parameters, and subscribe to its state (loading, error, data) to react to different stages of the asynchronous process, including error handling. ```typescript import { task, subscribe } from '@sylph/core'; const fetchData = task(async (id: number) => { // Simulate API call await new Promise(resolve => setTimeout(resolve, 50)); if (id < 0) throw new Error('Invalid ID'); return { data: `User data for ${id}` }; }); const unsubscribeTask = subscribe(fetchData, (state) => { if (state.loading) console.log('Task loading...'); if (state.error) console.error('Task error:', state.error.message); if (state.data) console.log('Task success:', state.data); }); fetchData.run(123); // Logs: Task loading... -> Task success: { data: 'User data for 123' } // fetchData.run(-1); // Would log: Task loading... -> Task error: Invalid ID // unsubscribeTask(); // Usually called on component unmount ``` -------------------------------- ### Manage Object State with Map in TypeScript Source: https://github.com/sylphxltd/zen/blob/main/packages/zen-core/README.md Illustrates using `map` to manage object-like state, `setKey` to update specific properties, and `listenKeys` to subscribe to changes on selected keys. ```typescript import { map, setKey, listenKeys, get } from '@sylph/core'; const user = map({ name: 'Anon', age: 99 }); const unsubscribeKey = listenKeys(user, ['name'], (value) => { // Note: listener receives the full map value console.log('User name changed:', value.name); }); console.log('Initial name:', get(user).name); // Logs: Initial name: Anon setKey(user, 'name', 'Sylph'); // Logs: User name changed: Sylph console.log('Updated name:', get(user).name); // Logs: Updated name: Sylph unsubscribeKey(); ``` -------------------------------- ### Produce New State with Draft Mutations and Patch Generation Source: https://github.com/sylphxltd/zen/blob/main/packages/zen-draft/README.md Demonstrates how to use the `produce` function to create a new immutable state from a base state by mutating a draft. It also shows how to enable and capture JSON patches and inverse patches generated during the process, and how to update a `zen-core` atom. ```typescript import { produce } from '@sylphlab/zen-draft'; import { atom } from '@sylphlab/zen-core'; const myAtom = atom({ user: { name: 'Alice', age: 30 }, tags: ['a', 'b'] }); // Get current state const currentState = myAtom.get(); // Produce the next state using a recipe const [nextState, patches, inversePatches] = produce( currentState, (draft) => { draft.user.age++; draft.tags.push('c'); delete draft.user.name; // Example deletion }, { patches: true, inversePatches: true } // Enable patch generation ); // Update the atom with the new state myAtom.set(nextState); console.log(currentState); // Output: { user: { name: 'Alice', age: 30 }, tags: ['a', 'b'] } console.log(nextState); // Output: { user: { age: 31 }, tags: ['a', 'b', 'c'] } console.log(patches); // Output: [ // { op: 'replace', path: ['user', 'age'], value: 31 }, // { op: 'add', path: ['tags', 2], value: 'c' }, // Note: Array index for push // { op: 'remove', path: ['user', 'name'] } // ] console.log(inversePatches); // Output: [ // { op: 'replace', path: ['user', 'age'], value: 30 }, // { op: 'remove', path: ['tags', 2] }, // { op: 'add', path: ['user', 'name'], value: 'Alice' } // ] ``` -------------------------------- ### Create derived state with computed in Zen Source: https://github.com/sylphxltd/zen/blob/main/docs/index.html Demonstrates how to use `computed` to create derived state from one or more `atom`s. It shows initial value retrieval, subscription to changes, and how updates to source atoms trigger re-evaluation of computed values. ```javascript import { atom, computed, get, set, subscribe } from '@sylph/zen'; const count = atom(10); const message = atom(' apples'); // Computed value based on count const double = computed([count], (value) => value * 2); // Computed value based on multiple atoms const fullMessage = computed([count, message], (num, msg) => `${num}${msg}`); const unsubDouble = subscribe(double, value => console.log('Double:', value)); // Output: Double: 20 (Initial call) const unsubMsg = subscribe(fullMessage, value => console.log('Message:', value)); // Output: Message: 10 apples (Initial call) console.log(get(double)); // Output: 20 console.log(get(fullMessage)); // Output: 10 apples set(count, 15); // Output: Double: 30 // Output: Message: 15 apples set(message, ' oranges'); // Output: Message: 15 oranges // (Double listener not called as 'double' didn't change) unsubDouble(); unsubMsg(); ``` -------------------------------- ### Manage nested state with deepMap in Zen Source: https://github.com/sylphxltd/zen/blob/main/docs/index.html Explains `deepMap` for efficiently managing and subscribing to changes within nested objects and arrays. It demonstrates subscribing to the entire deep map, listening to specific deep paths, and updating values using both string and array paths. ```javascript import { deepMap, get, subscribe, setDeepMapPath, setDeepMapValue, listenDeepMapPaths } from '@sylph/zen'; const settings = deepMap({ user: { name: 'Anon', preferences: { theme: 'light', notifications: true } }, data: [10, 20, 30]}); const unsub = subscribe(settings, value => console.log('Settings updated:', value)); // Output: Settings updated: { user: { name: 'Anon', preferences: { theme: 'light', notifications: true } }, data: [ 10, 20, 30 ] } (Initial call) // Listen to a deep path const unsubTheme = listenDeepMapPaths(settings, [['user', 'preferences', 'theme']], (value, path, fullObject) => { // Note: path received might be string or array depending on how it was registered/changed console.log(`Path '${Array.isArray(path) ? path.join('.') : path}' changed to: ${value}`);}); // Listen to an array element path const unsubData = listenDeepMapPaths(settings, [['data', 1]], (value, path, fullObject) => { console.log(`Path 'data[1]' changed to: ${value}`);}); // Update deep value using string path setDeepMapPath(settings, 'user.preferences.theme', 'dark'); // Output: Path 'user.preferences.theme' changed to: dark // Output: Settings updated: { user: {..., preferences: { theme: 'dark', ... }}, ... } // Update deep value using array path setDeepMapPath(settings, ['data', 1], 25); // Output: Path 'data[1]' changed to: 25 // Output: Settings updated: { ..., data: [10, 25, 30] } // Update unrelated path setDeepMapPath(settings, 'user.name', 'Alice'); // Output: Settings updated: { user: { name: 'Alice', ...}, ... } // (Theme and data listeners not called) unsub(); unsubTheme(); unsubData(); ``` -------------------------------- ### Handle Asynchronous Operations with Task in TypeScript Source: https://github.com/sylphxltd/zen/blob/main/packages/zen-core/README.md Demonstrates using `task` to manage asynchronous operations (like API calls), tracking loading, error, and success states, and subscribing to task lifecycle events. ```typescript import { task, subscribe } from '@sylph/core'; const fetchData = task(async (id: number) => { // Simulate API call await new Promise(resolve => setTimeout(resolve, 50)); if (id < 0) throw new Error('Invalid ID'); return { data: `User data for ${id}` }; }); const unsubscribeTask = subscribe(fetchData, (state) => { if (state.loading) console.log('Task loading...'); if (state.error) console.error('Task error:', state.error.message); if (state.data) console.log('Task success:', state.data); }); fetchData.run(123); // Logs: Task loading... -> Task success: { data: 'User data for 123' } // fetchData.run(-1); // Would log: Task loading... -> Task error: Invalid ID // unsubscribeTask(); // Usually called on component unmount ``` -------------------------------- ### Batching Multiple State Updates Source: https://github.com/sylphxltd/zen/blob/main/docs/modules/_sylph_core.html Demonstrates the `batch` function, which allows multiple state updates to be performed within a single transaction. This ensures that computed states and subscribers are only notified once after all batched updates are complete, optimizing performance and preventing unnecessary re-renders. ```typescript import { atom, batch, subscribe } from '@sylph/core'; const firstName = atom('John'); const lastName = atom('Doe'); const fullName = computed([firstName, lastName], (f, l) => `${f} ${l}`); const unsubscribeBatch = subscribe(fullName, (value) => { // This listener will only run ONCE after the batch console.log('Full name updated:', value); }); batch(() => { firstName.set('Jane'); lastName.set('Smith'); // fullName listener is not triggered here yet }); // Logs: Full name updated: Jane Smith unsubscribeBatch(); ``` -------------------------------- ### Manage Object State with `map` in TypeScript Source: https://github.com/sylphxltd/zen/blob/main/README.md The `map` utility is optimized for managing flat object state, allowing updates and subscriptions to individual keys or the entire object. It demonstrates `subscribe` for full object changes, `listenMapKeys` for specific key listeners, `setMapKey` to update individual properties, and `setMapValue` to replace the entire object. ```TypeScript import { map, get, subscribe, setMapKey, setMapValue, listenMapKeys } from '@sylph/zen'; const profile = map({ name: 'John', age: 30, city: 'New York' }); const unsub = subscribe(profile, value => console.log('Profile updated:', value)); // Output: Profile updated: { name: 'John', age: 30, city: 'New York' } (Initial call) // Listen to specific key changes const unsubAge = listenMapKeys(profile, ['age'], (value, key, fullObject) => { console.log(`Key '${key}' changed to: ${value}`); }); setMapKey(profile, 'age', 31); // Output: Key 'age' changed to: 31 // Output: Profile updated: { name: 'John', age: 31, city: 'New York' } setMapKey(profile, 'name', 'Jane'); // Output: Profile updated: { name: 'Jane', age: 31, city: 'New York' } // (Age listener not called) setMapValue(profile, { name: 'Peter', age: 40, city: 'London' }); // Update whole object // Output: Key 'age' changed to: 40 // Output: Profile updated: { name: 'Peter', age: 40, city: 'London' } unsub(); unsubAge(); ``` -------------------------------- ### Apply JSON Patches to a Base State Source: https://github.com/sylphxltd/zen/blob/main/packages/zen-draft/README.md Illustrates how to use the `applyPatches` function to transform a base state into a new state by applying an array of JSON patches. This is useful for replaying changes or synchronizing state. ```typescript import { applyPatches } from '@sylphlab/zen-draft'; const baseState = { user: { name: 'Alice' } }; const patches = [ { op: 'replace', path: ['user', 'name'], value: 'Bob' }, { op: 'add', path: ['user', 'age'], value: 40 }, ]; const nextState = applyPatches(baseState, patches); console.log(nextState); // Output: { user: { name: 'Bob', age: 40 } } ``` -------------------------------- ### Handle Asynchronous Operations with `task` in TypeScript Source: https://github.com/sylphxltd/zen/blob/main/README.md The `task` utility provides a structured way to manage asynchronous operations, tracking their loading, error, and data states. It demonstrates how to define an async function, wrap it with `task`, create a `computed` derived state for display, `subscribe` to status changes, `runTask` with arguments, and handle both successful and erroneous task executions. `getTaskState` allows direct access to the current state. ```TypeScript import { task, computed, get, subscribe, runTask, getTaskState } from '@sylph/zen'; const fetchData = async (userId: number): Promise<{ id: number; name: string }> => { // Simulate API call await new Promise(r => setTimeout(r, 50)); if (userId === 0) throw new Error('Invalid ID'); return { id: userId, name: `User ${userId}` }; }; const userTask = task(fetchData); // Use core 'get' to read the task state atom const userStatus = computed([userTask], (state) => { if (state.loading) return 'Loading user...'; if (state.error) return `Error: ${state.error.message}`; if (state.data) return `User Found: ${state.data.name} (ID: ${state.data.id})`; return 'Enter a user ID'; }); // Use core 'subscribe' subscribe(userStatus, status => console.log(status)); // Output: Enter a user ID (Initial call) // Run the task using runTask runTask(userTask, 123) .then(data => console.log('Success:', data)) .catch(err => console.error('Caught Error:', err)); // Output: Loading user... // (after ~50ms) // Output: User Found: User 123 (ID: 123) // Output: Success: { id: 123, name: 'User 123' } // Run with invalid ID runTask(userTask, 0) .catch(err => console.error('Caught Error:', err.message)); // Output: Loading user... // (after ~50ms) // Output: Error: Invalid ID // Output: Caught Error: Invalid ID // You can also get the current state directly console.log(getTaskState(userTask)); // Output: { loading: false, error: Error: Invalid ID, data: undefined } ``` -------------------------------- ### Manage Nested Object State with DeepMap in TypeScript Source: https://github.com/sylphxltd/zen/blob/main/packages/zen-core/README.md Shows how to use `deepMap` for deeply nested state structures, `setPath` for updating values at specific paths, and `listenPaths` for subscribing to changes on nested properties. ```typescript import { deepMap, setPath, listenPaths, get } from '@sylph/core'; const settings = deepMap({ user: { theme: 'dark', notifications: true }, other: [1, 2] }); const unsubPath = listenPaths(settings, [['user', 'theme']], (value) => { // Note: listener receives the full deepMap value console.log('Theme changed:', value.user.theme); }); console.log('Initial theme:', get(settings).user.theme); // Logs: Initial theme: dark // Update a nested property setPath(settings, ['user', 'theme'], 'light'); // Logs: Theme changed: light setPath(settings, ['other', 0], 100); // Update array element console.log('Updated theme:', get(settings).user.theme); // Logs: Updated theme: light console.log('Updated array:', get(settings).other); // Logs: Updated array: [100, 2] unsubPath(); ``` -------------------------------- ### Manage Nested State with `deepMap` in TypeScript Source: https://github.com/sylphxltd/zen/blob/main/README.md The `deepMap` utility is designed for efficient management and subscription to changes within deeply nested objects and arrays. It illustrates `subscribe` for overall changes, `listenDeepMapPaths` for specific deep path listeners, `setDeepMapPath` to update values at a given path (string or array), and `setDeepMapValue` to replace the entire deep object. ```TypeScript import { deepMap, get, subscribe, setDeepMapPath, setDeepMapValue, listenDeepMapPaths } from '@sylph/zen'; const settings = deepMap({ user: { name: 'Anon', preferences: { theme: 'light', notifications: true } }, data: [10, 20, 30] }); const unsub = subscribe(settings, value => console.log('Settings updated:', value)); // Output: Settings updated: { user: { name: 'Anon', preferences: { theme: 'light', notifications: true } }, data: [ 10, 20, 30 ] } (Initial call) // Listen to a deep path const unsubTheme = listenDeepMapPaths(settings, [['user', 'preferences', 'theme']], (value, path, fullObject) => { // Note: path received might be string or array depending on how it was registered/changed console.log(`Path '${Array.isArray(path) ? path.join('.') : path}' changed to: ${value}`); }); // Listen to an array element path const unsubData = listenDeepMapPaths(settings, [['data', 1]], (value, path, fullObject) => { console.log(`Path 'data[1]' changed to: ${value}`); }); // Update deep value using string path setDeepMapPath(settings, 'user.preferences.theme', 'dark'); // Output: Path 'user.preferences.theme' changed to: dark // Output: Settings updated: { user: {..., preferences: { theme: 'dark', ... }}, ... } // Update deep value using array path setDeepMapPath(settings, ['data', 1], 25); // Output: Path 'data[1]' changed to: 25 // Output: Settings updated: { ..., data: [10, 25, 30] } // Update unrelated path setDeepMapPath(settings, 'user.name', 'Alice'); // Output: Settings updated: { user: { name: 'Alice', ...}, ... } // (Theme and data listeners not called) unsub(); unsubTheme(); unsubData(); ``` === COMPLETE CONTENT === This response contains all available snippets from this library. No additional content exists. Do not make further requests.