summaryrefslogtreecommitdiff
path: root/blocks/eda-frontend/src/redux/saveSchematicSlice.js
blob: 701447b47041fa30926b8482639e51317472e19b (plain)
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
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
import { createSlice, createAsyncThunk } from '@reduxjs/toolkit'

import api from '../utils/Api'
import { transformXcos } from '../utils/GalleryUtils'

const initialState = {
  title: 'Untitled',
  description: '',
  xmlData: null,
  scriptDump: '',
  showDot: false,
  hasScript: false,
  details: {},
  isLoading: false,
  isSaved: null,
  isShared: null
}

// Api call to save new schematic or updating saved schematic.
export const saveSchematic = createAsyncThunk(
  'saveSchematic/saveSchematic',
  async ({ title, description, xml, base64, scriptDump }, { getState, rejectWithValue }) => {
    // Get token from localstorage
    const token = getState().auth.token
    if (!token) return rejectWithValue('No token found')
    const isSaved = getState().saveSchematic.isSaved
    const details = getState().saveSchematic.details

    // add headers
    const config = {
      headers: {
        'Content-Type': 'application/json',
        Authorization: `Token ${token}`
      }
    }

    const body = {
      data_dump: xml,
      base64_image: base64,
      name: title,
      description,
      script_dump: scriptDump
    }

    try {
      const url = `save/diagram${isSaved ? `/${details.save_id}` : ''}`
      const res = await api.post(url, body, config)
      if (res.status === 200) {
        return res.data
      }

      return rejectWithValue(res.data || 'Failed to save schematic')
    } catch (err) {
      console.log(err)
      const res = err.response
      return rejectWithValue(res?.data || 'Failed to save schematic')
    }
  })

// Action for Loading on-cloud saved schematics
export const fetchSchematic = createAsyncThunk(
  'saveSchematic/fetchSchematic',
  async (saveId, { getState, rejectWithValue }) => {
    // Get token from localstorage
    const token = getState().auth.token
    if (!token) return rejectWithValue('No token found')

    // add headers
    const config = {
      headers: {
        'Content-Type': 'application/json',
        Authorization: `Token ${token}`
      }
    }

    try {
      const res = await api.get(`save/diagram/${saveId}`, config)
      if (res.status === 200) {
        return res.data
      }

      return rejectWithValue(res.data || 'Failed to load schematic')
    } catch (err) {
      console.log(err)
      const res = err.response
      return rejectWithValue(res?.data || 'Failed to load schematic')
    }
  })

// Action for Loading on-cloud saved schematics
export const fetchDiagram = createAsyncThunk(
  'saveSchematic/fetchDiagram',
  async (saveId, { rejectWithValue }) => {
    try {
      const res = await api.get(`save/gallery/${saveId}`)
      if (res.status === 200) {
        res.data.data_dump = await loadGallery(res.data)()
        return res.data
      }

      return rejectWithValue(res.data || 'Failed to load diagram')
    } catch (err) {
      console.log(err)
      const res = err.response
      return rejectWithValue(res?.data || 'Failed to load diagram')
    }
  })

export const setSchShared = createAsyncThunk(
  'saveSchematic/setSchShared',
  async (share, { getState, rejectWithValue }) => {
    // Get token from localstorage
    const token = getState().auth.token
    if (!token) return rejectWithValue('No token found')

    const details = getState().saveSchematic.details

    // add headers
    const config = {
      headers: {
        'Content-Type': 'application/json',
        Authorization: `Token ${token}`
      }
    }

    const isShared = share ? 'on' : 'off'

    try {
      const res = await api.get(`save/${details.save_id}/sharing/${isShared}`, config)
      if (res.status === 200) {
        return res.data
      }

      return rejectWithValue(res.data || 'Failed to share schematic')
    } catch (err) {
      console.log(err)
      const res = err.response
      return rejectWithValue(res?.data || 'Failed to share schematic')
    }
  })

// Action for Loading local exported schematics
export const openLocalSch = createAsyncThunk(
  'saveSchematic/openLocalSch',
  async (data) => {
    return data
  })

