Files
next-ai-draw-io/contexts/diagram-context.tsx
2025-03-26 00:30:00 +00:00

87 lines
2.5 KiB
TypeScript

"use client";
import React, { createContext, useContext, useRef, useState } from "react";
import type { DrawIoEmbedRef } from "react-drawio";
import { extractDiagramXML } from "@/app/extract_xml";
interface DiagramContextType {
chartXML: string;
latestSvg: string;
diagramHistory: { svg: string; xml: string }[];
loadDiagram: (chart: string) => void;
handleExport: () => void;
resolverRef: React.MutableRefObject<((value: string) => void) | null>;
drawioRef: React.MutableRefObject<DrawIoEmbedRef | null>;
handleDiagramExport: (data: any) => void;
}
const DiagramContext = createContext<DiagramContextType | undefined>(undefined);
export function DiagramProvider({ children }: { children: React.ReactNode }) {
const [chartXML, setChartXML] = useState<string>("");
const [latestSvg, setLatestSvg] = useState<string>("");
const [diagramHistory, setDiagramHistory] = useState<
{ svg: string; xml: string }[]
>([]);
const drawioRef = useRef<DrawIoEmbedRef>(null);
const resolverRef = useRef<((value: string) => void) | null>(null);
const handleExport = () => {
if (drawioRef.current) {
drawioRef.current.exportDiagram({
format: "xmlsvg",
});
}
};
const loadDiagram = (chart: string) => {
if (drawioRef.current) {
drawioRef.current.load({
xml: chart,
});
}
};
const handleDiagramExport = (data: any) => {
const extractedXML = extractDiagramXML(data.data);
setChartXML(extractedXML);
setLatestSvg(data.data);
setDiagramHistory((prev) => [
...prev,
{
svg: data.data,
xml: extractedXML,
},
]);
if (resolverRef.current) {
resolverRef.current(extractedXML);
resolverRef.current = null;
}
};
return (
<DiagramContext.Provider
value={{
chartXML,
latestSvg,
diagramHistory,
loadDiagram,
handleExport,
resolverRef,
drawioRef,
handleDiagramExport,
}}
>
{children}
</DiagramContext.Provider>
);
}
export function useDiagram() {
const context = useContext(DiagramContext);
if (context === undefined) {
throw new Error("useDiagram must be used within a DiagramProvider");
}
return context;
}