Skip to content

Commit

Permalink
refactor: support binary string
Browse files Browse the repository at this point in the history
  • Loading branch information
lawvs committed Apr 19, 2024
1 parent b71115c commit 1547092
Showing 1 changed file with 30 additions and 7 deletions.
37 changes: 30 additions & 7 deletions src/utils.ts
Original file line number Diff line number Diff line change
@@ -1,15 +1,38 @@
import type { Path } from "@textea/json-viewer";
import * as Y from "yjs";

export async function fileToYDoc(file: File) {
const decoders = [
{
name: "binary update",
decode: async (file: File) => {
return new Uint8Array(await file.arrayBuffer());
},
},
{
name: "binary string",
decode: async (file: File) => {
const text = await file.text();
// Parse binary string
// `Buffer.from(encodeUpdate).toString("binary")`
return Uint8Array.from(text, (c) => c.charCodeAt(0));
},
},
// TODO handle base64 encoding
// https://docs.yjs.dev/api/document-updates#example-base64-encoding
const yDocUpdate = new Uint8Array(await file.arrayBuffer());
const newYDoc = new Y.Doc();
// For debugging
Y.logUpdate(yDocUpdate);
Y.applyUpdate(newYDoc, yDocUpdate);
return newYDoc;
];

export async function fileToYDoc(file: File) {
for (const decoder of decoders) {
try {
const yDocUpdate = await decoder.decode(file);
const newYDoc = new Y.Doc();
Y.applyUpdate(newYDoc, yDocUpdate);
Y.logUpdate(yDocUpdate);
return newYDoc;
} catch (error) {
console.warn(`Failed to decode ${decoder.name}`, error);
}
}
}

export function getPathValue<T = object, R = object>(
Expand Down

0 comments on commit 1547092

Please sign in to comment.