// Action for Loading Gallery diagrams
const loadGallery = (data) => async () => {
  if (!data) {
    console.error('No diagram found')
    return
  }

  try {
    // Check if the data is xcos or xml
    const parser = new DOMParser()
    let dataDump = data.data_dump
    const xmlDoc = parser.parseFromString(dataDump, 'application/xml')
    const isXcos = xmlDoc.getElementsByTagName('XcosDiagram').length > 0
    if (isXcos) {
      dataDump = new XMLSerializer().serializeToString(await transformXcos(xmlDoc))
    }
    return dataDump
  } catch (error) {
    console.error('Error loading gallery:', error)
  } finally {
    window.loadGalleryComplete = true
  }
}

const saveSchematicSlice = createSlice({
  name: 'saveSchematic',
  initialState,
  reducers: {
    setLoadingDiagram: (state, action) => {
      state.isLoading = action.payload
    },
    setSchTitle: (state, action) => {
      state.title = action.payload
    },
    setSchDescription: (state, action) => {
      state.description = action.payload
    },
    setSchXmlData: (state, action) => {
      state.xmlData = action.payload
    },
    setSchScriptDump: (state, action) => {
      state.scriptDump = action.payload
    },
    setShowDot: (state, action) => {
      state.showDot = action.payload
    }
  },
  extraReducers: (builder) => {
    builder
      .addCase(saveSchematic.pending, (state) => {
        state.isLoading = true
      })
      .addCase(saveSchematic.fulfilled, (state, action) => {
        state.isLoading = false
        state.details = action.payload
        state.isSaved = true
        state.isShared = action.payload.shared
      })
      .addCase(saveSchematic.rejected, (state) => {
        state.isLoading = false
      })
      .addCase(fetchSchematic.pending, (state) => {
        state.isLoading = true
      })
      .addCase(fetchSchematic.fulfilled, (state, action) => {
        state.isLoading = false
        state.details = action.payload
        state.description = action.payload.description
        state.isSaved = true
        state.isShared = action.payload.shared
        state.title = action.payload.name
        state.xmlData = action.payload.data_dump
        state.scriptDump = action.payload.script_dump
        state.showDot = action.payload.script_dump !== ''
      })
      .addCase(fetchSchematic.rejected, (state) => {
        state.isLoading = false
      })
      .addCase(fetchDiagram.pending, (state) => {
        state.isLoading = true
      })
      .addCase(fetchDiagram.fulfilled, (state, action) => {
        state.isLoading = false
        state.details = action.payload
        state.description = action.payload.description
        state.isSaved = false
        state.isShared = false
        state.title = action.payload.name
        state.xmlData = action.payload.data_dump
        state.scriptDump = action.payload.script_dump
        state.showDot = action.payload.script_dump !== ''
        state.hasScript = action.payload.script_dump !== ''
      })
      .addCase(fetchDiagram.rejected, (state) => {
        state.isLoading = false
      })
      .addCase(setSchShared.pending, (state) => {
        state.isLoading = true
      })
      .addCase(setSchShared.fulfilled, (state, action) => {
        state.isLoading = false
        state.details = action.payload
        state.isShared = action.payload.shared
      })
      .addCase(setSchShared.rejected, (state) => {
        state.isLoading = false
      })
      .addCase(openLocalSch.pending, (state) => {
        state.isLoading = true
      })
      .addCase(openLocalSch.fulfilled, (state, action) => {
        state.isLoading = false
        state.details = action.payload
        state.description = action.payload.description
        state.isSaved = true
        state.isShared = action.payload.shared
        state.title = action.payload.title
        state.xmlData = action.payload.data_dump
        state.scriptDump = action.payload.script_dump
        state.showDot = action.payload.script_dump !== ''
      })
      .addCase(openLocalSch.rejected, (state) => {
        state.isLoading = false
      })
  }
})

export const {
  setLoadingDiagram,
  setSchTitle,
  setSchDescription,
  setSchXmlData,
  setSchScriptDump,
  setShowDot
} = saveSchematicSlice.actions

export default saveSchematicSlice.reducer