Repository navigation
Expand file tree
/
Copy pathhistory.ts
More file actions
54 lines (49 loc) · 1.48 KB
/
Copy pathhistory.ts
File metadata and controls
54 lines (49 loc) · 1.48 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
import type { ModelDatabase } from "./types";
const MAX_HISTORY_ENTRIES = 20;
export type DatabaseHistory = {
past: ModelDatabase[];
present: ModelDatabase;
future: ModelDatabase[];
};
export type DatabaseHistoryAction =
| { type: "commit"; database: ModelDatabase }
| { type: "undo" }
| { type: "redo" }
| { type: "reset"; database: ModelDatabase };
export function createDatabaseHistory(database: ModelDatabase): DatabaseHistory {
return { past: [], present: database, future: [] };
}
export function databaseHistoryReducer(
history: DatabaseHistory,
action: DatabaseHistoryAction,
): DatabaseHistory {
switch (action.type) {
case "commit":
if (action.database === history.present) return history;
return {
past: [...history.past, history.present].slice(-MAX_HISTORY_ENTRIES),
present: action.database,
future: [],
};
case "undo": {
const previous = history.past.at(-1);
if (!previous) return history;
return {
past: history.past.slice(0, -1),
present: previous,
future: [history.present, ...history.future].slice(0, MAX_HISTORY_ENTRIES),
};
}
case "redo": {
const next = history.future[0];
if (!next) return history;
return {
past: [...history.past, history.present].slice(-MAX_HISTORY_ENTRIES),
present: next,
future: history.future.slice(1),
};
}
case "reset":
return createDatabaseHistory(action.database);
}
}