forked from nglviewer/ngl
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathscript.js
88 lines (76 loc) · 1.83 KB
/
script.js
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
/**
* @file Script
* @author Alexander Rose <[email protected]>
* @private
*/
import Signal from '../lib/signals.es6.js'
import { Log } from './globals.js'
/**
* Script class
*/
class Script {
/**
* Create a script instance
* @param {String} functionBody - the function source
* @param {String} name - name of the script
* @param {String} path - path of the script
*/
constructor (functionBody, name, path) {
this.signals = {
elementAdded: new Signal(),
elementRemoved: new Signal(),
nameChanged: new Signal()
}
this.name = name
this.path = path
this.dir = path.substring(0, path.lastIndexOf('/') + 1)
try {
/* eslint-disable no-new-func */
this.fn = new Function(
'stage', 'panel',
'__name__', '__path__', '__dir__',
functionBody
)
} catch (e) {
Log.error('Script compilation failed', e)
this.fn = function () {}
}
}
/**
* Object type
* @readonly
*/
get type () { return 'Script' }
/**
* Execute the script
* @param {Stage} stage - the stage context
* @return {Promise} - resolve when script finished running
*/
call (stage) {
var panel = {
add: function (/* element */) {
this.signals.elementAdded.dispatch(arguments)
}.bind(this),
remove: function (/* element */) {
this.signals.elementRemoved.dispatch(arguments)
}.bind(this),
setName: function (value) {
this.signals.nameChanged.dispatch(value)
}.bind(this)
}
return new Promise((resolve, reject) => {
var args = [
stage, panel,
this.name, this.path, this.dir
]
try {
this.fn.apply(null, args)
resolve()
} catch (e) {
Log.error('Script.fn', e)
reject(e)
}
})
}
}
export default Script