summaryrefslogtreecommitdiff
path: root/blocks/eda-frontend/src/pages/Gallery.js
blob: 83d9e967563460e19e0a260461911c81bc57b590 (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
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
// Main layout for gallery page.
import { useCallback, useEffect, useState } from 'react'
import { useDispatch, useSelector } from 'react-redux'
import { Link as RouterLink } from 'react-router-dom'

import PropTypes from 'prop-types'

import {
  Button,
  Card,
  CardActionArea,
  CardActions,
  CardContent,
  CardMedia,
  Container,
  CssBaseline,
  FormControl,
  Grid,
  Input,
  InputLabel,
  MenuItem,
  Select,
  Typography
} from '@material-ui/core'
import { makeStyles } from '@material-ui/core/styles'

import { fetchGallery } from '../redux/dashboardSlice'
import api from '../utils/Api'

const useStyles = makeStyles((theme) => ({
  mainHead: {
    width: '100%',
    backgroundColor: '#404040',
    color: '#fff'
  },
  title: {
    fontSize: 18,
    color: '#80ff80'
  },
  header: {
    padding: theme.spacing(5, 0, 6, 0)
  },
  root: {
    display: 'flex',
    minHeight: '100vh',
    backgroundColor: '#f4f6f8'
  },
  media: {
    marginTop: theme.spacing(3),
    height: 170
  }
}))

const images = require.context('../static/gallery', true)

// Card displaying overview of gallery sample schematics.
const SchematicCard = ({ sch }) => {
  const classes = useStyles()

  useEffect(() => {
    document.title = 'Gallery - ' + process.env.REACT_APP_NAME
  }, [])

  const imageName = images('./' + sch.media)

  return (
    <>
      <Card>
        <CardActionArea>
          <CardMedia
            component='img'
            className={classes.media}
            image={imageName}
            title={sch.name}
            style={{ width: '100%', height: 'auto', objectFit: 'contain' }}
          />
          <CardContent>
            <Typography gutterBottom variant='h5' component='h2'>
              {sch.name}
            </Typography>
            <Typography variant='body2' component='p'>
              {sch.description}
            </Typography>
          </CardContent>
        </CardActionArea>

        <CardActions>
          <Button
            target='_blank'
            component={RouterLink}
            to={'/editor?id=' + sch.save_id}
            size='small'
            color='primary'
          >
            Launch in Editor
          </Button>
        </CardActions>
      </Card>
    </>
  )
}
SchematicCard.propTypes = {
  sch: PropTypes.object
}

// Card displaying gallery page header.
const MainCard = () => {
  const classes = useStyles()

  const typography = process.env.REACT_APP_NAME + ' Gallery'
  const diagramTypography = 'Sample ' + process.env.REACT_APP_SMALL_DIAGRAMS_NAME + ' are listed below...'
  return (
    <Card className={classes.mainHead}>
      <CardContent>
        <Typography variant='h2' align='center' gutterBottom>
          {typography}
        </Typography>
        <Typography className={classes.title} align='center' gutterBottom>
          {diagramTypography}
        </Typography>
      </CardContent>
    </Card>
  )
}

const BookDropdown = ({ onBookChange }) => {
  const [books, setBooks] = useState([]) // To store books from the backend
  const [selectedBook, setSelectedBook] = useState('')

  // Fetch books from the backend (optional, or use static data)
  const fetchBooks = useCallback(() => {
    api.get('save/books')
      .then((res) => {
        if (res.status !== 200) {
          throw new Error(`HTTP error! Status: ${res.status}`)
        }
        setBooks(res.data) // Assuming the API returns an array of books
      })
      .catch(err => { console.error('Error fetching books:', err) })
  }, [])

  useEffect(() => {
    fetchBooks()
    return () => { setBooks([]) }
  }, [fetchBooks])

  // Handle dropdown selection change
  const handleChange = (evt) => {
    const selectedValue = evt.target.value
    setSelectedBook(selectedValue)
    onBookChange(selectedValue) // Notify the parent component
  }

  return (
    <Grid container spacing={2} alignItems='center'>
      <Grid item xs={12}>
        <FormControl fullWidth>
          <InputLabel id='book-label'>Book</InputLabel>
          <Select
            labelId='book-label'
            value={selectedBook || ''}
            onChange={handleChange}
            label='Book'
          >
            <MenuItem key='all-books' value='all'>
              All Books ({books?.reduce((total, book) => total + (book.example_count || 0), 0)})
            </MenuItem>
            {/* Render dynamic book options */}
            {books?.map((book) => (
              <MenuItem key={`book-${book.id}`} value={book.id}>
                {book.book_name} ({book.author_name}) ({book.example_count || 0})
              </MenuItem>
            ))}
          </Select>
        </FormControl>
      </Grid>
    </Grid>
  )
}

BookDropdown.propTypes = {
  onBookChange: PropTypes.func.isRequired
}

const SearchComponent = ({ onSearch }) => {
  const [searchTerm, setSearchTerm] = useState('')

  const handleSearch = (event) => {
    const value = event.target.value.trimStart()
    setSearchTerm(value)
    onSearch(value)
  }

  return (
    <Grid container spacing={2}>
      <Grid item xs={12}>
        <FormControl fullWidth>
          <InputLabel htmlFor='search-input'>Search</InputLabel>
          <Input
            id='search-input'
            type='text'
            placeholder='Search books, examples...'
            value={searchTerm}
            onChange={handleSearch}
          />
        </FormControl>
      </Grid>
    </Grid>
  )
}

SearchComponent.propTypes = {
  onSearch: PropTypes.func.isRequired
}

const Gallery = () => {
  const classes = useStyles()
  const GallerySchSample = useSelector(state => state.dashboard.gallery)

  // State to store the selected book ID
  const [selectedBook, setSelectedBook] = useState('')
  const [searchTerm, setSearchTerm] = useState('')

  const dispatch = useDispatch()

  useEffect(() => {
    dispatch(fetchGallery())
  }, [dispatch])

  // Handle dropdown selection change
  const handleBookChange = (book) => {
    setSelectedBook(book)
  }

  // Handle search term change
  const handleSearch = (term) => {
    setSearchTerm(term)
  }

  const filteredSchematics =
    (() => {
      if (!selectedBook) return []
      if (selectedBook === 'all') return GallerySchSample
      const selectedBookId = Number(selectedBook)
      return GallerySchSample.filter((sch) => sch.book_id === selectedBookId)
    })()

  const NOBLOCK = /^no./
  const SCE = /^(sce|sci|script)/
  const NOSCE = /^no(sce|sci|script)/
  const terms = searchTerm.trim().toLowerCase().split(/\s+/).filter(Boolean)

  // Then, filter based on the search term (independent from book selection)
  const finalfilteredSchematics =
    terms.length === 0
      ? filteredSchematics
      : filteredSchematics.filter((sch) => {
        return terms.every((st) =>
          sch.lcname.includes(st) ||
          sch.lcdescription.includes(st) ||
          (!NOBLOCK.test(st) && (';' + sch.blocks).includes(';' + st)) ||
          (NOBLOCK.test(st) && !(';' + sch.blocks + ';').includes(';' + st.substring(2) + ';')) ||
          sch.save_id.startsWith('gallery' + st) ||
          (SCE.test(st) && sch.has_script) ||
          (NOSCE.test(st) && !sch.has_script)
        )
      })

  return (
    <div className={classes.root}>
      <CssBaseline />
      <Container maxWidth='lg' className={classes.header}>
        <Grid container direction='row' justifyContent='flex-start' alignItems='flex-start' alignContent='center' spacing={3}>
          {/* Gallery Header */}
          <Grid item xs={12}>
            <MainCard />
          </Grid>

          <Grid item xs={12}>
            <Grid container spacing={2}>
              {/* BookDropdown */}
              <Grid item xs={12} md={6}>
                <BookDropdown onBookChange={handleBookChange} />
              </Grid>

              {/* SearchComponent */}
              <Grid item xs={12} md={6}>
                <SearchComponent onSearch={handleSearch} />
              </Grid>
            </Grid>
          </Grid>

          {/* Display a message or blank gallery */}
          <Grid item xs={12}>
            <Typography variant='h6' align='center' color='textSecondary'>
              {
                finalfilteredSchematics.length === 0
                  ? `No ${process.env.REACT_APP_SMALL_DIAGRAMS_NAME} to display. ${selectedBook === ''
                    ? 'Please select a book.'
                    : selectedBook === 'all'
                      ? 'Please try another search term.'
                      : 'Please select another book or try another search term.'
                  }`
                  : `${finalfilteredSchematics.length} ${finalfilteredSchematics.length !== 1
                    ? `${process.env.REACT_APP_SMALL_DIAGRAMS_NAME}`
                    : `${process.env.REACT_APP_SMALL_DIAGRAM_NAME}`}`
              }
            </Typography>
          </Grid>

          {
            finalfilteredSchematics.map((sch) => (
              <Grid item xs={12} sm={6} lg={4} key={sch.save_id}>
                <SchematicCard sch={sch} />
              </Grid>
            ))
          }
        </Grid>
      </Container>
    </div>
  )
}

export default Gallery