1
+ /* eslint-disable import/no-cycle */
2
+ import { layoutModeGet } from '../layoutMode'
3
+ import Scope , { scopeList } from '../circuit'
4
+ import { loadScope } from './load'
5
+ import { updateRestrictedElementsInScope } from '../restrictedElementDiv'
6
+ import { forceResetNodesSet } from '../engine'
7
+
8
+ // Declare global variables
9
+ declare let globalScope : Scope
10
+ declare let loading : boolean
11
+
12
+ /**
13
+ * Function to restore copy from backup
14
+ * @param scope - The circuit on which undo is called
15
+ * @category data
16
+ */
17
+ export default function undo ( scope : Scope = globalScope ) : void {
18
+ if ( layoutModeGet ( ) || scope . backups . length < 2 ) return
19
+
20
+ const { ox, oy, scale } = saveGlobalScopePosition ( )
21
+ resetGlobalScopePosition ( )
22
+
23
+ loading = true
24
+ const undoData = popLastBackup ( scope )
25
+ if ( ! undoData ) return
26
+
27
+ scope . history . push ( undoData )
28
+
29
+ const tempScope = createTempScope ( scope )
30
+ if ( ! tempScope ) return
31
+
32
+ updateGlobalScope ( tempScope , ox , oy , scale )
33
+ forceResetNodesSet ( true )
34
+ updateRestrictedElementsInScope ( )
35
+ }
36
+
37
+ function saveGlobalScopePosition ( ) {
38
+ return {
39
+ ox : globalScope . ox ,
40
+ oy : globalScope . oy ,
41
+ scale : globalScope . scale ,
42
+ }
43
+ }
44
+
45
+ function resetGlobalScopePosition ( ) {
46
+ globalScope . ox = 0
47
+ globalScope . oy = 0
48
+ }
49
+
50
+ function popLastBackup ( scope : Scope ) : string | undefined {
51
+ return scope . backups . pop ( )
52
+ }
53
+
54
+ function createTempScope ( scope : Scope ) : Scope | undefined {
55
+ const tempScope = new Scope ( scope . name )
56
+ if ( scope . backups . length === 0 ) return tempScope
57
+
58
+ try {
59
+ loadScope ( tempScope , JSON . parse ( scope . backups [ scope . backups . length - 1 ] ) )
60
+ } catch ( error ) {
61
+ console . error ( 'Failed to parse backup data:' , error )
62
+ loading = false
63
+ return undefined
64
+ }
65
+
66
+ tempScope . backups = scope . backups
67
+ tempScope . history = scope . history
68
+ tempScope . id = scope . id
69
+ tempScope . name = scope . name
70
+ tempScope . testbenchData = scope . testbenchData
71
+
72
+ return tempScope
73
+ }
74
+
75
+ function updateGlobalScope ( tempScope : Scope , ox : number , oy : number , scale : number ) {
76
+ scopeList [ tempScope . id ] = tempScope
77
+ globalScope = tempScope
78
+ globalScope . ox = ox
79
+ globalScope . oy = oy
80
+ globalScope . scale = scale
81
+ loading = false
82
+ }
0 commit comments