All files / src/store/features/scriptEventDefs scriptEventDefsState.ts

42.31% Statements 11/26
0% Branches 0/15
0% Functions 0/9
37.5% Lines 9/24

Press n or j to go to the next uncovered block, b, p or k for the previous block.

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 7421x     21x               21x                   21x                                         21x                                           21x     21x     21x   21x  
import { PayloadAction, createSlice } from "@reduxjs/toolkit";
import { ScriptEventDefs } from "shared/lib/scripts/scriptDefHelpers";
import { RootState } from "store/configureStore";
import projectActions from "store/features/project/projectActions";
 
export interface ScriptEventsState {
  lookup: ScriptEventDefs;
  lookupWithPresets: ScriptEventDefs;
  loaded: boolean;
}
 
export const initialState: ScriptEventsState = {
  lookup: {},
  lookupWithPresets: {},
  loaded: false,
};
 
// Script Events Defs can optionally include a number of preset values
// this function creates a lookup containing all the script event defs
// and also an entry for every one of their presets. Allowing components like
// AddScriptEventMenu to require very little about the concept of presets
const buildPresets = (lookup: ScriptEventDefs): ScriptEventDefs => {
  return Object.values(lookup).reduce(
    (memo, def) => {
      Iif (def && def.presets) {
        def.presets.forEach((p) => {
          memo[`${def.id}::${p.id}`] = {
            ...def,
            id: `${def.id}::${p.id}`,
            name: p.name,
            description: p.description ?? def.description,
            groups: p.groups ?? def.groups,
            subGroups: p.subGroups ?? def.subGroups,
          };
        });
      }
      return memo;
    },
    { ...lookup }
  );
};
 
const scriptEventDefsSlice = createSlice({
  name: "scriptEventDefs",
  initialState,
  reducers: {
    setScriptEventDefs: (state, action: PayloadAction<ScriptEventDefs>) => {
      state.lookup = action.payload;
      state.lookupWithPresets = buildPresets(state.lookup);
      state.loaded = true;
    },
  },
  extraReducers: (builder) =>
    builder
      .addCase(projectActions.loadProject.pending, (state, _action) => {
        state.loaded = false;
      })
      .addCase(projectActions.loadProject.fulfilled, (state, action) => {
        state.lookup = action.payload.scriptEventDefs;
        state.lookupWithPresets = buildPresets(state.lookup);
        state.loaded = true;
      }),
});
 
export const selectScriptEventDefs = (state: RootState) =>
  state.scriptEventDefs.lookup;
 
export const selectScriptEventDefsWithPresets = (state: RootState) =>
  state.scriptEventDefs.lookupWithPresets;
 
export const { actions, reducer } = scriptEventDefsSlice;
 
export default reducer;