Basic scaffold for managing equiped items
This commit is contained in:
64
src/lib/state.ts
Normal file
64
src/lib/state.ts
Normal file
@@ -0,0 +1,64 @@
|
||||
import type { EquipedItem, Item, ItemId } from "./types";
|
||||
|
||||
export type State = {
|
||||
equipedItems: EquipedItem[];
|
||||
bisList: ItemId[];
|
||||
};
|
||||
|
||||
export type Action =
|
||||
| {
|
||||
action: "equipItem";
|
||||
item: Item;
|
||||
}
|
||||
| {
|
||||
action: "unequipItem";
|
||||
item: Item;
|
||||
};
|
||||
|
||||
export const reducer = (state: State, action: Action): State => {
|
||||
switch (action.action) {
|
||||
case "equipItem":
|
||||
return {
|
||||
...state,
|
||||
equipedItems: [
|
||||
...state.equipedItems,
|
||||
{
|
||||
id: action.item.id,
|
||||
quality: "champion", // Default quality, can be changed later
|
||||
},
|
||||
],
|
||||
};
|
||||
case "unequipItem":
|
||||
return {
|
||||
...state,
|
||||
equipedItems: state.equipedItems.filter(
|
||||
(item) => item.id !== action.item.id,
|
||||
),
|
||||
};
|
||||
}
|
||||
};
|
||||
|
||||
export type LoadingAction<S> = {
|
||||
action: "loadState";
|
||||
state: S;
|
||||
};
|
||||
|
||||
function isLoadingAction<A, S>(
|
||||
action: A | LoadingAction<S>,
|
||||
): action is LoadingAction<S> {
|
||||
return (action as LoadingAction<S>).action === "loadState";
|
||||
}
|
||||
|
||||
export const withLoadingAction =
|
||||
<S, A>(reducer: (state: S, action: A) => S) =>
|
||||
(state: S | "loading", action: A | LoadingAction<S>): S | "loading" => {
|
||||
if (state !== "loading" && !isLoadingAction(action)) {
|
||||
return reducer(state, action);
|
||||
}
|
||||
|
||||
if (state === "loading" && isLoadingAction(action)) {
|
||||
return action.state;
|
||||
}
|
||||
|
||||
return state;
|
||||
};
|
||||
Reference in New Issue
Block a user