I am using this code to save yDoc change to database:
ydoc.on('update', (update, origin) => {
try {
let snapshot: Y.Snapshot = Y.snapshot(ydoc);
let snap: Uint8Array = Y.encodeSnapshot(snapshot);
// https://discuss.yjs.dev/t/save-the-yjs-snapshot-to-database/2317
let snapBase64 = btoa(String.fromCharCode(...new Uint8Array(snap)));
let params: TexFileVersion = {
file_id: editorAttr.docId,
name: editorAttr.name,
project_id: editorAttr.projectId,
content: ytext.toString(),
action: 1,
snapshot: snapBase64
};
throttledFn(params);
} catch (e) {
console.log(e);
}
});
this function works fine, I can save the document snapshot to database. but now the update will trigger when open the yDoc no matter edit the document or not. What should I do to detect the document change, only trigger the save to database action when the document changed.
raine
February 24, 2024, 4:56pm
2
You could try loading the stored snapshot and using equalSnapshots
to compare it directly with the in-memory snapshot.
1 Like
I have tried like this, seems the snapshot will never been equal:
ydoc.on('update', (update, origin) => {
try {
let snapshot: Y.Snapshot = Y.snapshot(ydoc);
let snap: Uint8Array = Y.encodeSnapshot(snapshot);
// https://discuss.yjs.dev/t/save-the-yjs-snapshot-to-database/2317
let content = String.fromCharCode(...new Uint8Array(snap));
let snapBase64 = btoa(content);
let lastsnapshot = localStorage.getItem("lastsnapshot");
if(snapBase64 === lastsnapshot){
// never run into this
debugger
return;
}
if(lastsnapshot){
let cached = base64ToUint8Array(lastsnapshot);
const decoded = Y.decodeSnapshot(cached);
let equal = Y.equalSnapshots(decoded,snapshot);
if(equal){
// never run into this
debugger
return;
}
}
let editorText = ytext.toString();
let lasteditortext = localStorage.getItem("lasteditortext");
if(lasteditortext === editorText){
// will run into this
debugger
return;
}
let params: TexFileVersion = {
file_id: editorAttr.docId,
name: editorAttr.name,
project_id: editorAttr.projectId,
content: editorText,
action: 1,
snapshot: snapBase64
};
// https://discuss.yjs.dev/t/is-it-possible-to-detect-the-document-changed-or-not/2453
localStorage.setItem("lastsnapshot",snapBase64);
localStorage.setItem("lasteditortext",editorText);
throttledFn(params);
} catch (e) {
console.log(e);
}
});