Live DOM Updates¶
domonic.diffdom can compare two rendered DOM trees and produce JSON-safe
patch data. That gives you a practical starting point for live HTML updates:
render on the server, diff against the previous tree, send only the changes.
Create a Patch¶
import json
from domonic.diffdom import DiffDOM
from domonic.html import button, div, h1, p
old = div(h1("Inbox"), p("0 messages"))
new = div(h1("Inbox"), p("1 message"), button("Open"))
dd = DiffDOM()
changes = dd.diff(old, new)
print(json.dumps(changes, indent=2))
# [
# {"action": "modifyTextElement", "route": [1, 0], "oldValue": "0 messages", "newValue": "1 message"},
# {"action": "addElement", "route": [2], "element": {"nodeName": "button", ...}}
# ]
Apply a Patch¶
dd.apply(old, changes)
assert str(old) == str(new)
Undo a Patch¶
dd.undo(old, changes)
print(old)
# <div><h1>Inbox</h1><p>0 messages</p></div>
WebSocket Shape¶
The server-side shape is intentionally plain.
import json
async def publish_dom_update(websocket, previous, current):
changes = DiffDOM().diff(previous, current)
await websocket.send(json.dumps(changes))
Browser Receiver¶
On the browser side you can apply the patch with a small JavaScript patcher that understands the same change data.
const socket = new WebSocket("ws://localhost:8765");
socket.addEventListener("message", event => {
const changes = JSON.parse(event.data);
applyPatches(document.body, changes);
});
See examples/sockets/diffdom_socket.py for a complete Python example.
Next Steps¶
diffdom for the full diff and patch API
Templates and Components for component rendering patterns
webapi for WebSocket, MessageChannel, BroadcastChannel, and Workers
Server-Side HTML for serving generated HTML
Examples Gallery for runnable socket and diff examples