mirror of
https://github.com/DayuanJiang/next-ai-draw-io.git
synced 2026-01-02 14:22:28 +08:00
refactor: extract all states to diagram-context.
This commit is contained in:
86
contexts/diagram-context.tsx
Normal file
86
contexts/diagram-context.tsx
Normal file
@@ -0,0 +1,86 @@
|
||||
"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;
|
||||
}
|
||||
Reference in New Issue
Block a user