### domx Quick Start Example
Source: https://github.com/adamzwasserman/domx/blob/main/site/docs.html
A basic example demonstrating the core functionality of domx: importing functions, defining a manifest, collecting state from the DOM, applying state to the DOM, and observing state changes. It shows how to interact with DOM elements programmatically.
```javascript
import { collect, apply, observe } from 'domx';
// Define a manifest
const manifest = {
username: { selector: '#username', read: 'value', write: 'value' },
rememberMe: { selector: '#remember', read: 'checked', write: 'checked' }
};
// Collect state from DOM
const state = collect(manifest);
// { username: "alice", rememberMe: true }
// Apply state to DOM
apply(manifest, { username: "bob" });
// Observe changes
const unsubscribe = observe(manifest, (state) => {
console.log('State changed:', state);
});
// Stop observing
unsubscribe();
```
--------------------------------
### Install domx via npm or CDN
Source: https://github.com/adamzwasserman/domx/blob/main/README.md
Instructions for installing the domx library. It can be added to your project using npm or included directly in your HTML via a CDN link.
```bash
npm install domx
```
```html
```
--------------------------------
### Install domx via npm
Source: https://github.com/adamzwasserman/domx/blob/main/site/index.html
Provides the npm command to install the domx library as a project dependency. This is the recommended method for integrating domx into modern JavaScript projects.
```bash
npm install domx
```
--------------------------------
### Apply State to DOM using apply() API
Source: https://github.com/adamzwasserman/domx/blob/main/README.md
This example shows the direct API usage of `domx.apply()`. It demonstrates how to update specific DOM elements with new values by providing a manifest and a state object containing the desired updates.
```javascript
domx.apply(manifest, { username: "alice" });
```
--------------------------------
### Collect DOM State using collect() API
Source: https://github.com/adamzwasserman/domx/blob/main/README.md
This is a direct API usage example for the `collect` function in domx. It demonstrates how to pass a manifest object to `domx.collect()` to retrieve the current state from the DOM, returning the state as an object.
```javascript
const state = domx.collect(manifest);
```
--------------------------------
### HTMX Integration Setup
Source: https://github.com/adamzwasserman/domx/blob/main/site/docs.html
This section details how to integrate DOMX with HTMX by including the DOMX HTMX extension script after the main htmx library. It also shows how to define a manifest for use with `dx-manifest` attribute. Dependencies: HTMX library, DOMX htmx extension.
```html
...
```
--------------------------------
### Subscribe to Raw MutationRecords with on() API
Source: https://github.com/adamzwasserman/domx/blob/main/README.md
This example demonstrates the low-level `domx.on()` API, which allows for direct subscription to raw `MutationRecord` objects. This is useful for framework integrations or when fine-grained control over DOM change events is needed. It returns an unsubscribe function.
```javascript
const unsubscribe = domx.on((mutations) => {
// Process raw mutations
});
```
--------------------------------
### Apply State to DOM Elements
Source: https://github.com/adamzwasserman/domx/blob/main/README.md
This example illustrates how to use the `domx.apply()` function to update DOM elements with new state values. It takes a manifest and a state object, applying only the entries for which a `write` method is defined in the manifest.
```javascript
domx.apply(manifest, { username: "bob", theme: "light" });
// DOM is updated
```
--------------------------------
### Define Manifest for Reading and Writing State
Source: https://github.com/adamzwasserman/domx/blob/main/README.md
This example shows how to define a manifest object that specifies how to read from and write to DOM elements. It includes definitions for input values, checkbox states, and data attributes, utilizing shortcut notations for common read/write operations.
```javascript
const manifest = {
username: { selector: '#username', read: 'value', write: 'value' },
rememberMe: { selector: '#remember', read: 'checked', write: 'checked' },
theme: { selector: '[data-theme]', read: 'data:theme', write: 'data:theme' }
};
```
--------------------------------
### Custom Read/Write Functions for Manifest
Source: https://github.com/adamzwasserman/domx/blob/main/README.md
This example demonstrates how to define custom read and write functions within a manifest entry for complex state manipulation. The `read` function extracts data by combining attributes, and the `write` function parses a value and sets multiple data attributes. A security warning advises against using unsafe DOM methods.
```javascript
const manifest = {
combined: {
selector: '#thing',
read: (el) => `${el.dataset.foo}-${el.dataset.bar}`,
write: (el, val) => {
const [foo, bar] = val.split('-');
el.dataset.foo = foo;
el.dataset.bar = bar;
}
}
};
```
--------------------------------
### Replay Cached Request for Page Refresh Recovery
Source: https://github.com/adamzwasserman/domx/blob/main/README.md
This example demonstrates the `domx.replay()` function, which attempts to resend a previously cached request. This is useful for recovering state after a page refresh. It returns the response object or null if no valid cache exists.
```javascript
// On page load
const response = await domx.replay();
if (response?.ok) {
const html = await response.text();
container.innerHTML = html;
}
```
--------------------------------
### Collect DOM State with Manifest (JavaScript)
Source: https://context7.com/adamzwasserman/domx/llms.txt
Reads current DOM state based on a manifest definition, mapping labels to DOM selectors and read methods. It returns an object containing the extracted state values. This is useful for getting the current values of form elements or attributes.
```javascript
const manifest = {
searchQuery: { selector: '#search', read: 'value' },
isActive: { selector: '#toggle', read: 'checked' },
sortDir: { selector: '[data-sort]', read: 'attr:data-sort-dir' },
tags: { selector: '.tag', read: 'text' }
};
// HTML in page:
//
//
//
// JavaScript
// Python
const state = domx.collect(manifest);
console.log(state);
// Output: {
// searchQuery: "hello",
// isActive: true,
// sortDir: "asc",
// tags: ["JavaScript", "Python"]
// }
```
--------------------------------
### Include domx via CDN
Source: https://github.com/adamzwasserman/domx/blob/main/site/index.html
Demonstrates how to include the domx library in an HTML document using a Content Delivery Network (CDN) link. This is a simple way to add domx to static websites or for quick testing.
```html
```
--------------------------------
### Low-Level Mutation Record Subscription
Source: https://github.com/adamzwasserman/domx/blob/main/site/docs.html
The `on` function provides a low-level subscription to raw `MutationRecords`. It is primarily intended for framework integration purposes. Inputs: A callback function that accepts `mutations`. Outputs: An unsubscribe function.
```javascript
const unsubscribe = on((mutations) => {
// Process raw MutationRecords
});
```
--------------------------------
### Send DOM State via Fetch with Caching
Source: https://github.com/adamzwasserman/domx/blob/main/site/docs.html
The `send` function collects the current DOM state using a manifest, caches it in `localStorage`, and then transmits it using the `fetch` API. Supports optional fetch options. Security Note: Data in `localStorage` is accessible to any script on the same domain; avoid sensitive data. Dependencies: `fetch` API, `localStorage`.
```javascript
const response = await send('/api/save', manifest, {
headers: { 'X-Custom': 'value' }
});
```
--------------------------------
### domx apply API
Source: https://context7.com/adamzwasserman/domx/llms.txt
Writes state values to DOM elements. Only processes manifest entries that include a `write` key.
```APIDOC
## domx.apply(manifest, state)
### Description
Writes state values to DOM elements. Only processes manifest entries that include a `write` key.
### Method
`apply`
### Parameters
#### Path Parameters
None
#### Query Parameters
None
#### Request Body
- **manifest** (object) - Required - An object mapping labels to DOM selectors and read/write methods.
- **[label]** (object) - Required - Configuration for a state property.
- **selector** (string) - Required - CSS selector for the DOM element.
- **read** (string) - Optional - The method or attribute to read from the element.
- **write** (string) - Required - The method or attribute to write to the element (e.g., 'value', 'checked', 'data:theme').
- **state** (object) - Required - An object containing the state values to apply to the DOM.
- **[label]** (any) - Required - The state value corresponding to the manifest label.
### Request Example
```json
{
"manifest": {
"username": { "selector": "#username", "read": "value", "write": "value" },
"theme": { "selector": "[data-theme]", "read": "data:theme", "write": "data:theme" },
"rememberMe": { "selector": "#remember", "read": "checked", "write": "checked" }
},
"state": {
"username": "bob",
"theme": "light",
"rememberMe": true
}
}
```
### Response
#### Success Response (void)
This function does not return a value.
#### Response Example
N/A
```
--------------------------------
### replay()
Source: https://context7.com/adamzwasserman/domx/llms.txt
Re-sends a cached request from localStorage. This is useful for restoring state after a page refresh. It returns null if no valid cache exists or if the cache has expired (default 5-minute TTL).
```APIDOC
## POST /api/replay
### Description
Replays a previously cached request from localStorage. If a valid, non-expired cache entry is found, it resends the request and returns the response. Otherwise, it returns null.
### Method
POST
### Endpoint
`/api/replay`
### Parameters
None
### Request Example
```javascript
document.addEventListener('DOMContentLoaded', async () => {
const response = await domx.replay();
if (response && response.ok) {
const html = await response.text();
const container = document.getElementById('results-container');
container.innerHTML = html;
console.log('State restored from cache');
} else if (response === null) {
console.log('No cached state, showing default view');
} else {
console.error('Failed to restore state:', response.status);
}
});
```
### Response
#### Success Response (200)
Returns the response from the replayed request if successful.
#### Response Example
(Returns raw response object from fetch API, or null if no cache found/expired)
### Notes
- The cache has a default Time-To-Live (TTL) of 5 minutes.
- The cache format in localStorage is typically `{"url": "/api/search", "state": {...}, "ts": 1704067200000}`.
```
--------------------------------
### Observe DOM State Changes
Source: https://github.com/adamzwasserman/domx/blob/main/README.md
This snippet shows how to set up an observer for DOM state changes using `domx.observe()`. It takes a manifest and a callback function that is executed whenever a relevant change is detected in the DOM. The function returns an unsubscribe handler to stop observing.
```javascript
const unsubscribe = domx.observe(manifest, (state) => {
console.log('State changed:', state);
});
// Later: stop observing
unsubscribe();
```
--------------------------------
### send(url, manifest, opts)
Source: https://context7.com/adamzwasserman/domx/llms.txt
Collects state from the DOM based on a manifest, caches it to localStorage, and sends it via a POST request. This is useful for forms and search interfaces that require persistence across refreshes.
```APIDOC
## POST /api/send
### Description
Collects state from the DOM using a provided manifest, caches it locally, and sends it as a POST request to the specified URL. It handles form data, search inputs, and other DOM elements.
### Method
POST
### Endpoint
`/api/send`
### Parameters
#### Path Parameters
None
#### Query Parameters
None
#### Request Body
- **url** (string) - Required - The URL to send the POST request to.
- **manifest** (object) - Required - An object defining the DOM elements to observe and how to read their state.
- **`selector`** (string) - Required - A CSS selector for the DOM element.
- **`read`** (string | function) - Required - Specifies how to read the state from the element (e.g., 'value', 'attr:data-sort-dir', 'data:page', or a custom function).
- **`write`** (function) - Optional - A function to write state back to the element.
- **opts** (object) - Optional - Additional options for the fetch request, such as headers.
- **`headers`** (object) - Optional - Custom headers for the request.
### Request Example
```javascript
const manifest = {
searchQuery: { selector: '#search', read: 'value' },
sortDir: { selector: '[data-sort]', read: 'attr:data-sort-dir' },
page: { selector: '[data-page]', read: 'data:page' }
};
try {
const response = await domx.send('/api/search', manifest, {
headers: {
'X-Custom-Header': 'value',
'Authorization': 'Bearer token123'
}
});
if (response.ok) {
const html = await response.text();
document.getElementById('results').innerHTML = html;
} else {
console.error('Search failed:', response.status);
}
} catch (error) {
console.error('Network error:', error);
}
```
### Response
#### Success Response (200)
Returns the response from the server, typically HTML content.
#### Response Example
(Returns raw response object from fetch API)
### Notes
- The POST body sent will be a JSON object containing the collected state.
- The library also caches the request details (URL, state, timestamp) in localStorage.
```
--------------------------------
### Collect, Apply, and Observe DOM State with domx
Source: https://github.com/adamzwasserman/domx/blob/main/site/index.html
Demonstrates the core functionalities of domx: collecting state from the DOM based on a manifest, applying state changes to the DOM, and observing DOM changes to trigger callbacks with updated state. The `collect` function reads state, `apply` writes state, and `observe` listens for changes.
```javascript
// Read state from DOM
const state = domx.collect(manifest);
// { searchQuery: "hello", sortDir: "asc", filters: ["active"] }
// Write state to DOM
domx.apply(manifest, { searchQuery: "world" });
// Watch for changes
domx.observe(manifest, (state) => {
console.log('State changed:', state);
});
```
--------------------------------
### Observe DOM Changes with observe() API
Source: https://github.com/adamzwasserman/domx/blob/main/README.md
This snippet illustrates the direct API usage of `domx.observe()`. It shows how to set up a listener for DOM changes based on a manifest, triggering a callback function with the updated state whenever changes are detected. The `unsubscribe` function is returned to stop the observation.
```javascript
const unsubscribe = domx.observe(manifest, (state) => {
// Called on any relevant DOM change
});
```
--------------------------------
### Custom Read/Write Functions
Source: https://context7.com/adamzwasserman/domx/llms.txt
Supports custom extractor (read) and writer (write) functions for complex state transformations in the manifest.
```APIDOC
## Manually Collect and Apply State
### Description
DOMX allows for advanced state management by defining custom functions within the manifest to read (extract) or write state to DOM elements. This enables complex data transformations and interactions beyond simple attribute or value retrieval.
### Method
N/A (These are programmatic functions)
### Endpoint
N/A
### Parameters
When defining a `manifest` object:
- **`read`** (function) - A function that takes the DOM element as an argument and returns the state to be collected.
- **`write`** (function) - A function that takes the DOM element and the new state value as arguments, and applies the state to the element.
### Request Example
```javascript
const manifest = {
// Combine multiple data attributes
coordinates: {
selector: '#location',
read: (el) => `${el.dataset.lat},${el.dataset.lng}`,
write: (el, val) => {
const [lat, lng] = val.split(',');
el.dataset.lat = lat;
el.dataset.lng = lng;
}
},
// Extract computed styles
visibility: {
selector: '#panel',
read: (el) => window.getComputedStyle(el).display !== 'none',
write: (el, visible) => {
el.style.display = visible ? 'block' : 'none';
}
}
};
// Collect state using custom read functions
const state = domx.collect(manifest);
// Example output: { coordinates: "40.7128,-74.0060", visibility: false }
// Apply state using custom write functions
domx.apply(manifest, { coordinates: "34.0522,-118.2437", visibility: true });
// This would update the location element and make the panel visible.
```
### Response
N/A (These are programmatic operations)
### Notes
- `domx.collect(manifest)`: Executes the `read` functions for all items in the manifest and returns an object of collected states.
- `domx.apply(manifest, stateObject)`: Iterates through `stateObject` and uses the `write` functions defined in the manifest to update the corresponding DOM elements.
```
--------------------------------
### DOMX Read/Write Shortcuts Manifest (JavaScript)
Source: https://context7.com/adamzwasserman/domx/llms.txt
Defines a manifest object that maps shortcut names to DOM element selectors and the specific properties or attributes to read from or write to. This enables simplified DOM manipulation by abstracting away direct element property access.
```javascript
const manifest = {
// "value" - for input fields
textInput: {
selector: '#text',
read: 'value',
write: 'value'
},
// "checked" - for checkboxes/radios
checkbox: {
selector: '#agree',
read: 'checked',
write: 'checked'
},
// "text" - for text content
label: {
selector: '#label',
read: 'text',
write: 'text'
},
// "attr:name" - for attributes
sortDir: {
selector: '[data-sort]',
read: 'attr:data-sort-dir',
write: 'attr:data-sort-dir'
},
// "data:name" - for dataset properties
userId: {
selector: '#user',
read: 'data:userId',
write: 'data:userId'
}
};
// HTML:
//
//
// Welcome
//
//
User Profile
const state = domx.collect(manifest);
// Output: {
// textInput: "hello",
// checkbox: true,
// label: "Welcome",
// sortDir: "asc",
// userId: "123"
// }
```
--------------------------------
### htmx Extension Integration
Source: https://context7.com/adamzwasserman/domx/llms.txt
Demonstrates how DOMX can be integrated as an htmx extension to automatically manage state collection, caching, and AJAX requests.
```APIDOC
## DOMX HTMX Extension
### Description
This section details the integration of DOMX with HTMX, enabling automatic state management for HTMX requests. It allows for state to be included in POST parameters and enables caching and automatic replay capabilities.
### Method
N/A (HTMX attributes and events)
### Endpoint
N/A (Configuration via HTML attributes)
### Parameters
HTML Attributes for `` or other elements:
- **`hx-ext="domx"`**: Enables the DOMX extension for HTMX.
- **`dx-manifest="manifestName"`**: Specifies the name of the JavaScript variable holding the DOMX manifest to use.
- **`dx-cache="true"`**: Enables localStorage caching for requests initiated through this element. The cached state will be automatically replayed on page refresh.
HTMX Events:
- **`dx:change`**: A custom event fired by DOMX when observed state changes.
### Request Example
```html
```
### Response
N/A (HTMX handles responses based on `hx-target` and other attributes)
### Notes
- When `dx-cache="true"` is set, DOMX automatically handles caching the request state and replaying it on subsequent page loads.
- The `dx:change` event allows triggering HTMX requests based on changes in the observed DOM state (e.g., typing in a search box).
- State collected by DOMX is automatically appended to the parameters of HTMX POST requests.
```
--------------------------------
### htmx Integration with domx Extension
Source: https://github.com/adamzwasserman/domx/blob/main/site/index.html
Shows how to integrate domx with htmx using the `domx` extension. This allows for automatic state collection from the DOM based on a specified manifest (`dx-manifest`) and caching of this state (`dx-cache`) for persistence across page refreshes, sending state with htmx requests.
```html
```
--------------------------------
### Replay Cached Request
Source: https://github.com/adamzwasserman/domx/blob/main/site/docs.html
The `replay` function attempts to re-send a previously cached request from `localStorage`. This is useful for recovering state after a page refresh. It returns `null` if no valid cache exists or if the cache has expired (default 5 minutes). Dependencies: `localStorage`, `fetch` API.
```javascript
// On page load
const response = await replay();
if (response?.ok) {
const html = await response.text();
container.innerHTML = html;
}
```
--------------------------------
### Collect State from DOM using Manifest
Source: https://github.com/adamzwasserman/domx/blob/main/README.md
This code snippet demonstrates how to use the `domx.collect()` function with a predefined manifest to read the current state from various DOM elements. The resulting state object contains the values extracted based on the manifest's read configurations.
```javascript
const state = domx.collect(manifest);
// → { username: "alice", rememberMe: true, theme: "dark" }
```
--------------------------------
### Replay Cached Request from localStorage
Source: https://context7.com/adamzwasserman/domx/llms.txt
Re-sends a previously cached request from localStorage, useful for restoring state after a page refresh. It returns null if no valid cache exists or if the cache has expired (default 5-minute TTL).
```javascript
// On page load (e.g., in DOMContentLoaded)
document.addEventListener('DOMContentLoaded', async () => {
const response = await domx.replay();
if (response && response.ok) {
const html = await response.text();
const container = document.getElementById('results-container');
container.innerHTML = html;
console.log('State restored from cache');
} else if (response === null) {
console.log('No cached state, showing default view');
} else {
console.error('Failed to restore state:', response.status);
}
});
// Cache format in localStorage (key: 'domx:lastRequest'):
// {
// "url": "/api/search",
// "state": {"searchQuery": "javascript", "sortDir": "desc"},
// "ts": 1704067200000
// }
```
--------------------------------
### Apply State to DOM Elements with Manifest (JavaScript)
Source: https://context7.com/adamzwasserman/domx/llms.txt
Writes state values to DOM elements based on a manifest. It only processes manifest entries that include a `write` key, allowing for selective updates. This function is ideal for populating forms or updating attributes based on application state.
```javascript
const manifest = {
username: { selector: '#username', read: 'value', write: 'value' },
theme: { selector: '[data-theme]', read: 'data:theme', write: 'data:theme' },
rememberMe: { selector: '#remember', read: 'checked', write: 'checked' }
};
// HTML before:
//
//
//
```
--------------------------------
### HTMX Trigger for DOMX Changes
Source: https://github.com/adamzwasserman/domx/blob/main/site/docs.html
Demonstrates using the `dx:change` event, fired by DOMX when observed state changes, as a trigger for HTMX requests. This allows for automatic updates or submissions based on DOM state modifications. Dependencies: DOMX, HTMX.
```html
```
--------------------------------
### Define and Collect DOM State with Manifest
Source: https://github.com/adamzwasserman/domx/blob/main/README.md
This snippet demonstrates how to define a manifest object that maps state labels to DOM selectors and read methods. It then uses `domx.collect()` to read the current state from the specified DOM elements based on the manifest. The collected state is returned as a JavaScript object.
```javascript
const manifest = {
searchQuery: { selector: '#search', read: 'value' },
sortDir: { selector: '[data-sort]', read: 'attr:data-sort-dir' },
filters: { selector: '.filter.active', read: 'data:filter' }
};
// Collect state from DOM
const state = domx.collect(manifest);
// → { searchQuery: "hello", sortDir: "asc", filters: ["status", "priority"] }
```
--------------------------------
### domx on API
Source: https://context7.com/adamzwasserman/domx/llms.txt
Low-level subscription to raw MutationRecords for framework integration or advanced use cases. Returns an unsubscribe function.
```APIDOC
## domx.on(callback)
### Description
Low-level subscription to raw MutationRecords for framework integration or advanced use cases. Returns an unsubscribe function.
### Method
`on`
### Parameters
#### Path Parameters
None
#### Query Parameters
None
#### Request Body
- **callback** (function) - Required - A function that will be called with an array of MutationRecords whenever a DOM mutation occurs.
- **mutations** (array) - An array of MutationRecord objects.
### Request Example
```javascript
domx.on((mutations) => {
for (const mutation of mutations) {
console.log('Mutation type:', mutation.type);
console.log('Target:', mutation.target);
}
});
```
### Response
#### Success Response (function)
- **unsubscribe** (function) - A function that, when called, stops observing DOM mutations.
#### Response Example
```javascript
const unsubscribe = domx.on((mutations) => {
console.log('Mutations detected:', mutations);
});
// To stop observing:
unsubscribe();
```
```
--------------------------------
### Subscribe to Raw DOM Mutations (JavaScript)
Source: https://context7.com/adamzwasserman/domx/llms.txt
Provides a low-level subscription to raw MutationRecords emitted by a MutationObserver. This is intended for framework integration or advanced use cases where direct access to mutation details is required. It returns an unsubscribe function to stop listening for mutations.
```javascript
// Monitor all DOM mutations
const unsubscribe = domx.on((mutations) => {
for (const mutation of mutations) {
console.log('Mutation type:', mutation.type);
console.log('Target:', mutation.target);
if (mutation.type === 'childList') {
console.log('Added nodes:', mutation.addedNodes);
console.log('Removed nodes:', mutation.removedNodes);
}
}
});
// Mutations are tracked automatically
document.body.appendChild(document.createElement('div'));
// Console output: Mutation type: childList, Added nodes: [div]
// Cleanup
unsubscribe();
```
--------------------------------
### Send DOM State and Cache to localStorage
Source: https://context7.com/adamzwasserman/domx/llms.txt
Collects state from DOM elements based on a manifest, caches it to localStorage, and sends it via a POST request. Useful for forms and search interfaces requiring persistence across refreshes. Handles network requests and response processing.
```javascript
const manifest = {
searchQuery: { selector: '#search', read: 'value' },
sortDir: { selector: '[data-sort]', read: 'attr:data-sort-dir' },
page: { selector: '[data-page]', read: 'data:page' }
};
// HTML:
//
//
//
Results
try {
const response = await domx.send('/api/search', manifest, {
headers: {
'X-Custom-Header': 'value',
'Authorization': 'Bearer token123'
}
});
if (response.ok) {
const html = await response.text();
document.getElementById('results').innerHTML = html;
} else {
console.error('Search failed:', response.status);
}
} catch (error) {
console.error('Network error:', error);
}
// POST body sent: {"searchQuery":"javascript","sortDir":"desc","page":"2"}
// localStorage cached: {"url":"/api/search","state":{...},"ts":1704067200000}
```
--------------------------------
### domx observe API
Source: https://context7.com/adamzwasserman/domx/llms.txt
Watches DOM for changes and invokes callback with full state. Automatically detects appropriate watch mechanism based on read type. Returns an unsubscribe function.
```APIDOC
## domx.observe(manifest, callback)
### Description
Watches DOM for changes and invokes callback with full state. Automatically detects appropriate watch mechanism (input events, change events, or MutationObserver) based on read type. Returns an unsubscribe function.
### Method
`observe`
### Parameters
#### Path Parameters
None
#### Query Parameters
None
#### Request Body
- **manifest** (object) - Required - An object mapping labels to DOM selectors and read methods.
- **[label]** (object) - Required - Configuration for a state property.
- **selector** (string) - Required - CSS selector for the DOM element.
- **read** (string) - Required - The method or attribute to read from the element.
- **callback** (function) - Required - A function that will be called with the updated state whenever a change is detected.
- **state** (object) - The current state object derived from the manifest.
### Request Example
```json
{
"manifest": {
"searchQuery": { "selector": "#search", "read": "value" },
"filters": { "selector": ".filter.active", "read": "data:filter" }
}
}
```
### Response
#### Success Response (function)
- **unsubscribe** (function) - A function that, when called, stops observing DOM changes.
#### Response Example
```javascript
const unsubscribe = domx.observe(manifest, (state) => {
console.log('State changed:', state);
});
// To stop observing:
unsubscribe();
```
```
--------------------------------
### domx collect API
Source: https://context7.com/adamzwasserman/domx/llms.txt
Reads current DOM state based on a manifest definition and returns an object with state values.
```APIDOC
## domx.collect(manifest)
### Description
Reads current DOM state based on a manifest definition and returns an object with state values.
### Method
`collect`
### Parameters
#### Path Parameters
None
#### Query Parameters
None
#### Request Body
- **manifest** (object) - Required - An object mapping labels to DOM selectors and read methods.
- **[label]** (object) - Required - Configuration for a state property.
- **selector** (string) - Required - CSS selector for the DOM element.
- **read** (string) - Required - The method or attribute to read from the element (e.g., 'value', 'checked', 'attr:data-sort-dir', 'text').
### Request Example
```json
{
"manifest": {
"searchQuery": { "selector": "#search", "read": "value" },
"isActive": { "selector": "#toggle", "read": "checked" },
"sortDir": { "selector": "[data-sort]", "read": "attr:data-sort-dir" },
"tags": { "selector": ".tag", "read": "text" }
}
}
```
### Response
#### Success Response (object)
- **state** (object) - An object containing the collected state values.
#### Response Example
```json
{
"searchQuery": "hello",
"isActive": true,
"sortDir": "asc",
"tags": ["JavaScript", "Python"]
}
```
```
--------------------------------
### Observe DOM Changes and State Updates (JavaScript)
Source: https://context7.com/adamzwasserman/domx/llms.txt
Watches the DOM for changes and invokes a callback function with the full current state whenever a change is detected. It automatically determines the best way to watch for changes (e.g., input events, MutationObserver) based on the read type defined in the manifest. It returns an unsubscribe function to stop observing.
```javascript
const manifest = {
searchQuery: { selector: '#search', read: 'value' },
filters: { selector: '.filter.active', read: 'data:filter' }
};
// HTML:
//
//
const unsubscribe = domx.observe(manifest, (state) => {
console.log('State changed:', state);
// Trigger UI updates, API calls, etc.
if (state.searchQuery.length > 2) {
// Perform search
}
});
// User types in search field
// Console output: State changed: { searchQuery: "abc", filters: ["status"] }
// Later: stop observing
unsubscribe();
```
--------------------------------
### HTMX Extension for Automatic DOMX Integration
Source: https://context7.com/adamzwasserman/domx/llms.txt
Integrates DOMX with HTMX, enabling automatic state collection and caching for HTMX requests. This extension allows DOM state to be automatically included in POST parameters and enables localStorage caching and auto-replay on page refreshes.
```html
```
--------------------------------
### Replay Cached Requests on Page Refresh
Source: https://github.com/adamzwasserman/domx/blob/main/README.md
domx helps maintain application state across page refreshes by caching requests before they are sent. The `replay()` method can be called on page load to re-send the cached request and restore the previous state.
```javascript
document.addEventListener('DOMContentLoaded', async () => {
const response = await domx.replay();
if (response?.ok) {
const html = await response.text();
document.getElementById('container').innerHTML = html;
}
});
```
--------------------------------
### Collect DOM State with Custom Functions
Source: https://github.com/adamzwasserman/domx/blob/main/site/docs.html
The `collect` function reads the current DOM state based on a provided manifest. It returns an object where keys correspond to the labels defined in the manifest. If a selector matches multiple elements, an array of values is returned. Dependencies: None explicitly mentioned, assumes DOM environment.
```javascript
const manifest = {
combined: {
selector: '#thing',
read: (el) => `${el.dataset.foo}-${el.dataset.bar}`,
write: (el, val) => {
const [foo, bar] = val.split('-');
el.dataset.foo = foo;
el.dataset.bar = bar;
}
}
};
const state = collect(manifest);
// { searchQuery: "hello", sortDir: "asc" }
```
```javascript
const manifest = {
tags: { selector: '.tag', read: 'text' }
};
collect(manifest);
// { tags: ["JavaScript", "TypeScript", "Python"] }
```
--------------------------------
### Observe DOM Changes with Custom Functions
Source: https://github.com/adamzwasserman/domx/blob/main/site/docs.html
The `observe` function watches the DOM for changes and invokes a callback with the complete state whenever changes are detected. It automatically determines the appropriate watching mechanism based on the `read` type in the manifest. Returns a function to unsubscribe from observations. Dependencies: DOM environment, MutationObserver or event listeners.
```javascript
const unsubscribe = observe(manifest, (state) => {
console.log('State changed:', state);
});
// Later: stop observing
unsubscribe();
```
--------------------------------
### Custom Read/Write Functions for DOM State
Source: https://context7.com/adamzwasserman/domx/llms.txt
Supports custom extractor (read) and writer functions for complex state transformations on DOM elements. This allows for dynamic manipulation and extraction of data beyond simple attribute or value reads.
```javascript
const manifest = {
// Combine multiple data attributes
coordinates: {
selector: '#location',
read: (el) => `${el.dataset.lat},${el.dataset.lng}`,
write: (el, val) => {
const [lat, lng] = val.split(',');
el.dataset.lat = lat;
el.dataset.lng = lng;
}
},
// Extract computed styles
visibility: {
selector: '#panel',
read: (el) => window.getComputedStyle(el).display !== 'none',
write: (el, visible) => {
el.style.display = visible ? 'block' : 'none';
}
}
};
// HTML:
//
NYC
//
Content
const state = domx.collect(manifest);
// Output: { coordinates: "40.7128,-74.0060", visibility: false }
domx.apply(manifest, { coordinates: "34.0522,-118.2437", visibility: true });
// Updates location to LA coordinates and shows panel
```
--------------------------------
### Define Manifest for DOM State Mapping
Source: https://github.com/adamzwasserman/domx/blob/main/site/index.html
Defines a JavaScript object that maps state labels to specific DOM elements and their properties or attributes. This manifest serves as the configuration for domx functions to read from and write to the DOM. It supports reading values, attributes, and data attributes.
```javascript
const manifest = {
searchQuery: { selector: '#search', read: 'value', write: 'value' },
sortDir: { selector: '[data-sort]', read: 'attr:data-sort-dir' },
filters: { selector: '.filter.active', read: 'data:filter' }
};
```
--------------------------------
### Include htmx integration via CDN
Source: https://github.com/adamzwasserman/domx/blob/main/site/docs.html
Include the htmx integration script for domx via CDN. This version provides specific functionality for working with htmx in your project.
```html
```
--------------------------------
### clearCache()
Source: https://context7.com/adamzwasserman/domx/llms.txt
Removes the cached request from localStorage. This is useful for logout flows or manual cache invalidation.
```APIDOC
## DELETE /api/cache
### Description
Clears the cached request data stored in localStorage. This action is typically performed during logout or when the cache needs to be manually invalidated.
### Method
DELETE
### Endpoint
`/api/cache`
### Parameters
None
### Request Example
```javascript
// Clear cache on logout
document.getElementById('logout-btn').addEventListener('click', () => {
domx.clearCache();
localStorage.removeItem('authToken');
window.location.href = '/login';
});
// Clear cache after successful form submission
const form = document.getElementById('search-form');
form.addEventListener('submit', async (e) => {
e.preventDefault();
const response = await domx.send('/api/search', manifest);
if (response.ok) {
domx.clearCache(); // Clear old cache after successful new search
}
});
```
### Response
#### Success Response (200)
Indicates that the cache has been successfully cleared.
#### Response Example
N/A (This is a client-side operation)
### Notes
- This function specifically targets the cache entry managed by DOMX, typically stored under a key like 'domx:lastRequest'.
```
--------------------------------
### Apply State to DOM with Custom Functions
Source: https://github.com/adamzwasserman/domx/blob/main/site/docs.html
The `apply` function writes state values back to the DOM. It selectively processes manifest entries that include a `write` function. Inputs: manifest object, state object. Outputs: Modifies the DOM.
```javascript
apply(manifest, { username: "alice", theme: "dark" });
```
--------------------------------
### Collect Multiple DOM Elements as an Array
Source: https://github.com/adamzwasserman/domx/blob/main/README.md
When a selector matches multiple elements, the `collect()` method in domx returns an array containing the read values from each matched element. This is useful for gathering data from lists of items.
```javascript
const manifest = {
tags: { selector: '.tag', read: 'text' }
};
const state = domx.collect(manifest);
// → { tags: ["JavaScript", "TypeScript", "Python"] }
```
--------------------------------
### Clear Cached Request with clearCache() API
Source: https://github.com/adamzwasserman/domx/blob/main/README.md
This code snippet shows the direct API usage of `domx.clearCache()`. This function is used to remove any previously cached request data, effectively clearing the cache used by `domx.send()` and `domx.replay()`.
```javascript
domx.clearCache();
```
--------------------------------
### htmx Integration with domx
Source: https://github.com/adamzwasserman/domx/blob/main/README.md
domx offers an htmx extension to seamlessly integrate DOM state collection into htmx requests. It automatically adds collected state to request parameters and supports caching and event triggering.
```html
```
--------------------------------
### Clear LocalStorage Cache
Source: https://github.com/adamzwasserman/domx/blob/main/site/docs.html
The `clearCache` function removes the cached request data stored in `localStorage`. This action is typically used to invalidate previously stored state. Dependencies: `localStorage`.
```javascript
clearCache();
```
--------------------------------
### Clear Cached Request from localStorage
Source: https://context7.com/adamzwasserman/domx/llms.txt
Removes the cached request from localStorage, which is useful for logout flows or manual cache invalidation. This ensures that stale data is not used.
```javascript
// Clear cache on logout
document.getElementById('logout-btn').addEventListener('click', () => {
domx.clearCache();
localStorage.removeItem('authToken');
window.location.href = '/login';
});
// Clear cache on successful form submission
const form = document.getElementById('search-form');
form.addEventListener('submit', async (e) => {
e.preventDefault();
const response = await domx.send('/api/search', manifest);
if (response.ok) {
domx.clearCache(); // Clear old cache after successful new search
}
});
```
=== COMPLETE CONTENT === This response contains all available snippets from this library. No additional content exists. Do not make further requests.