chore: applied feedback from merge request
Removed all the DOM manipulations and created a utils file so npx eslint is happy. Also changed the tests to test the new version of the code. ref: N25B-189
This commit is contained in:
@@ -135,3 +135,22 @@
|
||||
filter: drop-shadow(0 0 0.25rem red);
|
||||
}
|
||||
|
||||
.save-button-like {
|
||||
padding: 3px 10px;
|
||||
background-color: canvas;
|
||||
border-radius: 5pt;
|
||||
outline: dodgerblue solid 2pt;
|
||||
filter: drop-shadow(0 0 0.25rem dodgerblue);
|
||||
}
|
||||
|
||||
a.save-button-like {
|
||||
display: inline-block;
|
||||
text-decoration: none;
|
||||
color: inherit;
|
||||
cursor: pointer;
|
||||
transition: filter 200ms, background-color 200ms;
|
||||
}
|
||||
|
||||
a.save-button-like:hover {
|
||||
filter: drop-shadow(0 0 0.5rem dodgerblue);
|
||||
}
|
||||
@@ -1,133 +1,112 @@
|
||||
import { useRef, useState, useEffect } from "react";
|
||||
import useFlowStore from "../VisProgStores";
|
||||
import styles from "../../VisProg.module.css";
|
||||
import {type Edge } from "@xyflow/react";
|
||||
import type { AppNode } from "../VisProgTypes";
|
||||
import { cleanup } from "@testing-library/react";
|
||||
|
||||
type SavedProject = {
|
||||
version: 1;
|
||||
name: string;
|
||||
savedAt: string; // ISO timestamp
|
||||
nodes: AppNode[];
|
||||
edges: Edge[];
|
||||
};
|
||||
|
||||
|
||||
|
||||
export function makeProjectBlob(name: string, nodes: AppNode[], edges: Edge[]): Blob {
|
||||
const payload = {
|
||||
version: 1,
|
||||
name,
|
||||
savedAt: new Date().toISOString(),
|
||||
nodes,
|
||||
edges,
|
||||
};
|
||||
return new Blob([JSON.stringify(payload, null, 2)], { type: "application/json" });
|
||||
}
|
||||
|
||||
async function saveWithPicker(defaultName: string, blob: Blob) {
|
||||
// @ts-expect-error: not in lib.dom.d.ts everywhere
|
||||
if (window.showSaveFilePicker) {
|
||||
// @ts-expect-error
|
||||
const handle = await window.showSaveFilePicker({
|
||||
suggestedName: `${defaultName}.visprog.json`,
|
||||
types: [{ description: "Visual Program Project", accept: { "application/json": [".visprog.json", ".json"] } }],
|
||||
});
|
||||
const writable = await handle.createWritable();
|
||||
await writable.write(blob);
|
||||
await writable.close();
|
||||
return;
|
||||
}
|
||||
// Fallback if File system API is not supported
|
||||
const url = URL.createObjectURL(blob);
|
||||
const a = document.createElement("a");
|
||||
a.href = url;
|
||||
a.download = `${defaultName}.visprog.json`;
|
||||
a.click();
|
||||
URL.revokeObjectURL(url);
|
||||
}
|
||||
|
||||
async function loadWithPicker(): Promise<SavedProject | null> {
|
||||
try {
|
||||
// @ts-expect-error
|
||||
if (window.showOpenFilePicker) {
|
||||
// @ts-expect-error
|
||||
const [handle] = await window.showOpenFilePicker({
|
||||
multiple: false,
|
||||
types: [{ description: "Visual Program Project", accept: { "application/json": [".visprog.json", ".json", ".txt"] } }],
|
||||
});
|
||||
const file = await handle.getFile();
|
||||
return JSON.parse(await file.text()) as SavedProject;
|
||||
}
|
||||
// Fallback: input
|
||||
return await new Promise<SavedProject | null>((resolve) => {
|
||||
const input = document.createElement("input");
|
||||
input.type = "file";
|
||||
input.accept = ".visprog.json,.json,.txt,application/json,text/plain";
|
||||
input.onchange = async () => {
|
||||
const file = input.files?.[0];
|
||||
if (!file) return resolve(null);
|
||||
try {
|
||||
resolve(JSON.parse(await file.text()) as SavedProject);
|
||||
} catch {
|
||||
resolve(null);
|
||||
}
|
||||
};
|
||||
input.click();
|
||||
});
|
||||
} catch {
|
||||
return null;
|
||||
}
|
||||
}
|
||||
import { makeProjectBlob, type SavedProject } from "../../../../utils/SaveLoad";
|
||||
|
||||
export default function SaveLoadPanel() {
|
||||
const nodes = useFlowStore((s) => s.nodes) as AppNode[];
|
||||
const edges = useFlowStore((s) => s.edges) as Edge[];
|
||||
const nodes = useFlowStore((s) => s.nodes);
|
||||
const edges = useFlowStore((s) => s.edges);
|
||||
const setNodes = useFlowStore((s) => s.setNodes);
|
||||
const setEdges = useFlowStore((s) => s.setEdges);
|
||||
|
||||
const [saveUrl, setSaveUrl] = useState<string | null>(null);
|
||||
|
||||
// ref to the file input
|
||||
const inputRef = useRef<HTMLInputElement | null>(null);
|
||||
// ref to hold the resolver for the currently pending load promise
|
||||
const resolverRef = useRef<((p: SavedProject | null) => void) | null>(null);
|
||||
|
||||
useEffect(() => {
|
||||
return () => {
|
||||
if (resolverRef.current) {
|
||||
resolverRef.current(null);
|
||||
resolverRef.current = null;
|
||||
}
|
||||
};
|
||||
}, []);
|
||||
|
||||
const onSave = async () => {
|
||||
try {
|
||||
const nameGuess =
|
||||
(nodes.find((n) => n.type === "start")?.data?.label as string) || "visual-program";
|
||||
const blob = makeProjectBlob(nameGuess, nodes, edges);
|
||||
await saveWithPicker(nameGuess, blob);
|
||||
} catch (e) {
|
||||
console.error(e);
|
||||
alert("Saving failed. See console.");
|
||||
}
|
||||
const nameGuess = "visual-program";
|
||||
const blob = makeProjectBlob(nameGuess, nodes, edges);
|
||||
const url = URL.createObjectURL(blob);
|
||||
setSaveUrl(url);
|
||||
};
|
||||
|
||||
const onLoad = async () => {
|
||||
try {
|
||||
const proj = await loadWithPicker();
|
||||
const proj = await new Promise<SavedProject | null>((resolve) => {
|
||||
resolverRef.current = resolve;
|
||||
inputRef.current?.click();
|
||||
});
|
||||
// clear stored resolver
|
||||
resolverRef.current = null;
|
||||
|
||||
if (!proj) return;
|
||||
|
||||
if (proj.version !== 1 || !Array.isArray(proj.nodes) || !Array.isArray(proj.edges)) {
|
||||
alert("Invalid project file format.");
|
||||
return;
|
||||
}
|
||||
|
||||
//We clear all the current edges and nodes
|
||||
cleanup();
|
||||
//set all loaded nodes and edges into the VisProg
|
||||
const loadedNodes = proj.nodes as AppNode[];
|
||||
const loadedEdges = proj.edges as Edge[];
|
||||
setNodes(loadedNodes);
|
||||
setEdges(loadedEdges);
|
||||
|
||||
setNodes(proj.nodes);
|
||||
setEdges(proj.edges);
|
||||
} catch (e) {
|
||||
console.error(e);
|
||||
alert("Loading failed. See console.");
|
||||
}
|
||||
};
|
||||
|
||||
// input change handler resolves the onLoad promise with parsed project or null
|
||||
const handleFileChange = async (e: React.ChangeEvent<HTMLInputElement>) => {
|
||||
try {
|
||||
const file = e.target.files?.[0];
|
||||
if (!file) {
|
||||
resolverRef.current?.(null);
|
||||
resolverRef.current = null;
|
||||
return;
|
||||
}
|
||||
try {
|
||||
const text = await file.text();
|
||||
const parsed = JSON.parse(text) as SavedProject;
|
||||
resolverRef.current?.(parsed ?? null);
|
||||
} catch {
|
||||
resolverRef.current?.(null);
|
||||
} finally {
|
||||
// allow re-selecting same file next time
|
||||
if (inputRef.current) inputRef.current.value = "";
|
||||
resolverRef.current = null;
|
||||
}
|
||||
} catch {
|
||||
resolverRef.current?.(null);
|
||||
resolverRef.current = null;
|
||||
}
|
||||
};
|
||||
|
||||
const defaultName = "visual-program";
|
||||
return (
|
||||
<div className={`flex-col gap-lg padding-md ${styles.saveLoadPanel}`}>
|
||||
<div className="description">You can save and load your graph here.</div>
|
||||
<div className={`flex-row gap-lg ${styles.dndNodeContainer}`}>
|
||||
<button onClick={onSave} className={styles.draggableNodePhase}>Save Graph</button>
|
||||
<button onClick={onLoad} className={styles.draggableNodeNorm}>Load Graph</button>
|
||||
<a
|
||||
href={saveUrl ?? "#"}
|
||||
onClick={() => {
|
||||
onSave();
|
||||
}}
|
||||
download={`${defaultName}.json`}
|
||||
className={styles["save-button-like"]}
|
||||
>
|
||||
Save Graph
|
||||
</a>
|
||||
|
||||
<button onClick={onLoad} className={styles.draggableNodeNorm}>
|
||||
Load Graph
|
||||
</button>
|
||||
|
||||
<input
|
||||
ref={inputRef}
|
||||
type="file"
|
||||
accept=".visprog.json,.json,.txt,application/json,text/plain"
|
||||
onChange={handleFileChange}
|
||||
style={{ display: "none" }}
|
||||
aria-hidden
|
||||
/>
|
||||
</div>
|
||||
</div>
|
||||
);
|
||||
|
||||
Reference in New Issue
Block a user