code-slice.ts 1.4 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758
  1. import { createSlice } from "@reduxjs/toolkit";
  2. export interface FileState {
  3. path: string;
  4. savedContent: string;
  5. unsavedContent: string;
  6. }
  7. export const initialState = {
  8. code: "",
  9. path: "",
  10. refreshID: 0,
  11. fileStates: [] as FileState[],
  12. };
  13. export const codeSlice = createSlice({
  14. name: "code",
  15. initialState,
  16. reducers: {
  17. setCode: (state, action) => {
  18. state.code = action.payload;
  19. },
  20. setActiveFilepath: (state, action) => {
  21. state.path = action.payload;
  22. },
  23. setRefreshID: (state, action) => {
  24. state.refreshID = action.payload;
  25. },
  26. setFileStates: (state, action) => {
  27. state.fileStates = action.payload;
  28. },
  29. addOrUpdateFileState: (state, action) => {
  30. const { path, unsavedContent, savedContent } = action.payload;
  31. const newFileStates = state.fileStates.filter(
  32. (fileState) => fileState.path !== path,
  33. );
  34. newFileStates.push({ path, savedContent, unsavedContent });
  35. state.fileStates = newFileStates;
  36. },
  37. removeFileState: (state, action) => {
  38. const path = action.payload;
  39. state.fileStates = state.fileStates.filter(
  40. (fileState) => fileState.path !== path,
  41. );
  42. },
  43. },
  44. });
  45. export const {
  46. setCode,
  47. setActiveFilepath,
  48. setRefreshID,
  49. addOrUpdateFileState,
  50. removeFileState,
  51. setFileStates,
  52. } = codeSlice.actions;
  53. export default codeSlice.reducer;