-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathEditorReducer.js
More file actions
111 lines (96 loc) · 3.44 KB
/
EditorReducer.js
File metadata and controls
111 lines (96 loc) · 3.44 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
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
export const initialState = {
uid: crypto.randomUUID(),
tabs: [],
activeTab: null,
parentTabGroupId: null
};
export const editorReducer = (state, action) => {
switch (action.type) {
case "ADD_TAB": {
const { tab, index } = action.payload;
const tabInfo = state.tabs.find(obj => obj.uid === tab.uid);
if (tabInfo) {
console.warn(`Tab with id ${tabInfo.uid} already exists`);
return {
...state,
activeTab: tabInfo
};
}
// Insert tab at specific location if it was provided.
let tabs = [...state.tabs];
if (index !== undefined && index < state.tabs.length) {
tabs.splice(index, 0, tab);
} else {
tabs.push(tab);
}
return {
...state,
tabs: tabs,
activeTab: tab
};
}
case "SET_PARENT_TAB_GROUP_ID": {
return {
...state,
parentTabGroupId: action.payload
};
}
case "SELECT_TAB": {
const tab = state.tabs.find(obj => obj.uid === action.payload);
if (!tab) {
console.error(`Tab with id ${action.payload} not found.`);
return state;
}
return {
...state,
activeTab: tab
};
}
case "CLOSE_TAB": {
const ind = state.tabs.findIndex(obj => obj.uid === action.payload);
if (ind === -1) {
console.warn(`Tab with id ${action.payload} not found.`);
return state;
}
const newTabs = [...state.tabs];
newTabs.splice(ind, 1);
// If active tab is closed, select the next tab if it exists, otherwise select the previous tab.
let activeTab = state.activeTab;
const isActiveTabClosed = state.activeTab && state.activeTab.uid === action.payload;
if (isActiveTabClosed && ind < newTabs.length) {
activeTab = newTabs[Math.max(0, ind)];
} else if (isActiveTabClosed && ind >= newTabs.length) {
activeTab = newTabs.length > 0 ? newTabs[newTabs.length - 1] : null;
}
return {
...state,
tabs: newTabs,
activeTab: activeTab
};
}
case "MOVE_TAB": {
const prevTabs = [...state.tabs];
const { tabId, newIndex } = action.payload;
const oldIndex = prevTabs.findIndex(t => t.uid === tabId);
if (oldIndex === -1) {
console.warn(`Tab with id ${tabId} not found.`);
return state;
}
if (newIndex - 1 === oldIndex || newIndex === oldIndex) return state;
// Remove the tab from its old position and insert it into the new position.
const [tabToMove] = prevTabs.splice(oldIndex, 1);
const adjustedNewIndex = (oldIndex < newIndex) ? newIndex - 1 : newIndex;
prevTabs.splice(adjustedNewIndex, 0, tabToMove);
return {
...state,
tabs: prevTabs
};
}
case "RESET_STATE": {
return initialState;
}
default: {
return state;
}
}
}