53 lines
1.6 KiB
TypeScript
53 lines
1.6 KiB
TypeScript
import { fromUint8Array, toUint8Array } from 'js-base64';
|
|
import * as Y from 'yjs';
|
|
|
|
export function decodeAttributes<T>(encoded: string): T {
|
|
const doc = new Y.Doc();
|
|
Y.applyUpdate(doc, toUint8Array(encoded));
|
|
return doc.getMap('object').toJSON() as T;
|
|
}
|
|
|
|
export function encodeAttributes(attributes: Record<string, unknown>): string {
|
|
const doc = new Y.Doc();
|
|
const updates: Uint8Array[] = [];
|
|
doc.on('update', (update) => updates.push(update));
|
|
doc.transact(() => applyObject(doc.getMap('object'), attributes));
|
|
if (updates.length !== 1) throw new Error('Expected one Yjs update');
|
|
return fromUint8Array(Y.encodeStateAsUpdate(doc));
|
|
}
|
|
|
|
function applyObject(map: Y.Map<unknown>, object: Record<string, unknown>): void {
|
|
for (const [key, value] of Object.entries(object)) {
|
|
if (value === null || value === undefined) continue;
|
|
if (Array.isArray(value)) {
|
|
const arr = new Y.Array<unknown>();
|
|
arr.insert(0, value.map(convertValue));
|
|
map.set(key, arr);
|
|
} else if (isRecord(value)) {
|
|
const child = new Y.Map<unknown>();
|
|
applyObject(child, value);
|
|
map.set(key, child);
|
|
} else {
|
|
map.set(key, value);
|
|
}
|
|
}
|
|
}
|
|
|
|
function convertValue(value: unknown): unknown {
|
|
if (Array.isArray(value)) {
|
|
const arr = new Y.Array<unknown>();
|
|
arr.insert(0, value.map(convertValue));
|
|
return arr;
|
|
}
|
|
if (isRecord(value)) {
|
|
const map = new Y.Map<unknown>();
|
|
applyObject(map, value);
|
|
return map;
|
|
}
|
|
return value;
|
|
}
|
|
|
|
function isRecord(value: unknown): value is Record<string, unknown> {
|
|
return typeof value === 'object' && value !== null && !Array.isArray(value);
|
|
}
|