Reputation: 21
I want to transfer the NewDiagramName (text that the user entered into the prompt ) from MyDiagrams.jsx to EditDiagram.jsx . And to use NewDiagramName in EditDiagram.jsx in handleSave function to save the title as the diagram title here:
const response = await diagramService.createDiagram({
title: NewDiagramName,
description: "description",
links,
cells,
});
React,JSX,JOINTJS library,VSCODE.
MyDiagrams.jsx file:
import { useEffect, useState } from "react";
import { Link } from "react-router-dom";
import { diagramService } from "../Services/diagram.service";
import plusImg from "../../images/plus.png";
import "../Styles/MyDiagrams.css";
function MyDiagrams() {
const [myDiagrams, setMyDiagrams] = useState([]);
const [NewDiagramName, setNewDiagramName] = useState(""); // Use state to store NewDiagramName
const diagramNamePrompt = useEffect(() => {
loadDiagrams();
}, []);
const loadDiagrams = async () => {
const diagrams = await diagramService.getAllDiagrams();
setMyDiagrams(diagrams);
};
const handleClick = () => {
const enteredName = prompt("Enter name to the new diagram:");
setNewDiagramName(enteredName); // Set the value using useState
};
return (
<div>
<nav className="navbar">
<h2 className="title">Your diagrams</h2>
</nav>
{myDiagrams.map((diagram) => (
<Link
className="mlink"
key={diagram.id}
to={"/edit-diagram/" + diagram.id}
>
<div>{diagram.title}</div>
</Link>
))}
<Link to={`/create-diagram/${NewDiagramName}`} onClick={handleClick}>
<img src={plusImg} alt="Add New" />
</Link>
</div>
);
}
export default MyDiagrams;
EditDiagram.jsx file:
import { useEffect, useMemo, useRef, useState } from "react";
import { useParams } from "react-router-dom";
import DiagramMenu from "../Components/DiagramMenu";
import { diagramService } from "../Services/diagram.service";
import * as joint from "jointjs";
// Create a new graph
// const graph = new joint.dia.Graph();
function EditDiagram() {
const [paper, setPaper] = useState(new joint.dia.Paper());
const [historyStack, setHistoryStack] = useState([]);
const paperRef = useRef();
const graph = useMemo(() => new joint.dia.Graph(), []);
const params = useParams();
useEffect(() => {
const loadDiagram = async () => {
if (params.diagramId) {
const diagramData = await diagramService.getDiagramById(
params.diagramId
);
console.log(diagramData);
// Update the graph with diagramData
diagramData && buildDiagram(diagramData);
}
};
console.log(params.diagramId);
// diagramService.getDiagramById(diagramId)
// TODO
loadDiagram();
}, []);
const buildDiagram = (diagramData) => {
const cells = diagramData.cells.map(buildDiagramCell);
console.log(cells);
graph.fromJSON({ cells });
};
const buildDiagramCell = (cellData) => ({
id: cellData.id,
type: "standard.Rectangle",
position: {
x: cellData.positionX,
y: cellData.positionY,
},
size: {
width: cellData.width,
height: cellData.height,
},
attrs: {
body: {
stroke: "rgb(74, 72, 72)",
fill: cellData.color,
angle: 5,
},
label: {
fill: "rgb(74, 72, 72)",
text: cellData.content,
},
},
});
// Create a new paper
useEffect(() => {
const paper = new joint.dia.Paper({
el: paperRef.current,
model: graph,
width: 1500,
height: 3000,
gridSize: 1,
});
paper.on("cell:pointerclick", (cellView, evt, x, y) => {
console.log("Cell clicked.");
const selectedCell = cellView.model;
paper.selectedCell = selectedCell;
if (linkOn) {
cellsForLinking.push(selectedCell);
if (cellsForLinking.length === 2) {
link(cellsForLinking[0], cellsForLinking[1]);
cellsForLinking = [];
}
}
});
paper.on("cell:pointerdblclick", (cellView) => {
const model = cellView.model;
Swal.fire({
title: "Edit Text",
input: "textarea",
inputAttributes: {
rows: 4, // Set the number of rows to allow multi-line input
},
inputValue: model.attr("label/text"), // Populate the input field with existing text
showCancelButton: true,
confirmButtonText: "Save",
}).then((result) => {
if (result.isConfirmed && result.value !== null) {
model.attr("label/text", result.value);
const textWidth = result.value.length * 7;
var textheight = result.value.length * 2;
if (textheight < model.attributes.size.height) {
textheight = model.attributes.size.height;
}
model.resize(textWidth, textheight);
//model.attributes.size.height
}
saveToHistory();
});
});
paper.on("cell:pointerdown", (cellView, evt, x, y) => {
const toolRemove = $(evt.target).parents(".tool-remove")[0];
if (toolRemove) {
if (!confirm("Shall I remove this link?")) {
cellView.options.interactive = false;
_.defer(function () {
cellView.options.interactive = true;
});
}
}
});
paper.on("blank:pointerdblclick", () => {
resetAll(this);
info.attr("body/visibility", "hidden");
info.attr("label/visibility", "hidden");
this.drawBackground({
color: "orange",
});
saveToHistory();
});
paper.on("cell:pointerdblclick", (cellView) => {
var isElement = cellView.model.isElement();
var message = (isElement ? "Element" : "Link") + " clicked";
info.attr("label/text", message);
info.attr("body/visibility", "visible");
info.attr("label/visibility", "visible");
saveToHistory();
});
paper.setInteractivity({ stopDelegation: false });
setPaper(paper);
return () => {
paper.off("cell:pointerclick");
paper.off("cell:pointerdblclick");
paper.off("cell:pointerdown");
paper.off("blank:pointerdblclick");
paper.off("cell:pointerdblclick");
paper.remove();
};
}, []);
const handleSave = async () => {
const cells = graph.getCells().map((cell) => ({
positionX: cell.position().x,
positionY: cell.position().y,
serialNumber: 66, // TODO
width: cell.getBBox().width, // TODO
height: cell.getBBox().height, // TODO
color: cell.attr.fill, // find the cell color
content: cell.content,
startIndex: 1,
endIndex: 5435,
}));
const links = graph.getLinks().map((link) => {
if (typeof link.id === "string") {
return {
content: link.label(0).attrs.text.text, // TODO
fromCellId: link.source().id,
toCellId: link.target().id,
};
}
return {
id: link.id,
content: link.label(0).attrs.text.text, // TODO
fromCellId: link.source().id,
toCellId: link.target().id,
};
});
const response = await diagramService.createDiagram({
title: "TITLE",
description: "description",
links,
cells,
});
console.log("AFTER CREATE");
};
/*Function to create a cell*/
const handleCreateCell = () => {
const randomX = Math.floor(Math.random() * 1001);
const randomY = Math.floor(Math.random() * 651);
const rect = new joint.shapes.standard.Rectangle();
rect.position(randomX, randomY);
rect.resize(150, 40); // width, height
rect.attr({
body: {
fill: "white",
stroke: "rgb(74, 72, 72)",
strokeWidth: 2,
},
label: {
text: "",
fill: "rgb(74, 72, 72)",
},
});
rect.addTo(graph);
saveToHistory();
};
/*Function to save the current graph state to the history stack*/
const saveToHistory = () => {
const currentState = JSON.stringify(graph.toJSON());
setHistoryStack((prev) => [...prev, currentState]);
};
return (
<div>
<DiagramMenu
onSave={handleSave}
onCreate={handleCreateCell}
/>
<div id="myholder" ref={paperRef}></div>
<div className="canvas-container">
<div id="secondmyholder"></div>
</div>
</div>
);
}
export default EditDiagram;
I tried using params but I did not achieve my desired achievment.
Upvotes: 1
Views: 36