diff --git a/src/lib/History/history.ts b/src/lib/History/history.ts index bf8189d2..368c3dc1 100644 --- a/src/lib/History/history.ts +++ b/src/lib/History/history.ts @@ -1,4 +1,4 @@ -import { derived, Readable, Writable, writable } from 'svelte/store'; +import { derived, Readable, Writable, writable, get } from 'svelte/store'; const MAX_AUTO_HISTORY_LENGTH = 10; @@ -23,3 +23,17 @@ export const addHistoryEntry = (entry: HistoryEntry): void => { return [entry, ...entries]; }); }; + +export const clearHistoryData = (time?: Date): void => { + (get(autoHistoryMode) ? autoHistoryStore : manualHistoryStore).update((entries) => + entries.filter((entry) => time && entry.time != time) + ); +}; + +export const getPreviousState = (auto: boolean): string => { + const entries = get(auto ? autoHistoryStore : manualHistoryStore); + if (entries.length > 0) { + return JSON.stringify(entries[0].state); + } + return ''; +}; diff --git a/src/lib/History/index.svelte b/src/lib/History/index.svelte index d52b25d9..0f7eb21c 100644 --- a/src/lib/History/index.svelte +++ b/src/lib/History/index.svelte @@ -2,8 +2,15 @@ import Tabs from '$lib/Tabs/index.svelte'; import Card from '$lib/Card/index.svelte'; import { codeStore, getStateString } from '$lib/Util/state'; - import { addHistoryEntry, autoHistoryMode, historyStore } from './history'; - import { notify } from '$lib/Util/notify'; + import { + addHistoryEntry, + autoHistoryMode, + clearHistoryData, + getPreviousState, + historyStore + } from './history'; + import { notify, prompt } from '$lib/Util/notify'; + import { onMount } from 'svelte'; const HISTORY_SAVE_INTERVAL: number = 60000; @@ -21,30 +28,38 @@ } ]; - const previousState = {}; - - setInterval(() => { - saveHistory(true); - }, HISTORY_SAVE_INTERVAL); - const saveHistory = (auto = false) => { - const currentState = getStateString(); - if (previousState[`${auto}`] !== currentState) { + const currentState: string = getStateString(); + const previousState: string = getPreviousState(auto); + if (previousState !== currentState) { addHistoryEntry({ state: $codeStore, time: new Date(), name: 'test', auto }); - previousState[`${auto}`] = currentState; } else if (!auto) { notify('State already saved.'); } }; - const restoreHistory = (state: State): any => { + const clearHistory = (date?: Date): void => { + if (!date && !prompt('Clear all saved items?')) { + return; + } + clearHistoryData(date); + }; + + const restoreHistory = (state: State): void => { codeStore.set({ ...state, updateEditor: true, updateDiagram: true }); }; + + onMount(() => { + autoHistoryMode.set(false); + setInterval(() => { + saveHistory(true); + }, HISTORY_SAVE_INTERVAL); + }); @@ -55,14 +70,18 @@ + -