### Element Persistence Example with data-persist Source: https://context7.com/natemoo-re/micromorph/llms.txt Demonstrates how to use the `data-persist` attribute in HTML to keep elements like navigation or audio players intact across SPA page transitions. ```html

Page Title

Page content...

``` -------------------------------- ### Update Document from String with Micromorph Source: https://github.com/natemoo-re/micromorph/blob/main/README.md This example demonstrates updating the current document to match content parsed from an HTML string. It utilizes the DOMParser API and Micromorph's diffing capabilities to avoid FOUC. ```javascript import diff from 'micromorph'; const p = new DOMParser(); const newDoc = p.parseFromString(`

Hello world!

`, 'text/html'); diff(document, newDoc); ``` -------------------------------- ### Enable SPA Navigation with View Transitions Source: https://context7.com/natemoo-re/micromorph/llms.txt Initialize SPA navigation using the listen function and apply CSS for root or element-specific transitions. ```javascript import listen from 'micromorph/spa'; // Enable SPA navigation with automatic View Transitions listen(); // CSS for View Transitions (add to your stylesheet) /* ::view-transition-old(root) { animation: fade-out 0.2s ease-out; } ::view-transition-new(root) { animation: fade-in 0.2s ease-in; } @keyframes fade-out { from { opacity: 1; } to { opacity: 0; } } @keyframes fade-in { from { opacity: 0; } to { opacity: 1; } } */ // For element-specific transitions, use view-transition-name: /* .hero-image { view-transition-name: hero; } ::view-transition-old(hero), ::view-transition-new(hero) { animation-duration: 0.4s; } */ ``` -------------------------------- ### Enable SPA Navigation with Micromorph (/spa) Source: https://github.com/natemoo-re/micromorph/blob/main/README.md Use this alternative listener for browsers that do not support the Navigation API, enabling SPA-like behavior. It requires importing from 'micromorph/spa'. ```javascript import listen from 'micromorph/spa'; listen(); ``` -------------------------------- ### Basic SPA Navigation with micromorph/nav Source: https://context7.com/natemoo-re/micromorph/llms.txt Converts all local links to SPA navigation using the Navigation API. No configuration is needed for basic usage. ```javascript import listen from 'micromorph/nav'; // Basic usage - converts all local links to SPA navigation const router = listen(); ``` -------------------------------- ### Enable SPA Navigation with Micromorph (/nav) Source: https://github.com/natemoo-re/micromorph/blob/main/README.md Integrate this listener to transform a Multi-Page Application (MPA) into a Single-Page Application (SPA) using the Navigation API. Micromorph will only re-render changed content. ```javascript import listen from 'micromorph/nav'; listen(); ``` -------------------------------- ### Configurable SPA Navigation with micromorph/spa Source: https://context7.com/natemoo-re/micromorph/llms.txt Offers full configuration for SPA navigation using the History API, including beforeDiff, afterDiff, include selectors, and programmatic navigation. Supports scrollToTop option and element persistence. ```javascript import listen from 'micromorph/spa'; // Full configuration example const router = listen({ beforeDiff: async (newDocument) => { // Pre-process the new document // Useful for removing elements that shouldn't be diffed const alerts = newDocument.querySelectorAll('.alert'); alerts.forEach(alert => alert.remove()); }, afterDiff: async () => { // Post-navigation cleanup and initialization document.querySelectorAll('pre code').forEach(el => { hljs.highlightElement(el); }); }, // Only handle links within the main content area include: '#content a[href^="/"]', // Alternative: function-based filtering // include: (anchor) => { // return anchor.closest('nav') !== null; // }, scrollToTop: true // Default behavior }); // Programmatic navigation await router.go('/dashboard', { scrollToTop: false }); router.back(); router.forward(); // Persisting elements across navigation: // Add data-persist attribute to elements that shouldn't be replaced //
Audio player that keeps playing
``` -------------------------------- ### Configurable SPA Navigation with micromorph/nav Source: https://context7.com/natemoo-re/micromorph/llms.txt Customizes SPA navigation behavior using options like beforeDiff, afterDiff, and include selectors. Supports programmatic navigation and HTML attributes for control. ```javascript import listen from 'micromorph/nav'; // With configuration options const router = listen({ // Hook called before DOM diffing (async supported) beforeDiff: async (newDocument) => { console.log('About to update to:', newDocument.title); // Modify newDocument if needed before applying const scripts = newDocument.querySelectorAll('script[data-remove]'); scripts.forEach(s => s.remove()); }, // Hook called after DOM diffing completes afterDiff: async () => { console.log('Navigation complete'); // Re-initialize components, analytics, etc. window.analytics?.page(); }, // Control which links trigger SPA navigation include: 'a:not([data-external])', // CSS selector // OR use a function: // include: (anchor) => !anchor.href.includes('/api/'), // Disable automatic scroll-to-top scrollToTop: false }); // Programmatic navigation via returned Router instance router.go('/about'); // Navigate to path router.back(); // Go back in history router.forward(); // Go forward in history // HTML attributes for link-level control: // External Link - Skip SPA routing // No Scroll - Don't scroll to top ``` -------------------------------- ### Basic SPA Navigation with micromorph/spa Source: https://context7.com/natemoo-re/micromorph/llms.txt Provides SPA functionality using the History API for browsers without Navigation API support. Intercepts clicks on local links for basic SPA behavior. ```javascript import listen from 'micromorph/spa'; // Basic usage - intercepts clicks on local links const router = listen(); ``` -------------------------------- ### Element Persistence in micromorph/spa Configuration Source: https://context7.com/natemoo-re/micromorph/llms.txt Shows how micromorph/spa handles elements with the `data-persist` attribute during its `beforeDiff` and `afterDiff` hooks, ensuring they remain in the DOM. ```javascript import listen from 'micromorph/spa'; listen({ beforeDiff: (newDoc) => { // Persisted elements in newDoc are automatically handled // The original persisted elements are retained in the DOM }, afterDiff: () => { // After navigation, persisted elements are still there const player = document.getElementById('audio-player'); console.log(player.querySelector('audio').paused); // false - still playing } }); ``` -------------------------------- ### Low-Level API: patch() Source: https://context7.com/natemoo-re/micromorph/llms.txt The `patch()` function applies a patch object to a DOM node. It executes the changes computed by `diff()`, handling node creation, removal, replacement, and attribute updates. Returns a Promise. ```APIDOC ## Low-Level API: patch() ### Description Applies a patch object to a DOM node, executing the changes computed by `diff()`. ### Method `patch(node: Node, patches: PatchObject): Promise` ### Parameters - **node** (Node) - The DOM node to apply the patches to. - **patches** (PatchObject) - The patch object generated by the `diff()` function. ### Request Example ```javascript import { diff, patch } from 'micromorph'; const container = document.getElementById('app'); const originalContent = container.cloneNode(true); const parser = new DOMParser(); const newContent = parser.parseFromString( '

