The real DOM diffing.
deno.land:
import * as mod from "https://deno.land/x/dom_diff/mod.ts";
npm:
npm i dom-diff
Performs markup and event listener diff detection and application, which is often done in virtual-dom.
import {
Differ,
EventListenerReconciler,
MarkupReconciler,
setupEventListener,
} from "https://deno.land/dom_diff/mod.ts";
setupEventListener();
declare const oldNode: Node;
declare const newNode: Node;
const differ = new Differ(
new MarkupReconciler(),
new EventListenerReconciler()
);
differ.apply(oldNode, newNode);
The oldNode
is updated by calculating the difference from the newNode
.
Note Normally, event listeners cannot be referenced, so
addEventListener
andremoveEventListener
are replaced to proxies bysetupEventListener
.
Reconciler is a structure that encapsulates difference detection and difference application. This allows modularization of difference application.
For example, to perform event handler difference detection, use the EventHandlerReconciler
.
import { EventHandlerReconciler } from "https://deno.land/dom_diff/mod.ts";
const reconciler = new EventHandlerReconciler(["click", "blur", "mouseenter"]);
Event handlers cannot be enumerated, so you must specify the name of the event to be monitored.
Various reconciler are provided.
The built-in behavior abstracts the difference detection for children
.
It compares each node type and detects movements, additions, deletions, and substitutions.
For example, the following DOM:
Old | New |
|
|
The following is the result of differential application:
import { Differ } from "https://deno.land/dom_diff/mod.ts";
declare const oldNode: Node;
declare const newNode: Node;
new Differ().apply(oldNode, newNode);
Patched Old | New |
|
|
This result is a good representation of the default behavior.
The built-in behavior is concerned with the ordering of the Nodes.
First, each node is converted to a comparable value. This is called keying.
Then, it detects differences in the order of the keys.
All reconciler are executed after this.
This abstraction allows reconciler to focus only on top-level difference detection.
By default, nodeName
is used as the key.
This can be changed as follows:
import { Differ } from "https://deno.land/dom_diff/mod.ts";
declare const oldNode: Node;
declare const newNode: Node;
new Differ().apply(oldNode, newNode, {
keying: (node) => {
if (node instanceof Element && node.hasAttribute("data-key")) {
return node.getAttribute("data-key")!;
}
return node.nodeName;
},
});
In this example, the data-key
attribute is used as the key.
See keying for details.
See deno doc for all APIs.
See contributing.
MIT © 2023 Tomoki Miyauchi