|
|
|
import { type JsMessageType } from "@graphite/messages"; |
|
import { createSubscriptionRouter, type SubscriptionRouter } from "@graphite/subscription-router"; |
|
import init, { setRandomSeed, wasmMemory, EditorHandle } from "@graphite-frontend/wasm/pkg/graphite_wasm.js"; |
|
|
|
export type Editor = { |
|
raw: WebAssembly.Memory; |
|
handle: EditorHandle; |
|
subscriptions: SubscriptionRouter; |
|
}; |
|
|
|
|
|
let wasmImport: WebAssembly.Memory | undefined; |
|
|
|
|
|
export async function initWasm() { |
|
|
|
if (wasmImport !== undefined) return; |
|
|
|
|
|
|
|
const wasm = await init(); |
|
for (const [name, f] of Object.entries(wasm)) { |
|
if (name.startsWith("__node_registry")) f(); |
|
} |
|
|
|
wasmImport = await wasmMemory(); |
|
|
|
(window as any).imageCanvases = {}; |
|
|
|
|
|
const randomSeedFloat = Math.floor(Math.random() * Number.MAX_SAFE_INTEGER); |
|
const randomSeed = BigInt(randomSeedFloat); |
|
setRandomSeed(randomSeed); |
|
} |
|
|
|
|
|
export function createEditor(): Editor { |
|
|
|
if (!wasmImport) throw new Error("Editor WASM backend was not initialized at application startup"); |
|
const raw: WebAssembly.Memory = wasmImport; |
|
|
|
|
|
const handle: EditorHandle = new EditorHandle((messageType: JsMessageType, messageData: Record<string, unknown>) => { |
|
|
|
|
|
subscriptions.handleJsMessage(messageType, messageData, raw, handle); |
|
}); |
|
|
|
|
|
const subscriptions: SubscriptionRouter = createSubscriptionRouter(); |
|
|
|
|
|
(async () => { |
|
const demoArtwork = window.location.hash.trim().match(/#demo\/(.*)/)?.[1]; |
|
if (!demoArtwork) return; |
|
|
|
try { |
|
const url = new URL(`/${demoArtwork}.graphite`, document.location.href); |
|
const data = await fetch(url); |
|
if (!data.ok) throw new Error(); |
|
|
|
const filename = url.pathname.split("/").pop() || "Untitled"; |
|
const content = await data.text(); |
|
handle.openDocumentFile(filename, content); |
|
|
|
|
|
history.replaceState("", "", `${window.location.pathname}${window.location.search}`); |
|
} catch { |
|
|
|
} |
|
})(); |
|
|
|
return { raw, handle, subscriptions }; |
|
} |
|
|