# 用 Yjs 做協作編輯

> 一個 Yjs provider：共用文件和即時游標透過 private 或 presence 頻道傳送，Tiptap、BlockNote、ProseMirror、CodeMirror、Monaco 和 Quill 都能直接用，不必自己架 y-websocket 伺服器。

Source: https://hibira.io/zh-tw/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 })
```

## 開始之前

- 在 App 設定中開啟「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)