Updated

', 'text/html' ).getElementById('app'); const patches = diff(container, newContent); if (patches && patches.type !== undefined) { await patch(container, patches); console.log('DOM updated successfully'); } ``` ### Response #### Success Response (Promise resolves) - The `node` is updated according to the `patches`. ### Response Example (No explicit return value, DOM is mutated in place) ``` -------------------------------- ### Core API: Default Export (micromorph) Source: https://context7.com/natemoo-re/micromorph/llms.txt The main `micromorph` function performs a complete diff and patch operation between two DOM nodes. It accepts any Node types and efficiently syncs the first node to match the second. Returns a Promise that resolves when all patching is complete. ```APIDOC ## Default Export / micromorph ### Description Performs a complete diff and patch operation between two DOM nodes. ### Method `diff(fromNode: Node, toNode: Node): Promise` ### Parameters - **fromNode** (Node) - The source DOM node. - **toNode** (Node) - The target DOM node to sync with. ### Request Example ```javascript import diff from 'micromorph'; const fromNode = document.getElementById('content'); const toNode = document.createElement('div'); toNode.innerHTML = '

Updated Content

New paragraph

'; await diff(fromNode, toNode); ``` ### Response #### Success Response (Promise resolves) - The `fromNode` is updated to match `toNode`. ### Response Example (No explicit return value, DOM is mutated in place) ``` -------------------------------- ### Diff Two DOM Nodes with Micromorph Source: https://github.com/natemoo-re/micromorph/blob/main/README.md Use this snippet to efficiently compare two DOM nodes and synchronize any differences. Ensure 'micromorph' is imported. ```javascript import diff from 'micromorph'; diff(fromNode, toNode); ``` -------------------------------- ### Perform DOM Diff and Patch with Micromorph Source: https://context7.com/natemoo-re/micromorph/llms.txt Use the default export to synchronize a DOM node with a target structure. This is suitable for basic element updates or full document synchronization when combined with DOMParser. ```javascript import diff from 'micromorph'; // Basic element diffing const fromNode = document.getElementById('content'); const toNode = document.createElement('div'); toNode.innerHTML = '

