summaryrefslogtreecommitdiff
path: root/blocks/eda-frontend/src/components/SchematicEditor/ComponentSidebar.js
blob: e7afc227668c7d1ba3d5ca39a8815c79286972ce (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
import { useEffect, useRef, useState } from 'react'
import { TailSpin } from 'react-loader-spinner'
import { useDispatch, useSelector } from 'react-redux'

import PropTypes from 'prop-types'

import {
  Collapse,
  Hidden,
  IconButton,
  InputAdornment,
  List,
  ListItem,
  ListItemIcon,
  TextField,
  Tooltip
} from '@material-ui/core'
import { makeStyles } from '@material-ui/core/styles'
import CloseIcon from '@material-ui/icons/Close'
import ExpandLess from '@material-ui/icons/ExpandLess'
import ExpandMore from '@material-ui/icons/ExpandMore'
import SearchIcon from '@material-ui/icons/Search'

import {
  fetchComponents,
  fetchComponentImages,
  fetchLibraries,
  toggleCollapse,
  toggleSimulate
} from '../../redux/schematicEditorSlice'
import api from '../../utils/Api'

import './Helper/SchematicEditor.css'
import SideComp from './SideComp'
import SimulationProperties from './SimulationProperties'

const COMPONENTS_PER_ROW = 3

const useStyles = makeStyles((theme) => ({
  toolbar: {
    minHeight: '90px'
  },
  nested: {
    paddingLeft: theme.spacing(2),
    width: '100%'
  },
  head: {
    marginRight: 'auto'
  }
}))

const searchOptions = {
  NAME: 'name__istartswith'
}

export default function ComponentSidebar ({ _compRef }) {
  const classes = useStyles()
  const libraries = useSelector(state => state.schematicEditor.libraries)
  const collapse = useSelector(state => state.schematicEditor.collapse)
  const components = useSelector(state => state.schematicEditor.components)
  const isSimulate = useSelector(state => state.schematicEditor.isSimulate)

  const dispatch = useDispatch()
  const [isSearchedResultsEmpty, setIssearchedResultsEmpty] = useState(false)
  const [searchText, setSearchText] = useState('')
  const [loading, setLoading] = useState(false)

  const [searchedComponentList, setSearchedComponents] = useState([])
  const searchOption = 'NAME'

  const timeoutId = useRef()

  const handleSearchText = (evt) => {
    if (searchText.length === 0) {
      setSearchedComponents([])
    }
    setSearchText(evt.target.value.trim())
    setSearchedComponents([])
    // mimic the value so we can access the latest value in our API call.

    // call api from here. and set the result to searchedComponentList.
  }

  useEffect(() => {
    // if the user keeps typing, stop the API call!
    clearTimeout(timeoutId.current)
    setSearchedComponents([])
    // don't make an API call with no data
    if (searchText.length === 0) return
    // capture the timeoutId so we can
    // stop the call if the user keeps typing
    timeoutId.current = setTimeout(() => {
      // call api here
      setLoading(true)

      api.get(`newblocks/?${searchOptions[searchOption]}=${searchText}`)
        .then(
          (res) => {
            if (res.data.length === 0) {
              setIssearchedResultsEmpty(true)
            } else {
              setIssearchedResultsEmpty(false)
              setSearchedComponents([...res.data])
            }
          }
        )
        .catch((err) => { console.error(err) })
      setLoading(false)
    }, 800)
  }, [searchText, searchOption])

  const handleCollapse = (id) => {
    // Fetches Components for given library if not already fetched
    if (collapse[id] === false && components[id].length === 0) {
      dispatch(fetchComponents(id))
    }

    // Updates state of collapse to show/hide dropdown
    dispatch(toggleCollapse(id))
  }

  // For Fetching Libraries
  useEffect(() => {
    dispatch(fetchLibraries())
  }, [dispatch])

  // Used to chunk array
  const chunk = (array, size) => {
    return array.reduce((chunks, item, i) => {
      if (i % size === 0) {
        chunks.push([item])
      } else {
        chunks[chunks.length - 1].push(item)
      }
      return chunks
    }, [])
  }

  const link1 = process.env.REACT_APP_BLOCKS_NAME + ' List'
  const link2 = 'Search ' + process.env.REACT_APP_BLOCK_NAME
  const link3 = 'No ' + process.env.REACT_APP_BLOCKS_NAME + ' Found'
  return (
    <>
      <Hidden smDown>
        <div className={classes.toolbar} />
      </Hidden>

      <div style={isSimulate ? { display: 'none' } : {}}>
        {/* Display List of categorized components */}
        <List>
          <ListItem button>
            <h2 style={{ margin: '5px' }}>{link1}</h2>
          </ListItem>
          <ListItem>

            <TextField
              id='standard-number'
              placeholder={link2}
              variant='outlined'
              size='small'
              value={searchText}
              onChange={handleSearchText}
              InputProps={{
                startAdornment: (
                  <InputAdornment position='start'>
                    <SearchIcon />
                  </InputAdornment>
                )
              }}
            />

          </ListItem>

          <div style={{ maxHeight: '70vh', overflowY: 'auto', overflowX: 'hidden' }}>
            {searchText.length !== 0 && searchedComponentList.length !== 0 &&

              searchedComponentList.map((component, i) => {
                return (
                  <ListItemIcon key={i}>
                    <SideComp component={component} />
                  </ListItemIcon>
                )
              }
              )}

            <ListItem>

              <TailSpin
                color='#F44336'
                height={100}
                width={100}
                visible={loading}
              />
            </ListItem>

            {!loading && searchText.length !== 0 && isSearchedResultsEmpty &&

              <span style={{ margin: '20px' }}>{link3}</span>}

            {/* Collapsing List Mapped by Libraries fetched by the API */}
            {searchText.length === 0 &&
              libraries.map(
                (library) => {
                  return (
                    <div key={library.id}>
                      <ListItem onClick={(e, id = library.id) => handleCollapse(id)} button divider>
                        <span className={classes.head}>{library.name}</span>
                        {collapse[library.id] ? <ExpandLess /> : <ExpandMore />}
                      </ListItem>
                      <Collapse in={collapse[library.id]} timeout='auto' unmountOnExit mountOnEnter exit={false}>
                        <List component='div' disablePadding dense>

                          {/* Chunked Blocks of Library */}
                          {
                            chunk(components[library.id], COMPONENTS_PER_ROW).map((componentChunk) => {
                              return (
                                <ListItem key={componentChunk[0].id} divider>
                                  {
                                    componentChunk.map((component) => {
                                      return (
                                        <ListItemIcon key={component.name}>
                                          <SideComp component={component} />
                                        </ListItemIcon>
                                      )
                                    }
                                    )
                                  }
                                </ListItem>
                              )
                            })
                          }

                        </List>
                      </Collapse>
                    </div>
                  )
                }
              )}
          </div>
        </List>
      </div>
      <div style={isSimulate ? {} : { display: 'none' }}>
        {/* Display simulation modes parameters on left side pane */}
        <List>
          <ListItem button divider>
            <h2 style={{ margin: '5px auto 5px 5px' }}>Simulation Modes</h2>
            <Tooltip title='close'>
              <IconButton color='inherit' className={classes.tools} size='small' onClick={() => { dispatch(toggleSimulate()) }}>
                <CloseIcon fontSize='small' />
              </IconButton>
            </Tooltip>
          </ListItem>
          <SimulationProperties />
        </List>
      </div>
    </>
  )
}

export function ComponentImages () {
  const componentImages = useSelector(state => state.schematicEditor.component_images)

  const dispatch = useDispatch()

  // For Fetching Image Paths
  useEffect(() => {
    dispatch(fetchComponentImages())
  }, [dispatch])

  return (
    <div>
      {(componentImages !== undefined) && componentImages.forEach((image) => { new Image().src = '/django_static/' + image })}
    </div>
  )
}

ComponentSidebar.propTypes = {
  compRef: PropTypes.object.isRequired
}