Files
pages/assets/excalidraw-viewer/src/main.jsx
T
Anya Tokugawa c1175d389f Implement Knowledge City platform, organizer and DAV integration
Capture accumulated application, UI, CLI, regression tests and design documentation changes, including task project mapping and default CalDAV list naming.

Keep deployment data, backups, local credentials and build artifacts out of Git. Move the Compose enrollment token to an ignored local environment file.
2026-09-27 14:44:43 +09:00

113 lines
3.6 KiB
React

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 <main className="viewer-status viewer-error">{error}</main>
if (!scene) return <main className="viewer-status">Loading Excalidraw…</main>
return (
<main className="viewer-shell">
<Excalidraw
initialData={{
elements: scene.elements,
appState: scene.appState,
files: scene.files
}}
viewModeEnabled
zenModeEnabled
langCode={(navigator.language || "en").toLowerCase().startsWith("ja") ? "ja-JP" : "en"}
UIOptions={{
canvasActions: {
changeViewBackgroundColor: false,
clearCanvas: false,
export: false,
loadScene: false,
saveAsImage: false,
saveToActiveFile: false,
toggleTheme: true
}
}}
excalidrawAPI={api => {
requestAnimationFrame(() => api.scrollToContent(undefined, { fitToContent: true }))
notifyParent("ready")
}}
/>
</main>
)
}
createRoot(document.getElementById("root")).render(<Viewer />)