diff --git a/src/utils.ts b/src/utils.ts index a578222..21194ef 100644 --- a/src/utils.ts +++ b/src/utils.ts @@ -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(