如何通过 WebSocket 获取/加载 Yjs 文档

huangapple go评论52阅读模式
英文:

How to get/load Yjs Doc via websocket

问题

I'm trying to get/load Y.Doc via WebSocket API (y-websocket library).

For this I wrote simple code like this. It connects to the server, but I can't load a document.

const id = 'my doc id';
const accessToken = 'my tocken';
const endpoint = ${WEBSOCKET_BASE}/document/${id}/;
const params = accessToken ? { at: accessToken } : undefined;

let doc = new Doc();
doc.autoLoad = true;

const websocketProvider = new WebsocketProvider(endpoint, '', doc, {
connect: false,
params,
WebSocketPolyfill: WebSocket,
});

websocketProvider.on('status', ({ status }: any) => {
console.log('Status is' + status.toString());
});

websocketProvider.on('synced', () => {
channel.printLine('Synced');

console.log('is doc loaded: ' + doc.isLoaded.toString());
console.log('is doc synced ' + doc.isSynced.toString());

console.log(doc.getText());

});

websocketProvider.on('reload', (doc: Doc) => {
console.log('reaload');
});

doc.whenLoaded.then(() => {
console.log('loaded now');
});

websocketProvider.connect();

Maybe someone knows how to fix it?

Thanks!

英文:

I'm trying to get/load Y.Doc via WebSocket API (y-websocket library).

For this I wrote simple code like this. It connects to the server, but I can't load a document.

const id = 'my doc id';
const accessToken = 'my tocken';
const endpoint = `${WEBSOCKET_BASE}/document/${id}/`;
const params = accessToken ? { at: accessToken } : undefined;

let doc = new Doc();
doc.autoLoad = true;

const websocketProvider = new WebsocketProvider(endpoint, '', doc, {
    connect: false,
    params,
    WebSocketPolyfill: WebSocket,
});

websocketProvider.on('status', ({ status }: any) => {
    console.log('Status is' + status.toString());
});

websocketProvider.on('synced', () => {
    channel.printLine('Synced');
   
    console.log('is doc loaded: ' + doc.isLoaded.toString());
    console.log('is doc synced ' + doc.isSynced.toString());

    console.log(doc.getText());
});

websocketProvider.on('reload', (doc: Doc) => {
    console.log('reaload');
});    

doc.whenLoaded.then(() => {
    console.log('loaded now');
});

websocketProvider.connect();

Maybe someone knows how to fix it?

Thanks!

答案1

得分: 2

以下是翻译好的代码部分:

你可以通过以下方式将你的ydoc与websocket提供程序连接:

import * as Y from "yjs";
import { WebsocketProvider } from "y-websocket";

const doc = new Y.Doc();
const wsProvider = new WebsocketProvider(
  "wss://demos.yjs.dev",
  "my-roomname",
  doc
);

wsProvider.on("status", (event) => {
  console.log(event.status); // logs "connected" or "disconnected"
});

你可以在wsProvider对象上添加其他事件监听器。

这里提供了一个完整的工作示例供参考:

index.html

<!DOCTYPE html>
<html>
  <head>
    <title>Parcel Sandbox</title>
    <meta charset="UTF-8" />
  </head>

  <body>
    <div id="app">
      <button id="button">Insert random number to array</button>
      <div id="result" />
    </div>

    <script src="src/index.js"></script>
  </body>
</html>

index.js

import * as Y from "yjs";
import { WebsocketProvider } from "y-websocket";

const doc = new Y.Doc();
const wsProvider = new WebsocketProvider(
  "wss://demos.yjs.dev",
  "my-roomname",
  doc
);

wsProvider.on("status", (event) => {
  console.log(event.status); // logs "connected" or "disconnected"
});

const yarray = doc.getArray("my-array");

const button = document.getElementById("button");
const resultDiv = document.getElementById("result");

button.addEventListener("click", () => {
  const randomNumberBetweenZeroAndTen = Math.floor(Math.random() * 10);
  yarray.push([randomNumberBetweenZeroAndTen]);
});

resultDiv.innerText = "Content of my-array: " + yarray.toArray();
yarray.observe(() => {
  resultDiv.innerText = "Content of my-array: " + yarray.toArray();
});

codesandbox链接

上述实现将通过websocket在两个客户端之间同步你的ydoc。

英文:

You can connect your ydoc with websocket provider, like so:

import * as Y from &quot;yjs&quot;;
import { WebsocketProvider } from &quot;y-websocket&quot;;

const doc = new Y.Doc();
const wsProvider = new WebsocketProvider(
  &quot;wss://demos.yjs.dev&quot;,
  &quot;my-roomname&quot;,
  doc
);

wsProvider.on(&quot;status&quot;, (event) =&gt; {
  console.log(event.status); // logs &quot;connected&quot; or &quot;disconnected&quot;
});

You can add the other event listeners on wsProvider object.

I am adding a full working demo here, for you reference:

index.html

&lt;!DOCTYPE html&gt;
&lt;html&gt;
  &lt;head&gt;
    &lt;title&gt;Parcel Sandbox&lt;/title&gt;
    &lt;meta charset=&quot;UTF-8&quot; /&gt;
  &lt;/head&gt;

  &lt;body&gt;
    &lt;div id=&quot;app&quot;&gt;
      &lt;button id=&quot;button&quot;&gt;Insert random number to array&lt;/button&gt;
      &lt;div id=&quot;result&quot; /&gt;
    &lt;/div&gt;

    &lt;script src=&quot;src/index.js&quot;&gt;&lt;/script&gt;
  &lt;/body&gt;
&lt;/html&gt;

index.js

import * as Y from &quot;yjs&quot;;
import { WebsocketProvider } from &quot;y-websocket&quot;;

const doc = new Y.Doc();
const wsProvider = new WebsocketProvider(
  &quot;wss://demos.yjs.dev&quot;,
  &quot;my-roomname&quot;,
  doc
);

wsProvider.on(&quot;status&quot;, (event) =&gt; {
  console.log(event.status); // logs &quot;connected&quot; or &quot;disconnected&quot;
});

const yarray = doc.getArray(&quot;my-array&quot;);

const button = document.getElementById(&quot;button&quot;);
const resultDiv = document.getElementById(&quot;result&quot;);

button.addEventListener(&quot;click&quot;, () =&gt; {
  const randomNumberBetweenZeroAndTen = Math.floor(Math.random() * 10);
  yarray.push([randomNumberBetweenZeroAndTen]);
});

resultDiv.innerText = &quot;Content of my-array: &quot; + yarray.toArray();
yarray.observe(() =&gt; {
  resultDiv.innerText = &quot;Content of my-array: &quot; + yarray.toArray();
});

codesandbox link

The above implementation will sync your ydoc between two clients via websocket.

huangapple
  • 本文由 发表于 2023年4月6日 23:08:46
  • 转载请务必保留本文链接:https://go.coder-hub.com/75951061.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定