diff --git a/package.json b/package.json index c0a4abb..4a05c83 100644 --- a/package.json +++ b/package.json @@ -21,6 +21,7 @@ "@tanstack/react-query-devtools": "5.59.11", "@xyflow/react": "12.3.2", "elkjs": "0.9.3", + "libavoid-js": "0.4.5", "monaco-editor": "0.52.0", "react": "18.3.1", "react-aria-components": "^1.4.0", diff --git a/src/Visualizer.tsx b/src/Visualizer.tsx index 8f1d7fd..09e75f8 100644 --- a/src/Visualizer.tsx +++ b/src/Visualizer.tsx @@ -210,6 +210,8 @@ function Rendering({ setUseInteractiveLayout, mergeEdges, setMergeEdges, + avoidEdgeRouting, + setAvoidEdgeRouting, showText, setShowText, textSyntax, @@ -232,6 +234,8 @@ function Rendering({ setUseInteractiveLayout: (value: boolean) => void; mergeEdges: boolean; setMergeEdges: (value: boolean) => void; + avoidEdgeRouting: boolean; + setAvoidEdgeRouting: (value: boolean) => void; showText: boolean; setShowText: (value: boolean) => void; textSyntax: TextSyntax; @@ -338,6 +342,10 @@ function Rendering({ [setUseInteractiveLayout, useInteractiveLayout] ); const handleToggleMergeEdges = useCallback(() => setMergeEdges(!mergeEdges), [setMergeEdges, mergeEdges]); + const handleToggleAvoidEdgeRouting = useCallback( + () => setAvoidEdgeRouting(!avoidEdgeRouting), + [setAvoidEdgeRouting, avoidEdgeRouting] + ); const handleCopyText = useCallback( () => textClipboard.copy(blocksToPlainText(formatEGraphBlocks(subgraph, textSyntax))), [subgraph, textSyntax, textClipboard] @@ -463,6 +471,13 @@ function Rendering({ Merge edges {mergeEdges ? "Seperate ports for incoming edges" : "Merge all incoming edges"} + + {avoidEdgeRouting ? : } + Edge routing: {avoidEdgeRouting ? "libavoid" : "ELK"} + + {avoidEdgeRouting ? "Switch to ELK layered edge routing" : "Route edges with libavoid to reduce crossings"} + + @@ -529,6 +544,8 @@ function LayoutFlow({ setTextSyntax, inlineLevel, setInlineLevel, + avoidEdgeRouting, + setAvoidEdgeRouting, }: { egraph: string; outerElem: HTMLDivElement; @@ -542,6 +559,8 @@ function LayoutFlow({ setTextSyntax: (value: TextSyntax) => void; inlineLevel: InlineLevel; setInlineLevel: (value: InlineLevel) => void; + avoidEdgeRouting: boolean; + setAvoidEdgeRouting: (value: boolean) => void; }) { const [useInteractiveLayout, setUseInteractiveLayout] = useState(false); const [mergeEdges, setMergeEdges] = useState(false); @@ -665,6 +684,7 @@ function LayoutFlow({ selectedNodes, previousLayout, mergeEdges, + avoidEdgeRouting, inlineLevel, effectiveInlineSyntax, ], @@ -679,6 +699,7 @@ function LayoutFlow({ selectedNodes, previousLayout, mergeEdges, + avoidEdgeRouting, inlineLevel, effectiveInlineSyntax, signal @@ -837,6 +858,8 @@ function LayoutFlow({ setUseInteractiveLayout={setUseInteractiveLayout} mergeEdges={mergeEdges} setMergeEdges={setMergeEdges} + avoidEdgeRouting={avoidEdgeRouting} + setAvoidEdgeRouting={setAvoidEdgeRouting} showText={showText} setShowText={setShowText} textSyntax={textSyntax} @@ -931,6 +954,7 @@ export type MountOptions = { showText?: boolean; textSyntax?: TextSyntax; inlineLevel?: InlineLevel; + avoidEdgeRouting?: boolean; }; export function Visualizer({ @@ -940,6 +964,7 @@ export function Visualizer({ showText: initialShowText = false, textSyntax: initialTextSyntax = "call", inlineLevel: initialInlineLevel = 0, + avoidEdgeRouting: initialAvoidEdgeRouting = true, }: { egraphs: string[]; height?: string | null; @@ -947,6 +972,7 @@ export function Visualizer({ showText?: boolean; textSyntax?: TextSyntax; inlineLevel?: InlineLevel; + avoidEdgeRouting?: boolean; }) { const [rootElem, setRootElem] = useState(null); @@ -956,6 +982,7 @@ export function Visualizer({ const [showText, setShowText] = useState(initialShowText); const [textSyntax, setTextSyntax] = useState(initialTextSyntax); const [inlineLevel, setInlineLevel] = useState(initialInlineLevel); + const [avoidEdgeRouting, setAvoidEdgeRouting] = useState(initialAvoidEdgeRouting); const aspectRatio = rootElem ? rootElem.clientWidth / rootElem.clientHeight : null; useEffect(() => { @@ -970,6 +997,10 @@ export function Visualizer({ setInlineLevel(initialInlineLevel); }, [initialInlineLevel]); + useEffect(() => { + setAvoidEdgeRouting(initialAvoidEdgeRouting); + }, [initialAvoidEdgeRouting]); + // If we are at null, then use the last item in the list // if the last selection was for a list of egraphs that no longer exists, then use the last item in the list const [selected, setSelected] = useState(null); @@ -1003,6 +1034,8 @@ export function Visualizer({ setTextSyntax={setTextSyntax} inlineLevel={inlineLevel} setInlineLevel={setInlineLevel} + avoidEdgeRouting={avoidEdgeRouting} + setAvoidEdgeRouting={setAvoidEdgeRouting} /> )} @@ -1060,6 +1093,7 @@ export function mount( showText={merged.showText} textSyntax={merged.textSyntax} inlineLevel={merged.inlineLevel} + avoidEdgeRouting={merged.avoidEdgeRouting} /> ); diff --git a/src/layout.ts b/src/layout.ts index 64f7596..6169af3 100644 --- a/src/layout.ts +++ b/src/layout.ts @@ -5,6 +5,7 @@ import { Node, Edge } from "@xyflow/react"; // Make worker inline because if its external cannot be loaded from esm.sh due to CORS import ELKWorker from "elkjs/lib/elk-worker?worker&inline"; import { InlineLevel, InlineResult, inlineLeaves } from "./inline"; +import { routeOuterEdgesWithCancel } from "./routing"; import { TextSyntax } from "./text"; // Elk has a *huge* amount of options to configure. To see everything you can @@ -276,6 +277,7 @@ export async function layoutGraph( selectedNodes: SelectedNodes, previousLayout: PreviousLayout | null, mergeEdges: boolean, + avoidEdgeRouting: boolean, inlineLevel: InlineLevel, inlineSyntax: TextSyntax, signal: AbortSignal @@ -313,7 +315,7 @@ export async function layoutGraph( const { elkNode, colors } = toELKNode(subgraph, getNodeSize, getExtraSize, selectedNodes, aspectRatio, previousLayout, mergeEdges); const elkJSON = JSON.stringify(elkNode, null, 2); const layout = (await layoutWithCancel(elkNode, signal)) as MyELKNodeLayedOut; - const edges = toFlowEdges(layout); + const edges = await toFlowEdges(layout, mergeEdges, avoidEdgeRouting, signal); const nodes = toFlowNodes(layout); const nodeToEdges = new Map( [...Object.entries(Object.groupBy(edges, (edge) => edge.source)), ...Object.entries(Object.groupBy(edges, (edge) => edge.target))].map( @@ -576,9 +578,52 @@ function toFlowNodes(layout: MyELKNodeLayedOut): (FlowClass | FlowNode)[] { ]); } -function toFlowEdges(layout: MyELKNodeLayedOut): FlowEdge[] { +function joinInnerAndOuterPoints( + innerPoints: { x: number; y: number }[], + outerPoints: { x: number; y: number }[], + sourceNodeBounds?: { x: number; y: number; width: number; height: number } +): { x: number; y: number }[] { + const innerEnd = innerPoints[innerPoints.length - 1]; + const outerStart = outerPoints[0]; + if (Math.hypot(innerEnd.x - outerStart.x, innerEnd.y - outerStart.y) < 0.5) { + return [...innerPoints, ...outerPoints.slice(1)]; + } + // If inner edge is a straight vertical drop and libavoid nudged the border exit slightly + // horizontally within the source e-node's width, align the vertical drop so there is no jog. + if ( + sourceNodeBounds && + innerPoints.length === 2 && + Math.abs(innerPoints[0].x - innerEnd.x) < 0.5 && + Math.abs(innerEnd.y - outerStart.y) < 1 && + outerStart.x >= sourceNodeBounds.x + 3 && + outerStart.x <= sourceNodeBounds.x + sourceNodeBounds.width - 3 + ) { + return [{ x: outerStart.x, y: innerPoints[0].y }, ...outerPoints]; + } + return [...innerPoints, ...outerPoints]; +} + +async function toFlowEdges( + layout: MyELKNodeLayedOut, + mergeEdges: boolean, + avoidEdgeRouting: boolean, + signal: AbortSignal +): Promise { const outerEdges = Object.fromEntries(layout.edges!.map(({ edgeID, sections }) => [edgeID, sections![0]])); - return layout.children.flatMap(({ x: parentX, y: parentY, edges }) => + const classes = layout.children.map(({ id, x, y, width, height }) => ({ id, x, y, width, height })); + const nodeBounds = new Map(); + for (const cls of layout.children) { + for (const child of cls.children) { + nodeBounds.set(child.id, { + x: cls.x + child.x, + y: cls.y + child.y, + width: child.width, + height: child.height, + }); + } + } + + const edgeItems = layout.children.flatMap(({ id: sourceClassID, x: parentX, y: parentY, edges }) => edges!.map(({ edgeID, sections, sourceNode, targetNode }) => { const [section] = sections!; const outerEdge = outerEdges[edgeID]; @@ -588,15 +633,52 @@ function toFlowEdges(layout: MyELKNodeLayedOut): FlowEdge[] { y: y + parentY, })); return { - type: "edge", - id: edgeID, - source: sourceNode, - target: targetNode!, - data: { - // Combien inner and outer edge show it just shows up once in the rendering and can be selected as a single unit. - points: [...innerPoints, ...(outerEdge.bendPoints || []), outerEdge.endPoint], - }, + edgeID, + sourceNode, + sourceClassID, + targetNode: targetNode!, + innerPoints, + outerEdge, }; }) ); + + let routedOuter: Map | null = null; + if (avoidEdgeRouting) { + try { + routedOuter = await routeOuterEdgesWithCancel( + classes, + edgeItems.map((item) => ({ + edgeID: item.edgeID, + sourceClassID: item.sourceClassID, + targetClassID: item.targetNode, + sourcePoint: item.innerPoints[item.innerPoints.length - 1], + elkTargetPoint: item.outerEdge.endPoint, + })), + mergeEdges, + signal + ); + } catch (err) { + if (signal.aborted) { + throw err; + } + // Fall back to ELK edge routes if WASM routing fails in an unusual host environment. + console.warn("libavoid edge routing failed, falling back to ELK routes:", err); + } + } + + return edgeItems.map(({ edgeID, sourceNode, targetNode, innerPoints, outerEdge }) => { + const outerPoints = routedOuter?.get(edgeID); + const points = + outerPoints && outerPoints.length >= 2 + ? joinInnerAndOuterPoints(innerPoints, outerPoints, nodeBounds.get(sourceNode)) + : [...innerPoints, ...(outerEdge.bendPoints || []), outerEdge.endPoint]; + return { + type: "edge", + id: edgeID, + source: sourceNode, + target: targetNode, + data: { points }, + }; + }); } diff --git a/src/routing.ts b/src/routing.ts new file mode 100644 index 0000000..caaac64 --- /dev/null +++ b/src/routing.ts @@ -0,0 +1,98 @@ +// Make worker inline so it works from esm.sh / AnyWidget without external asset fetches or CORS issues. +import RoutingWorker from "./routing.worker?worker&inline"; +import type { + ClassBox, + OuterEdgeInput, + RoutePoint, + RouteWorkerRequest, + RouteWorkerResponse, +} from "./routing.worker"; + +export type { ClassBox, OuterEdgeInput, RoutePoint }; + +// Reuse a single warm worker when not aborted so WASM only compiles once per session; +// terminate and recreate on abort so long routing jobs cancel immediately. +let sharedWorker: Worker | null = null; +let workerBusy = false; + +function acquireWorker(): Worker { + if (sharedWorker && !workerBusy) { + return sharedWorker; + } + return new RoutingWorker(); +} + +export function routeOuterEdgesWithCancel( + classes: ClassBox[], + edges: OuterEdgeInput[], + mergeEdges: boolean, + signal: AbortSignal +): Promise> { + if (edges.length === 0 || classes.length === 0) { + return Promise.resolve(new Map()); + } + + return new Promise((resolve, reject) => { + if (signal.aborted) { + reject(signal.reason); + return; + } + + const worker = acquireWorker(); + const isShared = worker === sharedWorker || sharedWorker === null; + if (sharedWorker === null) { + sharedWorker = worker; + } + if (isShared) { + workerBusy = true; + } + + let settled = false; + const cleanup = (terminate: boolean) => { + worker.onmessage = null; + worker.onerror = null; + signal.removeEventListener("abort", onAbort); + if (terminate) { + worker.terminate(); + if (worker === sharedWorker) { + sharedWorker = null; + workerBusy = false; + } + } else if (isShared) { + workerBusy = false; + } else { + worker.terminate(); + } + }; + + const onAbort = () => { + if (settled) return; + settled = true; + cleanup(true); + reject(signal.reason); + }; + + signal.addEventListener("abort", onAbort, { once: true }); + + worker.onmessage = (event: MessageEvent) => { + if (settled) return; + settled = true; + cleanup(false); + if (event.data.ok) { + resolve(new Map(event.data.routes)); + } else { + reject(new Error(event.data.error)); + } + }; + + worker.onerror = (err) => { + if (settled) return; + settled = true; + cleanup(true); + reject(err instanceof ErrorEvent ? err.error ?? new Error(err.message) : err); + }; + + const req: RouteWorkerRequest = { classes, edges, mergeEdges }; + worker.postMessage(req); + }); +} diff --git a/src/routing.worker.ts b/src/routing.worker.ts new file mode 100644 index 0000000..0ebaba3 --- /dev/null +++ b/src/routing.worker.ts @@ -0,0 +1,247 @@ +import { AvoidLib } from "libavoid-js"; +import libavoidWasmUrl from "virtual:libavoid-wasm"; + +export type RoutePoint = { x: number; y: number }; + +export type ClassBox = { + id: string; + x: number; + y: number; + width: number; + height: number; +}; + +export type OuterEdgeInput = { + edgeID: string; + sourceClassID: string; + targetClassID: string; + sourcePoint: RoutePoint; + elkTargetPoint: RoutePoint; +}; + +export type RouteWorkerRequest = { + classes: ClassBox[]; + edges: OuterEdgeInput[]; + mergeEdges: boolean; +}; + +export type RouteWorkerResponse = + | { ok: true; routes: [string, RoutePoint[]][] } + | { ok: false; error: string }; + +let avoidReady: Promise> | null = null; + +function getAvoid() { + if (!avoidReady) { + avoidReady = AvoidLib.load(libavoidWasmUrl).then(() => AvoidLib.getInstance()); + } + return avoidReady; +} + +function clamp(val: number, min: number, max: number): number { + return Math.max(min, Math.min(max, val)); +} + +function simplifyPoints(pts: RoutePoint[]): RoutePoint[] { + if (pts.length <= 2) return pts; + const deduped: RoutePoint[] = [pts[0]]; + for (let i = 1; i < pts.length; i++) { + const prev = deduped[deduped.length - 1]; + if (Math.hypot(pts[i].x - prev.x, pts[i].y - prev.y) > 0.25) { + deduped.push(pts[i]); + } + } + if (deduped.length <= 2) return deduped; + const out: RoutePoint[] = [deduped[0]]; + for (let i = 1; i < deduped.length - 1; i++) { + const a = out[out.length - 1]; + const b = deduped[i]; + const c = deduped[i + 1]; + const cross = (b.x - a.x) * (c.y - b.y) - (b.y - a.y) * (c.x - b.x); + if (Math.abs(cross) > 0.5) { + out.push(b); + } + } + out.push(deduped[deduped.length - 1]); + return out; +} + +function sideDirection(pt: RoutePoint, box: ClassBox, Avoid: ReturnType): number { + const dTop = Math.abs(pt.y - box.y); + const dBottom = Math.abs(pt.y - (box.y + box.height)); + const dLeft = Math.abs(pt.x - box.x); + const dRight = Math.abs(pt.x - (box.x + box.width)); + const minD = Math.min(dTop, dBottom, dLeft, dRight); + if (minD === dBottom) return Avoid.ConnDirDown; + if (minD === dTop) return Avoid.ConnDirUp; + if (minD === dLeft) return Avoid.ConnDirLeft; + return Avoid.ConnDirRight; +} + +function snapToBoxSide( + pt: RoutePoint, + box: ClassBox, + dir: number, + Avoid: ReturnType +): { xOff: number; yOff: number } { + const xOff = box.width > 0 ? clamp((pt.x - box.x) / box.width, 0.01, 0.99) : 0.5; + const yOff = box.height > 0 ? clamp((pt.y - box.y) / box.height, 0.01, 0.99) : 0.5; + if (dir === Avoid.ConnDirDown) return { xOff, yOff: 1 }; + if (dir === Avoid.ConnDirUp) return { xOff, yOff: 0 }; + if (dir === Avoid.ConnDirLeft) return { xOff: 0, yOff }; + return { xOff: 1, yOff }; +} + +function routeWithAvoid( + Avoid: ReturnType, + req: RouteWorkerRequest +): [string, RoutePoint[]][] { + const { classes, edges, mergeEdges } = req; + if (edges.length === 0 || classes.length === 0) { + return []; + } + + // Crossing-penalty rerouting scales super-linearly with edge count; enable it up + // to 180 edges (takes ~2ms-4s in WASM) and fall back to fast orthogonal avoidance + // (~30-150ms) for giant graphs. + const useCrossingPenalty = edges.length <= 180; + // Unifying nudging preprocessing improves symmetry on smaller graphs but is O(N^3) + // on dense graphs (>90 edges). + const useUnifyingNudging = edges.length <= 90; + + const router = new Avoid.Router(Avoid.OrthogonalRouting); + try { + router.setRoutingParameter(Avoid.shapeBufferDistance, 4); + router.setRoutingParameter(Avoid.idealNudgingDistance, 4); + router.setRoutingParameter(Avoid.segmentPenalty, 25); + router.setRoutingParameter(Avoid.reverseDirectionPenalty, 50); + if (useCrossingPenalty) { + router.setRoutingParameter(Avoid.crossingPenalty, 200); + } + + router.setRoutingOption(Avoid.nudgeOrthogonalSegmentsConnectedToShapes, true); + router.setRoutingOption(Avoid.nudgeSharedPathsWithCommonEndPoint, true); + router.setRoutingOption(Avoid.performUnifyingNudgingPreprocessingStep, useUnifyingNudging); + router.setRoutingOption(Avoid.penaliseOrthogonalSharedPathsAtConnEnds, !mergeEdges); + + const classById = new Map(); + const shapeById = new Map>(); + for (const c of classes) { + classById.set(c.id, c); + const rect = new Avoid.Rectangle( + new Avoid.Point(c.x, c.y), + new Avoid.Point(c.x + c.width, c.y + c.height) + ); + shapeById.set(c.id, new Avoid.ShapeRef(router, rect)); + } + + const classesWithBottomOutgoing = new Set(); + const incomingCounts = new Map(); + for (const e of edges) { + incomingCounts.set(e.targetClassID, (incomingCounts.get(e.targetClassID) ?? 0) + 1); + const srcBox = classById.get(e.sourceClassID); + if (srcBox && sideDirection(e.sourcePoint, srcBox, Avoid) === Avoid.ConnDirDown) { + classesWithBottomOutgoing.add(e.sourceClassID); + } + } + + // Attach target pins on all free sides (preferring top, then left/right, then bottom + // if the class has no outgoing ports on the bottom). Libavoid's nudging fans multiple + // connectors cleanly across each side. + const TARGET_PIN_CLASS = 1; + for (const c of classes) { + if ((incomingCounts.get(c.id) ?? 0) === 0) continue; + const shape = shapeById.get(c.id)!; + const sides: [number, number, number, number][] = [ + [0.5, 0, Avoid.ConnDirUp, 0], + [0, 0.5, Avoid.ConnDirLeft, 15], + [1, 0.5, Avoid.ConnDirRight, 15], + ]; + if (!classesWithBottomOutgoing.has(c.id)) { + sides.push([0.5, 1, Avoid.ConnDirDown, 25]); + } + for (const [xOff, yOff, dir, cost] of sides) { + const pin = new Avoid.ShapeConnectionPin(shape, TARGET_PIN_CLASS, xOff, yOff, true, 0, dir); + pin.setExclusive(false); + if (cost > 0) { + pin.setConnectionCost(cost); + } + } + } + + // Route shorter edges first so local edges keep direct paths and long edges route around them. + const sortedEdges = [...edges].sort((a, b) => { + const da = Math.abs(a.elkTargetPoint.x - a.sourcePoint.x) + Math.abs(a.elkTargetPoint.y - a.sourcePoint.y); + const db = Math.abs(b.elkTargetPoint.x - b.sourcePoint.x) + Math.abs(b.elkTargetPoint.y - b.sourcePoint.y); + return da - db; + }); + + let nextPinClassId = 2; + const connByEdgeId = new Map>(); + for (const e of sortedEdges) { + const srcBox = classById.get(e.sourceClassID); + const srcShape = shapeById.get(e.sourceClassID); + const tgtShape = shapeById.get(e.targetClassID); + if (!srcBox || !srcShape || !tgtShape) continue; + + const srcDir = sideDirection(e.sourcePoint, srcBox, Avoid); + const srcSnap = snapToBoxSide(e.sourcePoint, srcBox, srcDir, Avoid); + const srcPinClass = nextPinClassId++; + const srcPin = new Avoid.ShapeConnectionPin( + srcShape, + srcPinClass, + srcSnap.xOff, + srcSnap.yOff, + true, + 0, + srcDir + ); + srcPin.setExclusive(false); + + const srcEnd = new Avoid.ConnEnd(srcShape, srcPinClass); + const tgtEnd = new Avoid.ConnEnd(tgtShape, TARGET_PIN_CLASS); + const conn = new Avoid.ConnRef(router, srcEnd, tgtEnd); + conn.setRoutingType(Avoid.ConnType_Orthogonal); + if (useCrossingPenalty) { + conn.setHateCrossings(true); + } + connByEdgeId.set(e.edgeID, conn); + } + + router.processTransaction(); + + const routes: [string, RoutePoint[]][] = []; + for (const [edgeID, conn] of connByEdgeId.entries()) { + const poly = conn.displayRoute(); + if (poly && poly.size() >= 2) { + const pts: RoutePoint[] = []; + for (let i = 0; i < poly.size(); i++) { + const p = poly.get_ps(i); + pts.push({ x: p.x, y: p.y }); + } + const simplified = simplifyPoints(pts); + if (simplified.length >= 2) { + routes.push([edgeID, simplified]); + } + } + } + return routes; + } finally { + Avoid.destroy(router); + } +} + +self.onmessage = async (event: MessageEvent) => { + try { + const Avoid = await getAvoid(); + const routes = routeWithAvoid(Avoid, event.data); + const resp: RouteWorkerResponse = { ok: true, routes }; + self.postMessage(resp); + } catch (err) { + const resp: RouteWorkerResponse = { + ok: false, + error: err instanceof Error ? err.message : String(err), + }; + self.postMessage(resp); + } +}; diff --git a/src/vite-env.d.ts b/src/vite-env.d.ts index 11f02fe..e9efc57 100644 --- a/src/vite-env.d.ts +++ b/src/vite-env.d.ts @@ -1 +1,6 @@ /// + +declare module "virtual:libavoid-wasm" { + const src: string; + export default src; +} diff --git a/vite.config.ts b/vite.config.ts index af5d9d0..6cf13b4 100644 --- a/vite.config.ts +++ b/vite.config.ts @@ -1,10 +1,36 @@ -import { resolve } from "path"; -import { defineConfig } from "vite"; +import { readFileSync } from "fs"; +import { createRequire } from "module"; +import { dirname, resolve } from "path"; +import { defineConfig, Plugin } from "vite"; import react from "@vitejs/plugin-react"; +const require = createRequire(import.meta.url); + +function inlineLibavoidWasm(): Plugin { + const virtualId = "virtual:libavoid-wasm"; + const resolvedId = "\0" + virtualId; + return { + name: "inline-libavoid-wasm", + resolveId(id) { + if (id === virtualId) return resolvedId; + }, + load(id) { + if (id === resolvedId) { + const libavoidEntry = require.resolve("libavoid-js"); + const wasmPath = resolve(dirname(libavoidEntry), "libavoid.wasm"); + const base64 = readFileSync(wasmPath).toString("base64"); + return `export default "data:application/wasm;base64,${base64}";`; + } + }, + }; +} + // https://vitejs.dev/config/ export default defineConfig({ - plugins: [react()], + plugins: [react(), inlineLibavoidWasm()], + worker: { + plugins: () => [inlineLibavoidWasm()], + }, base: "./", build: { lib: { diff --git a/yarn.lock b/yarn.lock index 88f2586..59ca9bf 100644 --- a/yarn.lock +++ b/yarn.lock @@ -3400,6 +3400,7 @@ __metadata: eslint-plugin-react-hooks: "npm:^5.1.0-rc-fb9a90fa48-20240614" eslint-plugin-react-refresh: "npm:^0.4.12" globals: "npm:^15.11.0" + libavoid-js: "npm:0.4.5" monaco-editor: "npm:0.52.0" postcss: "npm:8.4.47" react: "npm:18.3.1" @@ -4231,6 +4232,13 @@ __metadata: languageName: node linkType: hard +"libavoid-js@npm:0.4.5": + version: 0.4.5 + resolution: "libavoid-js@npm:0.4.5" + checksum: 10c0/70efa439bea5711d55cc2a42a3d87e74af9d0ea79fc77dd851d3262e66398a2a6b1ebfa94c4f4bbe0ac6d9db05892f5cae318097c92296f132c5cde61e84f8cf + languageName: node + linkType: hard + "lilconfig@npm:^2.1.0": version: 2.1.0 resolution: "lilconfig@npm:2.1.0"