svg-layout-designer-react/src/utils/saveload.ts
2022-10-19 10:09:09 +02:00

61 lines
2 KiB
TypeScript

/* eslint-disable @typescript-eslint/naming-convention */
import { IEditorState } from '../Interfaces/IEditorState';
import { IHistoryState } from '../Interfaces/IHistoryState';
import { IContainerModel } from '../Interfaces/IContainerModel';
import { ISymbolModel } from '../Interfaces/ISymbolModel';
/**
* Revive the Editor state
* by setting the containers references to their parent
* @param editorState Editor state
*/
export function Revive(editorState: IEditorState): void {
const history = editorState.history;
// restore last step
editorState.historyCurrentStep = history.length - 1;
// restore the parents and the selected container
ReviveHistory(history);
}
export function ReviveHistory(history: IHistoryState[]): void {
for (const state of history) {
ReviveState(state);
}
}
export function ReviveState(state: IHistoryState): void {
if (state.mainContainer === null || state.mainContainer === undefined) {
return;
}
const symbols: Array<{ Key: string, Value: ISymbolModel }> = (state.symbols) as any;
state.symbols = new Map(symbols.map(({ Key, Value }) => [Key, Value]));
for (const symbol of state.symbols.values()) {
symbol.linkedContainers = new Set(symbol.linkedContainers);
}
const containers: Array<{ Key: string, Value: IContainerModel }> = (state.containers) as any;
state.containers = new Map(containers.map(({ Key, Value }) => [Key, Value]));
}
export function GetCircularReplacer(): (key: any, value: object | Map<string, any> | null) => object | null | undefined {
return (key: any, value: object | null) => {
if (key === 'containers') {
return [...(value as Map<string, any>).entries()]
.map(([Key, Value]: [string, any]) => ({ Key, Value }));
}
if (key === 'symbols') {
return [...(value as Map<string, any>).entries()]
.map(([Key, Value]: [string, any]) => ({ Key, Value }));
}
if (key === 'linkedContainers') {
return Array.from(value as Set<string>);
}
return value;
};
}