feature: remember node positions after refreshing pages

This commit is contained in:
Cindy Chang
2024-07-01 10:39:53 +08:00
parent 69a3f27cb2
commit 24ccdd47ae
5 changed files with 60 additions and 40 deletions

View File

@@ -1,60 +1,51 @@
import { el } from 'date-fns/locale';
import { defineStore } from 'pinia';
// interface NodePosition {
// id: string;
// position: { x: number; y: number };
// graphId: string;
// }
import { SAVE_KEY_NAME } from '@/constants/constants.js';
import { printObject } from '@/utils/jsUtils';
export default defineStore('useCytoscapeStore', {
state: () => ({
nodePositions: [],
nodePositions: {},
currentGraphId: "",
}),
actions: {
/**
* 儲存或更新單個節點的位置資訊。
* @param {string} id
* @param {object} position {x, y}
* @param {string} graphId
* @param {object} position {x, y} position有兩個值x與y
*/
saveNodePosition(id, position) {
const existingNode = this.nodePositions.find(node => node.id === id && node.graphId === this.currentGraphId);
if (existingNode) { // 如果存在,更新位置資訊
existingNode.position = position;
} else { // 如果不存在,新增一個新的位置資訊
this.nodePositions.push({
id,
position,
graphId: this.currentGraphId,
});
saveNodePosition(nodeId, position) {
// 若是資訊曾經存在這張圖於localStorage中
if (localStorage.getItem(SAVE_KEY_NAME) && JSON.parse(localStorage.getItem(SAVE_KEY_NAME))[this.currentGraphId]) {
const nodeToSave = this.nodePositions[this.currentGraphId].find(node => node.id === nodeId);
if(nodeToSave) {
nodeToSave.position = position;
} else {
this.nodePositions[this.currentGraphId] = [... this.nodePositions[this.currentGraphId],
{id: nodeId, position: position}]
}
}
},
/**
* 根據節點 ID 獲取該節點的位置資訊
* @param {string} id
* @returns
*/
getNodePosition(id) { // 返回該節點的位置資訊,如果不存在則返回 undefined
return this.nodePositions.find(node => node.id === id)?.position;
this.savePositionsToStorage();
},
/**
* 從本地存儲中加載節點位置資訊。
*/
loadPositionsFromStorage() {
const storedPositions = localStorage.getItem('cy-node-positions');
if (storedPositions) {
this.nodePositions = JSON.parse(storedPositions);
if (localStorage.getItem(SAVE_KEY_NAME)) {
this.nodePositions[this.currentGraphId] = JSON.parse(localStorage.getItem(SAVE_KEY_NAME))[this.currentGraphId];
}
},
/**
* 將節點位置資訊儲存到本地存儲中。
*/
savePositionsToStorage() {
localStorage.setItem('cy-node-positions', JSON.stringify(this.nodePositions));
localStorage.setItem(SAVE_KEY_NAME, JSON.stringify(this.nodePositions));
},
setCurrentGraphId(currentGraphId) {
this.currentGraphId = currentGraphId;
this.nodePositions[currentGraphId] = [];
},
},
});