Skip to content

Commit

Permalink
generics
Browse files Browse the repository at this point in the history
  • Loading branch information
brauliodiez committed Jan 21, 2024
1 parent 4f3acda commit 8d28485
Show file tree
Hide file tree
Showing 2 changed files with 12 additions and 12 deletions.
3 changes: 2 additions & 1 deletion src/core/undo-redo/history-manager.business.ts
Original file line number Diff line number Diff line change
@@ -1,5 +1,6 @@
// TODO Add Unit tests to this Undo/Redo helpers

// #162
// https://github.com/Lemoncode/mongo-modeler/issues/162
export function addSnapshotToHistory<T>(
history: T[],
newSnapshot: T,
Expand Down
21 changes: 10 additions & 11 deletions src/core/undo-redo/history-manager.hook.ts
Original file line number Diff line number Diff line change
@@ -1,37 +1,36 @@
import { useState, useRef } from 'react';
import { DatabaseSchemaVm } from '../providers';
import {
addSnapshotToHistory,
canUndo,
canRedo,
performUndo,
performRedo,
} from './history-manager.business';

const MAX_HISTORY_LENGTH = 20;

export const useHistoryManager = (initialState: DatabaseSchemaVm) => {
const [canvasSchema, setCanvasSchema] =
useState<DatabaseSchemaVm>(initialState);
const historyRef = useRef<DatabaseSchemaVm[]>([initialState]);
export const useHistoryManager = <T>(initialState: T) => {
const [currentState, setCurrentState] = useState<T>(initialState);
const historyRef = useRef<T[]>([initialState]);
const currentIndexRef = useRef<number>(0);

const addSnapshot = (newSchema: DatabaseSchemaVm) => {
const addSnapshot = (newState: T) => {
const [newHistory, newIndex] = addSnapshotToHistory(
historyRef.current,
newSchema,
newState,
currentIndexRef.current,
MAX_HISTORY_LENGTH
);
historyRef.current = newHistory;
currentIndexRef.current = newIndex;
setCanvasSchema(newSchema);
setCurrentState(newState);
};

const undo = () => {
const newIndex = performUndo(currentIndexRef.current);
if (newIndex !== currentIndexRef.current) {
currentIndexRef.current = newIndex;
setCanvasSchema(historyRef.current[newIndex]);
setCurrentState(historyRef.current[newIndex]);
}
};

Expand All @@ -42,12 +41,12 @@ export const useHistoryManager = (initialState: DatabaseSchemaVm) => {
);
if (newIndex !== currentIndexRef.current) {
currentIndexRef.current = newIndex;
setCanvasSchema(historyRef.current[newIndex]);
setCurrentState(historyRef.current[newIndex]);
}
};

return {
canvasSchema,
currentState,
addSnapshot,
getCurrentState: () => historyRef.current[currentIndexRef.current],
undo,
Expand Down

0 comments on commit 8d28485

Please sign in to comment.