import { defineStore } from 'pinia'; import { SAVE_KEY_NAME } from '@/constants/constants.js'; // nodePositions 結構 { // graphId: [{ // id, // position: { // x, // y, // } // }] // } interface Position { x: number; y: number; } interface Node { id: string; position: Position; } interface NodePositions { [graphId: string]: Node[]; } export default defineStore('useCytoscapeStore', { state: () => ({ nodePositions: {} as NodePositions, currentGraphId: "", }), actions: { /** * 儲存或更新單個節點的位置資訊。 * @param {string} id * @param {object} position {x, y} position有兩個值,x與y */ saveNodePosition(nodeId: string, position: NodePosition) { // 若是資訊曾經存在這張圖於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 { console.log('aaaa this.nodePositions[this.currentGraphId]',this.nodePositions[this.currentGraphId] ); this.nodePositions[this.currentGraphId].push({id: nodeId, position: position}); } } else { this.nodePositions[this.currentGraphId] = []; this.nodePositions[this.currentGraphId].push({id: nodeId, position: position}); localStorage.setItem(SAVE_KEY_NAME, JSON.stringify(this.nodePositions)); } console.log('', ); this.savePositionsToStorage(); }, /** * 從本地存儲中加載節點位置資訊。 */ loadPositionsFromStorage() { if (localStorage.getItem(SAVE_KEY_NAME)) { this.nodePositions[this.currentGraphId] = JSON.parse(localStorage.getItem(SAVE_KEY_NAME))[this.currentGraphId]; } }, /** * 將節點位置資訊儲存到本地存儲中。 */ savePositionsToStorage() { localStorage.setItem(SAVE_KEY_NAME, JSON.stringify(this.nodePositions)); }, setCurrentGraphId(currentGraphId: string) { this.currentGraphId = currentGraphId; this.nodePositions = {[this.currentGraphId]: []}; }, }, });