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
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
|
/* eslint new-cap: ["error", {"newIsCapExceptionPattern": "^mx"}] */
import { useEffect, useState } from 'react'
import { useSelector, useDispatch } from 'react-redux'
import { Link as RouterLink } from 'react-router-dom'
import { Canvg } from 'canvg'
import mxGraphFactory from 'mxgraph'
import PropTypes from 'prop-types'
import beautify from 'xml-beautifier'
import {
Divider,
Drawer,
IconButton,
List,
ListItem,
ListItemIcon,
ListItemText,
Snackbar,
Tooltip,
useMediaQuery
} from '@material-ui/core'
import { makeStyles } from '@material-ui/core/styles'
import AddBoxOutlinedIcon from '@material-ui/icons/AddBoxOutlined'
import ClearAllIcon from '@material-ui/icons/ClearAll'
import CloseIcon from '@material-ui/icons/Close'
import CreateNewFolderOutlinedIcon from '@material-ui/icons/CreateNewFolderOutlined'
import DeleteIcon from '@material-ui/icons/Delete'
import DescriptionIcon from '@material-ui/icons/Description'
import HelpOutlineIcon from '@material-ui/icons/HelpOutline'
import ImageOutlinedIcon from '@material-ui/icons/ImageOutlined'
import OpenInBrowserIcon from '@material-ui/icons/OpenInBrowser'
import PlayCircleOutlineIcon from '@material-ui/icons/PlayCircleOutline'
import PrintOutlinedIcon from '@material-ui/icons/PrintOutlined'
import RedoIcon from '@material-ui/icons/Redo'
import RotateRightIcon from '@material-ui/icons/RotateRight'
import SaveOutlinedIcon from '@material-ui/icons/SaveOutlined'
import SettingsOverscanIcon from '@material-ui/icons/SettingsOverscan'
import SystemUpdateAltOutlinedIcon from '@material-ui/icons/SystemUpdateAltOutlined'
import UndoIcon from '@material-ui/icons/Undo'
import ZoomInIcon from '@material-ui/icons/ZoomIn'
import ZoomOutIcon from '@material-ui/icons/ZoomOut'
import { closeCompProperties } from '../../redux/componentPropertiesSlice'
import {
openLocalSch,
saveSchematic,
setLoadingDiagram,
setSchXmlData
} from '../../redux/saveSchematicSlice'
import { toggleSimulate } from '../../redux/schematicEditorSlice'
import store from '../../redux/store'
import api from '../../utils/Api'
import { transformXcos, saveToFile } from '../../utils/GalleryUtils'
import {
ClearGrid,
PrintPreview,
Rotate,
deleteComp,
editorRedo,
editorUndo,
editorZoomAct,
editorZoomIn,
editorZoomOut,
renderGalleryXML,
saveXml
} from './Helper/ToolbarTools'
import {
HelpScreen,
ImageExportDialog,
NetlistModal,
OpenSchDialog,
ScriptScreen
} from './ToolbarExtension'
const {
mxUtils
} = new mxGraphFactory()
const useStyles = makeStyles((theme) => ({
menuButton: {
marginLeft: 'auto',
marginRight: theme.spacing(0),
padding: theme.spacing(1),
[theme.breakpoints.up('lg')]: {
display: 'none'
}
},
tools: {
padding: theme.spacing(1),
margin: theme.spacing(0, 0.5),
color: '#262626'
},
pipe: {
fontSize: '1.45rem',
color: '#d6c4c2',
margin: theme.spacing(0, 1.5)
}
}))
// Notification snackbar to give alert messages
function SimpleSnackbar ({ open, close, message }) {
return (
<div>
<Snackbar
anchorOrigin={{
vertical: 'bottom',
horizontal: 'left'
}}
open={open}
autoHideDuration={5000}
onClose={close}
message={message}
action={
<>
<IconButton size='small' aria-label='close' color='inherit' onClick={close}>
<CloseIcon fontSize='small' />
</IconButton>
</>
}
/>
</div>
)
}
SimpleSnackbar.propTypes = {
open: PropTypes.bool,
close: PropTypes.func,
message: PropTypes.string
}
export default function SchematicToolbar ({ _mobileClose, gridRef }) {
const classes = useStyles()
const isAuthenticated = useSelector(state => state.auth.isAuthenticated)
const description = useSelector(state => state.saveSchematic.description)
const xmlData = useSelector(state => state.saveSchematic.xmlData)
const title2 = useSelector(state => state.saveSchematic.title)
const scriptDump = useSelector(state => state.saveSchematic.scriptDump)
const showDot = useSelector(state => state.saveSchematic.showDot)
const dispatch = useDispatch()
const isMobile = useMediaQuery('(max-width:600px)')
const [drawerOpen, setDrawerOpen] = useState(false)
const toggleDrawer = (open) => () => setDrawerOpen(open)
// Netlist Modal Control
const [open, setOpen] = useState(false)
const [netlist] = useState('')
const handleNetlistOpen = () => {
dispatch(toggleSimulate())
}
const handleClose = () => {
setOpen(false)
}
// Control Help dialog window
const [helpOpen, setHelpOpen] = useState(false)
const [scriptOpen, setScriptOpen] = useState(false)
const handleHelpOpen = () => {
setHelpOpen(true)
}
const handleHelpClose = () => {
setHelpOpen(false)
}
const handleSchWinOpen = () => {
setScriptOpen(true)
}
const handleScriptClose = () => {
setScriptOpen(false)
}
// Handle Delete component
const handleDeleteComp = () => {
deleteComp()
dispatch(closeCompProperties())
}
// Handle Notification Snackbar
const [snacOpen, setSnacOpen] = useState(false)
const [message, setMessage] = useState('')
const handleSnacClick = () => {
setSnacOpen(true)
}
const handleSnacClose = (event, reason) => {
if (reason === 'clickaway') {
return
}
setSnacOpen(false)
}
useEffect(() => {
if (xmlData) {
renderGalleryXML(xmlData)
}
}, [xmlData])
// Image Export of Schematic Diagram
async function exportImage (type) {
try {
const svg = document.querySelector('#divGrid > svg').cloneNode(true)
// Ensure xlink namespace is declared in the root SVG element
svg.setAttributeNS('http://www.w3.org/2000/xmlns/',
'xmlns:xlink',
'http://www.w3.org/1999/xlink')
svg.removeAttribute('style')
svg.setAttribute('width', gridRef.current.scrollWidth)
svg.setAttribute('height', gridRef.current.scrollHeight)
// Create a copy of the SVG for further processing if needed
const svgCopyForCanvg = svg.cloneNode(true)
const canvas = document.createElement('canvas')
canvas.width = gridRef.current.scrollWidth
canvas.height = gridRef.current.scrollHeight
canvas.style.width = canvas.width + 'px'
canvas.style.height = canvas.height + 'px'
const images = svgCopyForCanvg.getElementsByTagName('image')
for (const image of images) {
try {
const imageUrl = image.getAttribute('xlink:href')
if (imageUrl) {
let data = await fetch(imageUrl).then(v => v.text())
data = encodeURIComponent(data)
image.removeAttribute('xlink:href')
image.setAttributeNS('http://www.w3.org/1999/xlink',
'href',
'data:image/svg+xml;base64,' + window.btoa(data)
)
}
} catch (err) {
console.error('Error fetching image data:', err)
throw err
}
}
const ctx = canvas.getContext('2d')
ctx.webkitImageSmoothingEnabled = true
ctx.msImageSmoothingEnabled = true
ctx.imageSmoothingEnabled = true
const pixelRatio = window.devicePixelRatio || 1
ctx.setTransform(pixelRatio, 0, 0, pixelRatio, 0, 0)
return new Promise(resolve => {
if (type === 'SVG') {
const svgdata = new XMLSerializer().serializeToString(svg)
resolve('<?xml version="1.0" encoding="UTF-8"?>' + svgdata)
return
}
let svgString = svg.outerHTML
svgString = svgString.replace(/<hr>/g, '<hr />').replace(/<br>/g, '<br />').replace(/ /g, ' ')
const v = Canvg.fromString(ctx, svgString)
v.render().then(() => {
let image = ''
if (type === 'JPG') {
const imgdata = ctx.getImageData(0, 0, canvas.width, canvas.height)
for (let i = 0; i < imgdata.data.length; i += 4) {
if (imgdata.data[i + 3] === 0) {
imgdata.data[i] = 255
imgdata.data[i + 1] = 255
imgdata.data[i + 2] = 255
imgdata.data[i + 3] = 255
}
}
ctx.putImageData(imgdata, 0, 0)
image = canvas.toDataURL('image/jpeg', 1.0)
} else if (type === 'PNG') {
image = canvas.toDataURL('image/png')
}
resolve(image)
}).catch(err => {
console.error('Error rendering SVG with Canvg:', err)
})
})
} catch (err) {
console.error('Error in exportImage function:', err)
}
}
// Download JPEG, PNG exported Image
function downloadImage (data, type) {
const evt = new MouseEvent('click', {
view: window,
bubbles: false,
cancelable: true
})
const a = document.createElement('a')
const ext = (type === 'PNG') ? '.png' : '.jpg'
a.setAttribute('download', title2 + '_' + process.env.REACT_APP_NAME + '_on_Cloud' + ext)
a.setAttribute('href', data)
a.setAttribute('target', '_blank')
a.dispatchEvent(evt)
}
// Download SVG image
function downloadText (data, options) {
saveToFile(title2 + '_' + process.env.REACT_APP_NAME + '_on_Cloud.svg', options, data)
}
const [imgopen, setImgOpen] = useState(false)
const handleImgClickOpen = () => {
setImgOpen(true)
}
const handleImgClose = (value) => {
setImgOpen(false)
if (value === 'SVG') {
exportImage('SVG')
.then(v => {
downloadText(v, 'data:image/svg+xml')
})
} else if (value === 'PNG') {
exportImage('PNG')
.then(v => {
downloadImage(v, 'PNG')
})
} else if (value === 'JPG') {
exportImage('JPG')
.then(v => {
downloadImage(v, 'JPG')
})
}
}
// Handle Save Schematic onCloud
const handleSchSave = () => {
if (isAuthenticated !== true) {
setMessage('You are not Logged In')
handleSnacClick()
} else {
const xml = saveXml(description)
dispatch(setSchXmlData(xml))
exportImage('PNG')
.then(res => {
dispatch(saveSchematic({ title: title2, description, xml, base64: res, scriptDump }))
setMessage('Saved Successfully')
})
.catch(err => {
// Debugging: Log if there is an error in exportImage
console.error('Error exporting image:', err)
setMessage('Error exporting image')
})
handleSnacClick()
}
}
// Save Schematics Locally
const handleLocalSchSave = () => {
saveToFile(title2 + '_' + process.env.REACT_APP_NAME + '_on_Cloud.xml', 'application/xml', beautify(saveXml(description)))
}
const handleLocalSchSaveXcos = async () => {
try {
const xmlContent = beautify(saveXml(description))
const xmlBlob = new Blob([xmlContent], { type: 'application/xml' })
const xmlFileName = title2 + '.xml'
const scriptTaskId = store.getState().simulation.scriptTaskId
const formData = new FormData()
formData.append('file', xmlBlob, xmlFileName)
formData.append('scriptTaskId', scriptTaskId)
const config = {
headers: {
'Content-Type': 'multipart/form-data'
}
}
const response = await api.post('/simulation/save', formData, config)
if (!response || response.status !== 200) {
throw new Error('Network response was not ok')
}
saveToFile(title2 + '_' + process.env.REACT_APP_NAME + '_on_Cloud.xcos', 'application/x-scilab-xcos', response.data)
} catch (error) {
console.error('There was an error!', error)
}
}
const handleLocalSchSaveScript = () => {
saveToFile(title2 + '_' + process.env.REACT_APP_NAME + '_on_Cloud.sce', 'application/x-scilab', scriptDump)
}
const readXmlFile = (xmlDoc, dataDump, title) => {
const firstCell = xmlDoc.documentElement.children[0].children[0].children[0]
const firstCellAttrs = firstCell.attributes
const appname = firstCellAttrs.appname.value
const description = (firstCellAttrs.description !== undefined) ? firstCellAttrs.description.value : ''
if (appname !== process.env.REACT_APP_NAME) {
setMessage('Unsupported app name error !')
handleSnacClick()
} else {
const obj = { data_dump: dataDump, title, description }
if (obj.data_dump === undefined || obj.title === undefined || obj.description === undefined) {
setMessage('Unsupported file error !')
handleSnacClick()
} else {
dispatch(openLocalSch(obj))
}
}
}
// Open Locally Saved Schematic
const handleLocalSchOpen = () => {
const fileSelector = document.createElement('input')
fileSelector.setAttribute('type', 'file')
fileSelector.setAttribute('accept', '.xcos, .xml, application/xml')
fileSelector.click()
fileSelector.addEventListener('change', function (event) {
const file = event.target.files[0]
const filename = file.name
const base = '(_' + process.env.REACT_APP_NAME + '_on_Cloud)?( *\\([0-9]*\\))?\\.(xcos|xml)$'
const re = new RegExp(base, 'i')
if (re.test(filename)) {
const reader = new FileReader()
reader.onload = function (event) {
dispatch(setLoadingDiagram(true))
const title = filename.replace(re, '')
let dataDump = event.target.result
const xmlDoc = mxUtils.parseXml(dataDump)
const rexcos = /\.xcos$/i
if (rexcos.test(filename)) {
transformXcos(xmlDoc).then(xmlDoc => {
dataDump = new XMLSerializer().serializeToString(xmlDoc)
readXmlFile(xmlDoc, dataDump, title)
dispatch(setLoadingDiagram(false))
})
} else {
readXmlFile(xmlDoc, dataDump, title)
dispatch(setLoadingDiagram(false))
}
}
reader.readAsText(file)
} else {
setMessage('Unsupported file type error! Select valid file.')
handleSnacClick()
}
})
}
// Control Help dialog window open and close
const [schOpen, setSchOpen] = useState(false)
const handleSchDialOpen = () => {
setSchOpen(true)
}
const handleSchDialClose = () => {
setSchOpen(false)
}
// All toolbar icons in order
const toolbarItems = [
{ icon: <CreateNewFolderOutlinedIcon fontSize='small' />, label: 'New', link: '/editor' },
{ icon: <OpenInBrowserIcon fontSize='small' />, label: 'Open', action: handleSchDialOpen },
{ icon: <SaveOutlinedIcon fontSize='small' />, label: 'Save', action: handleSchSave },
'pipe',
{ icon: <SystemUpdateAltOutlinedIcon fontSize='small' />, label: 'Export', action: handleLocalSchSave },
{ icon: <SystemUpdateAltOutlinedIcon fontSize='small' />, label: 'Export in Xcos', action: handleLocalSchSaveXcos },
{ icon: <SystemUpdateAltOutlinedIcon fontSize='small' />, label: 'Export Script', action: handleLocalSchSaveScript },
{ icon: <ImageOutlinedIcon fontSize='small' />, label: 'Image Export', action: handleImgClickOpen },
{ icon: <PrintOutlinedIcon fontSize='small' />, label: 'Print Preview', action: PrintPreview },
'pipe',
{
icon: (
<div style={{ position: 'relative', display: 'inline-block', cursor: 'pointer' }}>
<DescriptionIcon fontSize="small" style={{ color: scriptDump ? 'red' : 'inherit' }} />
{/* Blinking Dot */}
{showDot && (
<div
style={{
position: 'absolute',
top: '-3px', // Adjust position to be visible
right: '-3px',
width: '5px',
height: '5px',
borderRadius: '50%',
backgroundColor: 'green',
animation: 'blink-animation 1s infinite alternate',
zIndex: 10 // Ensure visibility
}}
/>
)}
{/* CSS for blinking effect */}
<style>
{`
@keyframes blink-animation {
0% { opacity: 1; }
50% { opacity: 0.3; }
100% { opacity: 1; }
}
`}
</style>
</div>
),
label: 'Show Script',
action: handleSchWinOpen
},
{ icon: <PlayCircleOutlineIcon fontSize='small' />, label: 'Simulate', action: handleNetlistOpen },
'pipe',
{ icon: <UndoIcon fontSize='small' />, label: 'Undo', action: editorUndo },
{ icon: <RedoIcon fontSize='small' />, label: 'Redo', action: editorRedo },
{ icon: <RotateRightIcon fontSize='small' />, label: 'Rotate', action: Rotate },
'pipe',
{ icon: <ZoomInIcon fontSize='small' />, label: 'Zoom In', action: editorZoomIn },
{ icon: <ZoomOutIcon fontSize='small' />, label: 'Zoom Out', action: editorZoomOut },
{ icon: <SettingsOverscanIcon fontSize='small' />, label: 'Default Size', action: editorZoomAct },
'pipe',
{ icon: <DeleteIcon fontSize='small' />, label: 'Delete', action: handleDeleteComp },
{ icon: <ClearAllIcon fontSize='small' />, label: 'Clear All', action: ClearGrid },
{ icon: <HelpOutlineIcon fontSize='small' />, label: 'Help', action: handleHelpOpen }
]
// Only first 7 icons will be shown in mobile view, rest will go into the drawer
const visibleIcons = isMobile ? toolbarItems.slice(0, 7) : toolbarItems
return (
<>
<div style={{ display: 'flex', gap: '2px', alignItems: 'center' }}>
{/* ✅ Desktop: Show all icons */}
{!isMobile && visibleIcons.map((item, index) =>
item === 'pipe'
? (
<span key={index} style={{ margin: '0 8px', fontWeight: 'bold', opacity: 0.7, fontSize: '18px' }}>|</span>
)
: (
<Tooltip key={index} title={item.label}>
{item.link
? (
<IconButton color='inherit' className={classes.tools} size='small' component={RouterLink} to={item.link}>
{item.icon}
</IconButton>
)
: (
<IconButton color='inherit' className={classes.tools} size='small' onClick={item.action}>
{item.icon}
</IconButton>
)}
</Tooltip>
)
)}
{/* ✅ Mobile: Show only hamburger menu */}
{isMobile && (
<>
<Tooltip title="More">
<IconButton
color='inherit'
aria-label='open drawer'
edge='end'
size='small'
onClick={toggleDrawer(true)}
className={classes.menuButton}
>
<AddBoxOutlinedIcon fontSize='small' />
</IconButton>
</Tooltip>
</>
)}
</div>
{/* ✅ Mobile Hamburger Drawer */}
<Drawer anchor="right" open={drawerOpen} onClose={toggleDrawer(false)}>
<List>
{toolbarItems.map((item, index) =>
item === 'pipe'
? <Divider key={index} />
: (
<ListItem button key={index} onClick={item.action}>
<ListItemIcon>{item.icon}</ListItemIcon>
<ListItemText primary={item.label} />
</ListItem>
)
)}
<Divider />
<ListItem button onClick={toggleDrawer(false)}>
<ListItemText primary="Close Menu" />
</ListItem>
</List>
</Drawer>
{/* ✅ Dialogs & Modals */}
{schOpen && <OpenSchDialog open={schOpen} close={handleSchDialClose} openLocal={handleLocalSchOpen} /> }
{snacOpen && <SimpleSnackbar open={snacOpen} close={handleSnacClose} message={message} /> }
{imgopen && <ImageExportDialog open={imgopen} onClose={handleImgClose} /> }
{open && <NetlistModal open={open} close={handleClose} netlist={netlist} /> }
{helpOpen && <HelpScreen open={helpOpen} close={handleHelpClose} /> }
{scriptOpen && <ScriptScreen isOpen={scriptOpen} onClose={handleScriptClose} /> }
</>
)
}
SchematicToolbar.propTypes = {
mobileClose: PropTypes.func,
gridRef: PropTypes.object.isRequired
}
|