yjs / y-webrtc

WebRTC Connector for Yjs
MIT License
448 stars 109 forks source link

Support for obtaining the current online client #44

Closed fEyebrow closed 1 year ago

fEyebrow commented 1 year ago

I had this situation: https://github.com/yjs/yjs-demos/issues/16.

To avoid the initial content being duplicated, the client needs to know if it is the first to join. Only the first to join needs to set the initial content. So I added the function.

Here is my client code:

provider.on('synced', (val: { synced: boolean }) => {
  console.log('synced', val.synced)
  status.value = val.synced ? 'connected' : 'disconnected'
  isInitContent = true
})

let isInitContent = false
provider.signalingConns[0].on('message', (m: any) => {
  if (m?.data?.type === 'announce' && m?.number <= 1 && !isInitContent) {
    isInitContent = true
    const currentContent = editor.value?.getHTML()
    if (currentContent === '<p></p>') {
      editor.value?.commands.setContent(content, true)
    }
  }
})
dmonad commented 1 year ago

Hi @fEyebrow,

This will work fine for local testing. But if the delay is more significant, this approach will fail when two clients connect simultaneously to the signaling server. Once "the first client" announces themselves, the "room" might already have two users listening to messages.

There needs to be more to solve the underlying problem. I still suggest you go with the solution described in https://github.com/yjs/yjs-demos/issues/16.

However, happy to include the number of connected clients in the published messages. Please rename message.number to message.clients.

fEyebrow commented 1 year ago

@dmonad I renamed message.number to message.clients

Thanks for your answer. If I go with the solution described in https://github.com/yjs/yjs-demos/issues/16, I need to save the Yjs doc when the article is created, and then edit it later based on the saved Yjs doc, just like git clone the same source. After that, when a new user joins, the content will not be duplicated, is that right?

dmonad commented 1 year ago

If I go with the solution described in https://github.com/yjs/yjs-demos/issues/16, I need to save the Yjs doc when the article is created, and then edit it later based on the saved Yjs doc, just like git clone the same source. After that, when a new user joins, the content will not be duplicated, is that right?

Exactly :+1: