Yjs入门

2022-12-08  本文已影响0人  我叫Aliya但是被占用了

具有强大的共享数据抽象的 CRDT (conflict-free replicated data type 无冲突复制数据类型) 框架。它将其内部数据结构公开为共享类型。

共享类型是常见的数据类型,如具有超能力的 Map 或 Array:更改会自动分发到其他对等体,并在没有合并冲突的情况下进行合并。(带有数据劫持的 shareArray?)

支持许多现有的富文本编辑器、脱机编辑、版本快照、撤消/重做和共享光标。

demosAPI

// demo from  https://docs.yjs.dev/
import * as Y from 'yjs'

const ydoc = new Y.Doc()
const ymap = ydoc.getMap()
ymap.set('keyA', 'valueA')

// 比如服务器?
const ydocRemote = new Y.Doc()
const ymapRemote = ydocRemote.getMap()
ymapRemote.set('keyB', 'valueB')

// Merge changes from remote
const update = Y.encodeStateAsUpdate(ydocRemote)
Y.applyUpdate(ydoc, update)

// Observe that the changes have merged
console.log(ymap.toJSON()) // => { keyA: 'valueA', keyB: 'valueB' }

共享类型

Y.Doc : const doc = new Y.Doc()

https://github.com/yjs/yjs#Shared-Types

y-websocket

maybe https://github.com/y-js/y-websockets-clienthttps://github.com/y-js/y-websockets-server ?

// Extension for tiptap
import { keymap } from "prosemirror-keymap";
import { Extension } from "tiptap";
import {
  redo,
  undo,
  yCursorPlugin,
  ySyncPlugin,
  yUndoPlugin,
} from "y-prosemirror";
import { WebsocketProvider } from "y-websocket";
import * as Y from "yjs";

const ydoc = new Y.Doc();
const roomname = location.href.includes("uuu") ? "tiptap-demo2" : "tiptap-demo";
const provider = new WebsocketProvider("ws://localhost:8080", roomname, ydoc);
const type = ydoc.getXmlFragment("prosemirror");

provider.on("sync", (isSynced) => {
  console.log("======= sync", isSynced, window.ee.getHTML()); // logs "connected" or "disconnected"
  //   现在没值时进行插入
  if (window.ee.getText() === "")
    window.ee.commands.setContent("<p>Example Text</p>");
});

export default class RealtimeExtension extends Extension {
  get name() {
    return "realtime";
  }

  get plugins() {
    return [
      ySyncPlugin(type),
      yCursorPlugin(provider.awareness),
      yUndoPlugin(),
      keymap({
        "Mod-z": undo,
        "Mod-y": redo,
        "Mod-Shift-z": redo,
      }),
    ];
  }
}
// server by node
const WebSocket = require("ws");
const http = require("http");
const StaticServer = require("node-static").Server;
const setupWSConnection = require("y-websocket/bin/utils.js").setupWSConnection;

const production = process.env.PRODUCTION != null;
const port = process.env.PORT || 8080;

const staticServer = new StaticServer("../", {
  cache: production ? 3600 : false,
  gzip: production,
});

const server = http.createServer((request, response) => {
  request
    .addListener("end", () => {
      staticServer.serve(request, response);
    })
    .resume();
});
const wss = new WebSocket.Server({ server });

wss.on("connection", (conn, req) => setupWSConnection(conn, req, { gc: true }));

server.listen(port);

console.log(
  `Listening to http://localhost:${port} ${production ? "(production)" : ""}`
);
上一篇下一篇

猜你喜欢

热点阅读