aotds-docks/src/stores/ship.js

65 lines
1.5 KiB
JavaScript
Raw Normal View History

2021-06-13 15:36:59 +00:00
import { browser } from "$app/env";
2020-07-19 20:21:28 +00:00
import { readable } from "svelte/store";
import { compose, applyMiddleware } from "redux";
import { calc_ship_req } from "../dux/utils";
2021-05-17 13:48:31 +00:00
let composeEnhancers = compose;
2021-06-13 15:36:59 +00:00
if (browser) {
composeEnhancers = window.__REDUX_DEVTOOLS_EXTENSION_COMPOSE__;
2021-05-17 13:48:31 +00:00
}
2020-07-19 20:21:28 +00:00
import shipDux from "../dux";
export default () => {
2021-06-13 15:36:59 +00:00
let saved;
2021-05-17 13:48:31 +00:00
2021-06-13 15:36:59 +00:00
if (browser) saved = window.localStorage.getItem("aotds-shipyard");
2020-07-19 20:21:28 +00:00
2021-06-13 15:36:59 +00:00
if (saved) {
saved = JSON.parse(saved);
} else {
saved = undefined;
}
2020-07-19 20:21:28 +00:00
const duxStore = shipDux.createStore(saved, (mw) =>
composeEnhancers(applyMiddleware(mw))
);
duxStore.dispatch(
duxStore.actions.set_ship_reqs(calc_ship_req(duxStore.getState()))
);
2021-06-13 15:36:59 +00:00
Object.entries(duxStore.actions).forEach(([type, action]) => {
duxStore.dispatch[type] = (payload) => duxStore.dispatch(action(payload));
2020-07-19 20:21:28 +00:00
});
let previous = undefined;
2021-06-13 15:36:59 +00:00
duxStore.subscribe(() => {
2020-07-19 20:21:28 +00:00
let current = duxStore.getState();
2021-06-13 15:36:59 +00:00
if (previous === current) return;
previous = current;
2020-07-19 20:21:28 +00:00
2021-06-13 15:36:59 +00:00
if (browser)
window.localStorage.setItem("aotds-shipyard", JSON.stringify(current));
2020-07-19 20:21:28 +00:00
});
const state = readable(duxStore.getState(), (set) =>
duxStore.subscribe(() => {
set(duxStore.getState());
})
);
2021-06-13 15:36:59 +00:00
const dispatch_action = (action, payload) =>
duxStore.dispatch[action](payload);
2020-07-19 20:21:28 +00:00
return {
subscribe: state.subscribe,
dispatch: duxStore.dispatch,
actions: duxStore.actions,
selectors: duxStore.selectors,
2021-06-13 15:36:59 +00:00
dispatch_action,
2020-07-19 20:21:28 +00:00
};
};