-
Notifications
You must be signed in to change notification settings - Fork 0
/
store.js
74 lines (69 loc) · 1.93 KB
/
store.js
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
const createStoreWorker = (path, reducer, initialState) => {
const worker = new Worker(path);
let state = initialState;
const subscribers = new Set();
const getState = () => state;
const reduceAndNotify = action => {
state = reducer(state, action);
for (let callback of subscribers) callback({ dispatch, getState, action });
};
const dispatch = (action, isAsync = true) => {
if (isAsync) {
worker.postMessage(action);
} else {
reduceAndNotify(action);
}
};
const subscribe = callback => {
subscribers.add(callback);
const unsubscribe = () => subscribers.delete(callback);
return unsubscribe;
};
worker.addEventListener("message", function handleWorkerMessage(e) {
reduceAndNotify(e.data);
});
return { dispatch, getState, subscribe };
};
const initialState = {
debug: window.location.search.includes('debug=1'),
global: true,
ignoreCase: false,
instructions: null,
multiline: false,
regExpString: "[a-z]{4,}",
testString:
"This is a string that will be highlighted when your regular expression matches something.",
testStringPanelScrollTop: 0
};
const reducer = (state, action) => {
switch (action.type) {
case "PUBLISH":
return { ...state, ...action.state };
case "INPUT_CHANGED":
return { ...state, [action.name]: action.value };
default:
return state;
}
};
export const { dispatch, getState, subscribe } = createStoreWorker(
"./store-worker.js",
reducer,
initialState
);
const MAIN_THREAD_FIELDS = new Set(["testStringPanelScrollTop"]);
const WORKER_FIELDS = new Set(
Object.keys(initialState).filter(name => !MAIN_THREAD_FIELDS.has(name))
);
// send worker fields
dispatch({
type: "INIT",
initialState: Object.entries(initialState).reduce(
(storeWorkerInitialState, [name, value]) => {
if (WORKER_FIELDS.has(name)) {
storeWorkerInitialState[name] = value;
}
return storeWorkerInitialState;
},
{}
)
});