# 用 Yjs 做协作编辑

> 一个 Yjs provider：共享文档和实时光标通过 private 或 presence 频道传输，Tiptap、BlockNote、ProseMirror、CodeMirror、Monaco 和 Quill 都能直接用，不必自己部署 y-websocket 服务器。

Source: https://hibira.io/zh-cn/guides/y-hibira

一个 Yjs provider：共享文档和实时光标通过 private 或 presence 频道传输，Tiptap、BlockNote、ProseMirror、CodeMirror、Monaco 和 Quill 都能直接用，不必自己部署 y-websocket 服务器。

Package: y-hibira

- 各端通过 client events 互相同步；离线时的编辑会在重新连接后合并。
- 用 awareness 共享名字、光标和选区；在 presence 频道上，断线的成员会立即被移除。
- 支持 pusher-js 或 Laravel Echo 的频道，内置发送频率限制，较大的更新会自动分段。

## 1. 安装

```shell
npm install y-hibira yjs pusher-js
```

## 2. 使用

```js
import * as Y from 'yjs';
import Pusher from 'pusher-js';
import { HibiraProvider } from 'y-hibira';

const pusher = new Pusher('YOUR_APP_KEY', {
  cluster: 'hkg',
  wsHost: 'ws.hibira.io',
  channelAuthorization: { endpoint: '/broadcasting/auth' },
});

const doc = new Y.Doc();
const provider = new HibiraProvider(pusher, 'presence-doc-42', doc);
provider.awareness.setLocalStateField('user', { name: 'Alice', color: '#f97316' });
// Tiptap: Collaboration.configure({ document: doc }) and CollaborationCaret.configure({ provider })
```

## 开始之前

- 在应用设置中开启「Allow client events」：各端用 client events 互传文档更新。
- 私有频道和 presence 频道需要后端提供授权端点，用应用密钥签名订阅，做法与 pusher-js 相同。
- 服务器只转发更新，不会存储。请自行保存文档（Y.encodeStateAsUpdate），并在连接前加载。

- [npm](https://www.npmjs.com/package/y-hibira)
- [GitHub](https://github.com/hibira-io/y-hibira)
