DOM Diffing and Synchronization over Braid-HTTP
Note: Currently buggy! WIP.
Efficiently diff and synchronize a DOM, either locally or over the network via Braid-HTTP. Sync multiple browser & server DOMs over the network, via Dom Diffs. Collaboratively edit live HTML. Create mashups of UIs, interoperating via Dom Diffs.
- Supports Braid-HTTP 04 protocol
- Uses Tree-sitter for robust, incremental HTML parsing
- Implements DOM diffing algorithm over Tree-sitter
- Run it on server or client
- Developed as part of the braid.org project
This library makes it easy to add collaborative HTML editing to your web applications, allowing multiple users to edit the same DOM structure in real-time.
General Use on Server
Install in your project:
npm install @braidjs/dom-diff
Require the library, which adds the serve_dom_diff
request handler to the global namespace, and use it to handle HTTP requests:
require('@braidjs/dom-diff')
http_server.on("request", (req, res) => {
serve_dom_diff(req, res, (subscribe) => {
require("braid-text").get(req.url, {subscribe})
})
})
serve_dom_diff
first subscribes to an underlying textual resource using the provided callback. It then responds to the request with a Braid subscription using the simpleton
merge type for HTML, which sends replacement HTML for a given xpath
. When changes occur in the underlying textual resource, serve_dom_diff
calculates the relevant DOM changes and sends these patches to all subscribed clients.
Server API
serve_dom_diff(req, res, braid_text_cb, options)
req
: Incoming HTTP request object.res
: Outgoing HTTP response object.braid_text_cb
: Function called by serve_dom_diff
to subscribe to the underlying textual resource. It receives a callback function with parameters like ({ version, parents, body, patches })
to be called for each new Braid version.options
: (optional) An object containing additional options:
key
: (optional) ID of HTML resource to sync with. Defaults to req.url
.
- This method handles Braid-HTTP requests for collaborative DOM editing.
Client-side Usage
Include the library in your client-side JavaScript.
<script src="https://unpkg.com/@braidjs/dom-diff"></script>
Once included, you can use the DOM diffing functionality in your client-side code:
await init_dom_diff()
let dd = create_dom_diff(initialHtml)
let currentHtml = dd.get()
let diff = dd.patch(newHtml)
[{ range: `/*[1]/*[2:2]`, content: '<b>hi</b>' },
{ range: `/*[2:2]`, content: 'world' }]
apply_dom_diff(domElement, diff)
Client API
async init_dom_diff()
- Initializes the DOM diffing system, loading necessary dependencies.
create_dom_diff(html)
- Creates a new DOM diff object for the given
html
. - Returns an object with methods:
get()
: Returns the current HTML.patch(newHtml)
: Updates to the newHtml
and returns the DOM diff to get there.
apply_dom_diff(dom, diff)
- Applies a diff to the given DOM element.
dom
: The target DOM element to update.diff
: The diff object generated by patch()
.