Skip to content

Commit

Permalink
Add y.js helpers to decode awareness messages
Browse files Browse the repository at this point in the history
Signed-off-by: Jonas <[email protected]>
  • Loading branch information
mejo- committed Jun 21, 2023
1 parent e099f42 commit 2856d09
Showing 1 changed file with 40 additions and 1 deletion.
41 changes: 40 additions & 1 deletion src/helpers/yjs.js
Original file line number Diff line number Diff line change
Expand Up @@ -20,8 +20,21 @@
*
*/

import { encodeArrayBuffer, decodeArrayBuffer } from '../helpers/base64.js'
import { encodeArrayBuffer, decodeArrayBuffer } from './base64.js'
import { Doc, encodeStateAsUpdate, applyUpdate } from 'yjs'
import * as decoding from 'lib0/decoding.js'

export const yjsMessageTypes = {
sync: 0,
awareness: 1,
awarenessQuery: 3,
}

export const yjsMessageSyncTypes = {
step1: 0,
step2: 1,
update: 3,
}

/**
*
Expand All @@ -42,3 +55,29 @@ export function applyDocumentState(ydoc, documentState, origin) {
const update = decodeArrayBuffer(documentState)
applyUpdate(ydoc, update, origin)
}

/**
* @param {string} update - base64 encoded Y.js message
*/
export function getMessageType(update) {
const decoder = decoding.createDecoder(update)
return decoding.readVarUint(decoder)
}

/**
* @param {string} update - base64 encoded Y.js message
*/
export function getAwarenessMessageClientIds(update) {
const decoder = decoding.createDecoder(update)
const type = decoding.readVarUint(decoder)
if (type !== yjsMessageTypes.awareness) {
return []
}

const len = decoding.readVarUint(decoder)
const clientIds = []
for (let i = 0; i < len; i++) {
clientIds.push(decoding.readVarUint(decoder))
}
return clientIds
}

0 comments on commit 2856d09

Please sign in to comment.