import React, { useEffect, useState } from "react"
import { createRoot } from "react-dom/client"
import { Excalidraw } from "@excalidraw/excalidraw"
import "@excalidraw/excalidraw/index.css"
import "./viewer.css"
const MAX_SCENE_BYTES = 2 * 1024 * 1024
const notifyParent = (type, detail = "") => {
window.parent.postMessage({ source: "pageswiki-excalidraw", type, detail }, window.location.origin)
}
const sceneURL = () => {
const value = new URLSearchParams(window.location.search).get("url") || ""
const parsed = new URL(value, window.location.origin)
if (parsed.origin !== window.location.origin || !parsed.pathname.startsWith("/v/raw/rev:")) {
throw new Error("An immutable same-origin Revision URL is required")
}
return parsed.href
}
const readBoundedText = async response => {
const declared = Number(response.headers.get("content-length") || 0)
if (declared > MAX_SCENE_BYTES) throw new Error("Scene exceeds the 2 MiB viewer limit")
if (!response.body) return response.text()
const reader = response.body.getReader()
const chunks = []
let size = 0
while (true) {
const { done, value } = await reader.read()
if (done) break
size += value.byteLength
if (size > MAX_SCENE_BYTES) {
await reader.cancel()
throw new Error("Scene exceeds the 2 MiB viewer limit")
}
chunks.push(value)
}
const joined = new Uint8Array(size)
let offset = 0
chunks.forEach(chunk => {
joined.set(chunk, offset)
offset += chunk.byteLength
})
return new TextDecoder().decode(joined)
}
function Viewer() {
const [scene, setScene] = useState(null)
const [error, setError] = useState("")
useEffect(() => {
const controller = new AbortController()
;(async () => {
try {
const response = await fetch(sceneURL(), {
credentials: "same-origin",
cache: "force-cache",
signal: controller.signal,
headers: { Accept: "application/json" }
})
if (!response.ok) throw new Error(`Revision fetch failed: HTTP ${response.status}`)
const loaded = JSON.parse(await readBoundedText(response))
if (loaded?.type !== "excalidraw" || !Array.isArray(loaded.elements)) {
throw new Error("Invalid Excalidraw scene")
}
setScene(loaded)
} catch (reason) {
if (reason?.name === "AbortError") return
const message = reason instanceof Error ? reason.message : String(reason)
setError(message)
notifyParent("error", message)
}
})()
return () => controller.abort()
}, [])
if (error) return {error}
if (!scene) return Loading Excalidraw…
return (
{
requestAnimationFrame(() => api.scrollToContent(undefined, { fitToContent: true }))
notifyParent("ready")
}}
/>
)
}
createRoot(document.getElementById("root")).render()