yjs / yjs-demos

A collection of demos for Yjs
https://demos.yjs.dev
The Unlicense
729 stars 120 forks source link

Issue related to rendering snapshot version changes from database #60

Open kkpal610 opened 10 months ago

kkpal610 commented 10 months ago

I am reaching out regarding an implementation challenge I am facing while integrating ProseMirror version history using the Yjs-demo code available here (https://github.com/yjs/yjs-demos/tree/main/prosemirror-versions).

To provide some context, I am storing base64-encoded snapshots on the server. When attempting to retrieve and decode these snapshots upon a page refresh, I encounter an issue – the ProseMirror editor does not render the expected diff changes. Strangely, I can observe the snapshot version changes successfully when staying on the page without a refresh.

I am seeking your expertise to identify and address what might be going wrong in this scenario. Specifically, I have ensured the proper initialization of both the Y.Doc and ProseMirror editor to match the state of the snapshot. Additionally, the initial state of the ProseMirror editor is set correctly.

If you could spare a moment to review the provided information and offer insights into potential solutions or debugging approaches, it would be greatly appreciated.

@dmonad Appreciate your help

Implentation Code:

const versions = ydoc.getArray('versions')

 const addSnapshotToDatbase = doc => {
    const snapshot = Y.snapshot(doc)
    const encodedSnapshot = Y.encodeSnapshot(snapshot)
    // encode the snapshot and store in db
    const binaryString = String.fromCharCode(...encodedSnapshot);
    const base64Encoded = btoa(binaryString);

    // code to send the base64Encoded string to database  and store on server
}

const getSnapshotsFromDatabase = () => {
    const versionBlobFromDatabase = "SGVsbG8sIFdvcmxkIQ==";
    // decode encoded string
    const decodedString = atob(versionBlobFromDatabase);
    const decodedArray = new Uint8Array(decodedString.length);
    for (let i = 0; i < decodedString.length; i++) {
        decodedArray[i] = decodedString.charCodeAt(i);
    }

    renderVersion(editorview, decodedArray, null)
}

const renderVersion = (editorview, snapshotversion, prevSnapshot) => {
    editorview.dispatch(
        editorview.state.tr.setMeta(
            ySyncPluginKey,
            { 
                snapshot: Y.decodeSnapshot(snapshotversion),
                prevSnapshot: prevSnapshot == null ? Y.emptySnapshot : Y.decodeSnapshot(prevSnapshot)
            }
        )
    )
  }

<button onclick="addSnapshotToDatbase(ydoc)">Capture Snapshot</button>

<button onclick="addSnapshotToDatbase(ydoc)">View Snapshot Diff</button>