The patch function is used to apply incremental updates to the DOM based on a patch object. It supports several action types to create, remove, replace, or update nodes and their attributes.
Parameters:
parent: The parent Node of the element being patched.PATCH: An object describing the change. It must contain a type property.child (optional): The specific Node to be patched if the operation is not targeting the parent directly.
Supported Action Types:
ACTION_CREATE: Appends a new node (provided in PATCH.node) to the parent.ACTION_REMOVE: Removes the target element from the parent.ACTION_REPLACE: Replaces the target element with a new node (from PATCH.node). If PATCH.value is a string, it updates the nodeValue of the element instead.ACTION_UPDATE: Performs a complex update on an element. It applies attribute changes (from PATCH.attributes) and recursively calls patch for each child in PATCH.children.
import { patch } from './patch';
import { ACTION_CREATE, ACTION_UPDATE } from './consts';
// Example: Creating a new element
const createPatch = {
type: ACTION_CREATE,
node: document.createElement('div')
};
await patch(document.body, createPatch);
// Example: Updating an existing element's attributes and children
const updatePatch = {
type: ACTION_UPDATE,
attributes: [{ type: 'SET_ATTR', name: 'class', value: 'container' }],
children: [
{ type: 'CREATE', node: document.createTextNode('Hello World') }
]
};
await patch(existingElement, updatePatch);