This repository has been archived by the owner on Apr 7, 2024. It is now read-only.
forked from cytoscape/cytosnap
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathindex.js
237 lines (184 loc) · 5.94 KB
/
index.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
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
let Promise = require('bluebird');
let browserify = require('browserify');
let fs = require('fs');
let base64 = require('base64-stream');
let stream = require('stream');
let path = require('path');
let os = require('os');
let puppeteer = require('puppeteer');
let typeofFn = typeof function(){};
let isFunction = x => typeof x === typeofFn;
let Handlebars = require('handlebars');
let readFile = Promise.promisify(fs.readFile);
let writeFile = Promise.promisify(fs.writeFile);
let callbackifyValue = function( fn ){
return function( val ){
if( isFunction(fn) ){ fn( null, val ); }
return val;
};
};
let callbackifyError = function( fn ){
return function( err ){
if( isFunction(fn) ){ fn( err ); }
throw err;
};
};
let getStream = function( text ){
let s = new stream.Duplex();
s.push( text );
s.push( null );
return s;
};
let browserSrc;
let browserifyBrowserSrc = function(){
if( browserSrc != null ){
return browserSrc;
}
browserSrc = new Promise(function( resolve ){
browserify()
.add( path.join(__dirname, './browser/index.js') )
.bundle()
.on( 'end', resolve )
.pipe( fs.createWriteStream( path.join(__dirname, './browser/index.pack.js') ) );
});
return browserSrc;
};
let Cytosnap = function( opts = {} ){
if( !(this instanceof Cytosnap) ){
return new Cytosnap( opts );
}
this.options = Object.assign( {
// top-level defaults -- none currently
}, opts );
// options to pass to puppeteer.launch()
this.options.puppeteer = Object.assign({
// defaults
args: opts.args, // backwards compat
headless: true
}, opts.puppeteer);
this.running = false;
};
let extensions = [];
Cytosnap.use = function(exts){
extensions = exts;
};
let wroteExtensionList = false;
let writeExtensionsList = function(){
if( wroteExtensionList ){ return Promise.resolve(); }
let readTemplate = () => readFile(path.join(__dirname, './browser/index.js.hbs'), 'utf8');
let writeJs = contents => writeFile(path.join(__dirname, './browser/index.js'), contents);
let fillTemplate = template => {
return Handlebars.compile(template)({ extensions });
};
let done = () => wroteExtensionList = true;
return Promise.try(readTemplate).then(fillTemplate).then(writeJs).then(done);
};
let proto = Cytosnap.prototype;
proto.start = function( next ){
let snap = this;
return Promise.try(function(){
return puppeteer.launch(snap.options.puppeteer);
}).then(function( browser ){
snap.browser = browser;
snap.running = true;
}).then( callbackifyValue(next) ).catch( callbackifyError(next) );
};
proto.stop = function( next ){
let snap = this;
return Promise.try(function(){
snap.browser.close();
}).then(function(){
snap.running = false;
}).then( callbackifyValue(next) ).catch( callbackifyError(next) );
};
proto.shot = function( opts, next ){
let snap = this;
let page;
opts = Object.assign( {
// defaults
elements: [],
style: [],
layout: { name: 'grid' },
format: 'png',
background: 'transparent',
quality: 85,
width: 200,
height: 200,
resolvesTo: 'base64uri'
}, opts );
if( opts.format === 'jpg' ){
opts.format = 'jpeg';
} else if( opts.format === 'png' ){
opts.quality = 0; // most compression
}
return Promise.try(function(){
return writeExtensionsList();
}).then(function(){
return browserifyBrowserSrc();
}).then(function(){
return snap.browser.newPage();
}).then(function( puppeteerPage ){
page = puppeteerPage;
}).then(function(){
return page.setViewport({ width: opts.width, height: opts.height });
}).then(function(){
let patchUri = function(uri){
if( os.platform() === 'win32' ){
return '/' + uri.replace(/\\/g, '/');
} else {
return uri;
}
};
return page.goto( 'file://' + patchUri(path.join(__dirname, './browser/index.html')) );
}).then(function(){
if( !isFunction( opts.style ) ){ return Promise.resolve(); }
let js = 'window.styleFunction = (' + opts.style + ')';
return page.evaluate( js );
}).then(function(){
if( !isFunction( opts.layout ) ){ return Promise.resolve(); }
let js = 'window.layoutFunction = (' + opts.layout + ')';
return page.evaluate( js );
}).then(function(){
let js = 'window.options = ( ' + JSON.stringify(opts) + ' )';
return page.evaluate( js );
}).then(function(){
let js = 'document.body.style.setProperty("background", "' + opts.background + '")';
return page.evaluate( js );
}).then(function(){
return page.evaluate(function(){
/* global window, options, cy, layoutFunction, styleFunction */
if( window.layoutFunction ){ options.layout = layoutFunction(); }
if( window.styleFunction ){ options.style = styleFunction(); }
cy.style( options.style );
cy.add( options.elements );
let layoutDone = cy.promiseOn('layoutstop');
cy.makeLayout( options.layout ).run(); // n.b. makeLayout used in case cytoscape@2 support is desired
return layoutDone;
});
}).then(function(){
if( opts.resolveTo === 'json' ){ return null; } // can skip in json case
return page.screenshot({ type: opts.format, quality: opts.quality, encoding: 'base64' });
}).then(function( b64Img ){
switch( opts.resolvesTo ){
case 'base64uri':
return 'data:image/' + opts.format + ';base64,' + b64Img;
case 'base64':
return b64Img;
case 'stream':
return getStream( b64Img ).pipe( base64.decode() );
case 'json':
return page.evaluate(function(){
let posns = {};
cy.nodes().forEach(function(n){
posns[ n.id() ] = n.position();
});
return posns;
});
default:
throw new Error('Invalid resolve type specified: ' + opts.resolvesTo);
}
}).then(function( img ){
return page.close().then(function(){ return img; });
}).then( callbackifyValue(next) ).catch( callbackifyError(next) );
};
module.exports = Cytosnap;