Updated Content

New paragraph

'; await diff(fromNode, toNode); // fromNode is now updated to match toNode's structure // Full document diffing with DOMParser const parser = new DOMParser(); const newHtml = ` New Page Title

Hello World!

This content will be efficiently merged.

`; const newDoc = parser.parseFromString(newHtml, 'text/html'); // Diff entire document - handles head/body intelligently to avoid FOUC await diff(document, newDoc); // Page is now updated with minimal DOM mutations ``` -------------------------------- ### Apply DOM Patches with Low-Level patch() Source: https://context7.com/natemoo-re/micromorph/llms.txt Use the `patch` function to apply a computed patch object to a target DOM node. This function handles the execution of DOM modifications and returns a Promise for asynchronous operations. ```javascript import { diff, patch } from 'micromorph'; const container = document.getElementById('app'); const originalContent = container.cloneNode(true); // Create new desired state const parser = new DOMParser(); const newContent = parser.parseFromString( '

Updated

  • Item 1
  • Item 2
', 'text/html' ).getElementById('app'); // Compute differences const patches = diff(container, newContent); // Apply patches with full control if (patches && patches.type !== undefined) { await patch(container, patches); console.log('DOM updated successfully'); } // Two-step process allows for: // - Logging/debugging changes before applying // - Conditional patching based on patch contents // - Custom pre/post processing ``` -------------------------------- ### Low-Level API: diff() Source: https://context7.com/natemoo-re/micromorph/llms.txt The `diff()` function computes the differences between two nodes without applying them. It returns a patch object describing the necessary changes. Useful for inspecting changes or custom patching. ```APIDOC ## Low-Level API: diff() ### Description Computes the differences between two nodes without applying them. Returns a patch object. ### Method `diff(fromNode: Node, toNode: Node): PatchObject | null` ### Parameters - **fromNode** (Node) - The source DOM node. - **toNode** (Node) - The target DOM node. ### Return Value - **PatchObject** - An object describing the changes needed. - **null** - If no changes are detected. ### Patch Object Structure Example ```json { "type": 3, // ACTION_UPDATE "attributes": [ { "type": 4, "name": "class", "value": "container active" } // ACTION_SET_ATTR ], "children": [ { "type": 3, "attributes": [], "children": [...] }, // Update span { "type": 0, "node": '; const patches = diff(oldElement, newElement); console.log(patches); ``` ``` -------------------------------- ### Compute DOM Differences with Low-Level diff() Source: https://context7.com/natemoo-re/micromorph/llms.txt Utilize the `diff` function to calculate the necessary changes between two DOM nodes without applying them. This returns a patch object detailing create, remove, replace, or update operations. ```javascript import { diff } from 'micromorph'; const oldElement = document.createElement('div'); oldElement.className = 'container'; oldElement.innerHTML = 'Old text'; const newElement = document.createElement('div'); newElement.className = 'container active'; newElement.innerHTML = 'New text'; const patches = diff(oldElement, newElement); console.log(patches); // Output structure: // { // type: 3, // ACTION_UPDATE // attributes: [ // { type: 4, name: 'class', value: 'container active' } // ACTION_SET_ATTR // ], // children: [ // { type: 3, attributes: [], children: [...] }, // Update span // { type: 0, node: