Creating a document from file (initial document state)

Hi, I have been working on a collaborative code editor with multiple files. I want to be able to start the server and create a document for each file in the project, and populate each document with its files contents.

Basically, is there a way to create a document on the server, and set its content to an initial value? If not is there any other way to load the data into a document other than the client creating a new document and updating it? From what I see, you can only start from scratch with a blank document

Thank you in advance! And I just want to say that yjs is insanely awesome, and I really hope I can get it working for my use case.

1 Like

Are you using the y-websocket server? I have a little experience with that and might be able to help if so.

Yes, I am using y-websocket and tired to have it add the value on creation in y-we socket, but couldn’t get it to encode the string, I insert, and apply update.

That sounds like what I would have done. Is there a gist or code snippet you can share of what you did?

@canadaduane - inside of y-websocket inside setupWSConnection, i modified this block:

 const doc = map.setIfUndefined(docs, docName, () => {
    const doc = new WSSharedDoc(docName)
    doc.gc = gc
    if (persistence !== null) {
      persistence.bindState(docName, doc)
    }
    
    docs.set(docName, doc)
    const content = 'testing123';
    const ytext = new Y.Text();
    ytext.insert(0, content);
    const state = Y.encodeStateAsUpdate(ytext.doc);
    Y.applyUpdate(doc, state);
    return doc
  })

but i’ve tried different variations, and when I start the server it looks good, but now when i get the document from the client the sever errors out:

running on port 1234
/Users/tcubbedge/my-y-websockets-server/node_modules/yjs/dist/yjs.cjs:797
  writeClientsStructs(encoder, doc.store, targetStateVector);
                                   ^

TypeError: Cannot read property 'store' of null
    at writeStateAsUpdate (/Users/tcubbedge/my-y-websockets-server/node_modules/yjs/dist/yjs.cjs:797:36)
const ytext = new Y.Text();
ytext.insert(0, content);

The ytext type is never attached to the document.

Try this:

const ytext = doc.getText('my-text-type')
ytext.insert(0, content);

And then get the same text type on the client-side. Please also carefully read the Yjs documentation and play with the demos. This might help you to understand how the shared types work.

1 Like

It doesn’t work like that. You need to create a Yjs document first, and then define a type on the document.

1 Like

A question: how to initialization when persistence is empty

If it is the first time a document is opened, you can have a central server initializing the state. This may only happen once for each document. After that, you should persist the Yjs document somewhere to retain history.

1 Like