diff-dom-streaming
TypeScript icon, indicating that this package has built-in type declarations

0.3.0 • Public • Published

Diff DOM Streaming

npm version npm size PRs Welcome follow on Twitter

The Diff DOM (Document Object Model) algorithm is used to compare two versions of the DOM, such as before and after an update on a web page. It aims to efficiently identify the changes between both DOMs, minimizing the number of manipulations required to update the user interface.

The Diff DOM Streaming library extends the traditional Diff DOM algorithm by introducing support for comparing a DOM node with a streaming reader. This enables the library to process the changes incrementally as they occur during the diff process.

For more info, read this post.

Getting started

NPM

Install:

bun install diff-dom-streaming

Then import it:

import diff from "diff-dom-streaming";

JSR

Install:

bunx jsr add @aralroca/diff-dom-streaming

Then import it:

import diff from "@aralroca/diff-dom-streaming";

UNPKG

Just import it:

import diff from "https://unpkg.com/diff-dom-streaming@latest";

Using it

const res = await fetch(/* some url */);

// Diff between the current document and the reader:
await diff(document, res.body.getReader());

API

diff(oldNode: Node, reader: ReadableStreamDefaultReader, options?: Options)

This function performs a diffing operation between the oldNode and the DOM tree streamed through reader. It applies the necessary changes to update the oldNode accordingly. An optional options that include:

type Options = {
  // calback to handle each new docoument node during the streaming
  // (default: undefined)
  onNextNode?: NextNodeCallback;
  // update the DOM using document.startViewTransition (default: false)
  transition?: boolean;
};

Lists and key attribute

Keys help to identify which items have changed, are added, or are removed. Keys should be given to the elements inside the array to give the elements a stable identity:

const numbers = [1, 2, 3, 4, 5];
const listItems = numbers.map((number) => (
  <li key={number.toString()}>{number}</li>
));

(Example with JSX)

The diff-dom-streaming library takes into account the key attribute for these cases, if it does not exist, then see if they have id.

Examples

In the repo we have examples for you to try.

Locally

  1. Clone this repository
  2. Run bun run example

Stackblitz

You can run the boxes demo with Vanillajs here.

ezgif-4-1ff18912f4

Acknowledgments

The Diff DOM Algorithm with HTML Streaming is inspired by the set-dom library by @dylan_piercey and a technique for parsing streams pioneered by @jaffathecake.

Contributing

See Contributing Guide and please follow our Code of Conduct.

License

MIT

Package Sidebar

Install

npm i diff-dom-streaming

Weekly Downloads

211

Version

0.3.0

License

MIT

Unpacked Size

9.73 kB

Total Files

5

Last publish

Collaborators

  • aralroca