Skip to content

实时协作 (Collaboration)

FlowCollaborationEngine 基于 WebSocket 与轻量级 CRDT(LWW Register / G-Counter)实现多人实时编辑 Flow,支持光标同步、选区同步与冲突解决。协作引擎提供 connectdisconnect 与事件监听,可直接与现有的 WebSocket 服务对接。

协作架构

  • CRDT 状态:本地维护 nodesedgesviewport 的 Map,结合 LWW 注册表处理并发更新
  • WebSocket 消息:join/leave/operation/sync/cursor/selection 六种消息类型,用于房间管理、状态同步与即时交互
  • 事件回调:支持 syncoperationcursor_updateuser_joineduser_left 等事件,便于 UI 响应
  • 重连机制:自动指数退避重连,最多 5 次尝试

核心 API

API说明
connect(options)连接到协作房间(serverUrl、roomId、userId、userName、初始节点/边)
disconnect()断开连接,清理心跳
addNode(node) / updateNode(nodeId, updates) / deleteNode(nodeId)本地操作自动广播
addEdge(edge) / updateEdge(edgeId, updates) / deleteEdge(edgeId)连线操作同步
updateViewport(viewport) / updateCursor(x, y) / updateSelection(nodeIds)视口与交互同步
getState() / getCursors() / getConnectionState()查询当前状态
on(event, callback) / off(event, callback)事件订阅

示例

下面示例演示如何初始化协作引擎、连接房间、监听事件,并在 UI 中展示用户光标与状态。

开始
协作编辑
结束

连接状态:disconnected

实时协作示例

最佳实践

  1. 结合业务 WebSocket 服务connect 中的 serverUrl 替换为你的协作后端地址,后端只需转发消息即可。
  2. 本地优先:所有本地操作立即生效,网络同步通过 operation 消息异步完成,LWW 机制保证最终一致性。
  3. 处理冲突:通过 on('operation') 监听远程更新,可针对特定节点/边做冲突 UI 提示或回滚。
  4. 光标与选区优化updateCursorupdateSelection 使用不可靠传输(unreliable),避免频繁网络抖动影响体验。

Released under the MIT License.