85 lines
2.4 KiB
TypeScript
85 lines
2.4 KiB
TypeScript
import { defineStore } from 'pinia';
|
||
|
||
import { SAVE_KEY_NAME } from '@/constants/constants.js';
|
||
|
||
// nodePositions[graphId][direction][id]
|
||
// nodePositions[graphId][position]
|
||
|
||
|
||
interface Position {
|
||
x: number;
|
||
y: number;
|
||
}
|
||
|
||
interface Node {
|
||
id: string;
|
||
position: Position;
|
||
}
|
||
|
||
interface NodePositions {
|
||
[direction: string]: {
|
||
[graphId: string]: Node[];
|
||
}
|
||
}
|
||
|
||
|
||
export const useCytoscapeStore = defineStore('cytoscapeStore', {
|
||
state: () => ({
|
||
nodePositions: {} as NodePositions,
|
||
currentGraphId: "",
|
||
}),
|
||
actions: {
|
||
/**
|
||
* 儲存或更新單個節點的位置資訊。
|
||
* @param {string} id
|
||
* @param {object} position {x, y} position有兩個值,x與y
|
||
* @param {string} direction 'TB' 'LR'
|
||
*/
|
||
saveNodePosition(nodeId: string, position: Position, direction: string) {
|
||
// 若是資訊曾經存在這張圖於localStorage中
|
||
if (localStorage.getItem(SAVE_KEY_NAME)) {
|
||
const nodeToSave = this.nodePositions[this.currentGraphId][direction]
|
||
.find(node => node.id === nodeId);
|
||
if (nodeToSave) {
|
||
nodeToSave.position = position;
|
||
} else {
|
||
this.nodePositions[this.currentGraphId][direction]
|
||
.push({ id: nodeId, position: position });
|
||
}
|
||
} else {
|
||
this.nodePositions[this.currentGraphId][direction] = [];
|
||
this.nodePositions[this.currentGraphId][direction]
|
||
.push({ id: nodeId, position: position });
|
||
localStorage.setItem(SAVE_KEY_NAME, JSON.stringify(this.nodePositions));
|
||
}
|
||
this.savePositionsToStorage();
|
||
},
|
||
/**
|
||
* 從本地存儲中加載節點位置資訊。
|
||
* @param {string} direction 'TB' TopBotom; 'LR' LeftRight
|
||
*/
|
||
loadPositionsFromStorage(direction: string) {
|
||
if (localStorage.getItem(SAVE_KEY_NAME) &&
|
||
JSON.parse(
|
||
localStorage.getItem(SAVE_KEY_NAME))[this.currentGraphId]) {
|
||
this.nodePositions[this.currentGraphId][direction] = JSON.parse(
|
||
localStorage.getItem(SAVE_KEY_NAME))[this.currentGraphId][direction];
|
||
}
|
||
},
|
||
/**
|
||
* 將節點位置資訊儲存到本地存儲中。
|
||
*/
|
||
savePositionsToStorage() {
|
||
localStorage.setItem(SAVE_KEY_NAME, JSON.stringify(this.nodePositions));
|
||
},
|
||
setCurrentGraphId(currentGraphId: string) {
|
||
this.currentGraphId = currentGraphId;
|
||
this.nodePositions = {
|
||
[this.currentGraphId]: {
|
||
'TB': [],
|
||
'LR': [],
|
||
}
|
||
};
|
||
},
|
||
},
|
||
}); |