/
tributary.js
366 lines (335 loc) · 13.2 KB
/
tributary.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
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
tributary.Tributary = Backbone.Model.extend({
defaults: {
code: ""
},
binder: function() {
this.on("code", this.newcode);
this.on("execute", this.execute);
this.on("error", this.handle_error);
},
initialize: function() {
this.binder();
},
handle_error: function(e) {
if(tributary.trace) {
console.log(e);
console.trace();
}
},
execute: function() {
try {
svg = d3.select("svg");
//wrap the code in a closure
code = "tributary.initialize = function(g) {";
code += this.get("code");
code += "};";
eval(code);
//trib = window.trib #access global trib object
//trib_options = window.trib_options #access global trib object
//tributary.initialize(d3.select("svg.tributary_svg"))
} catch (e) {
this.trigger("error", e);
return false;
}
//we don't want it to nuke the svg if there is an error
try {
//for the datGUI stuff
window.trib = {}; //reset global trib object
window.trib_options = {}; //reset global trib_options object
trib = window.trib;
trib_options = window.trib_options;
$("svg.tributary_svg").empty();
tributary.initialize(d3.select("svg.tributary_svg"));
} catch (er) {
this.trigger("error", er);
return false;
}
this.trigger("noerror");
return true;
},
newcode: function(code) {
//save the code in the model
this.set({code:code});
this.execute();
//TODO: store code in local storage
return true;
},
get_code: function(callback) {
var that = this;
if(this.get("gist") && this.get("filename")) {
src_url = "/tributary/api/" + this.get("gist");// + "/" + this.get("filename");
d3.text(src_url, function(data) {
if(data) {
code = data;
that.set({code: data});
} else {
code = that.get("code");
if(!code) {
code = "";
}
}
//TODO: add error checking
callback(null, code);
});
}
}
});
tributary.TributaryView = Backbone.View.extend({
check_date: true,
initialize: function() {
this.endpoint = this.options.endpoint || "tributary";
//TODO: this should all be in render()
//but we assume that the #editor div is present when this class is
//instanciated. move it once the code is on more solid ground
//we will be using "that" a lot. it would have been fun to use "dat" instead.
var that = this;
d3.select("#editor").on("click", function() {
that.sliding = false;
that.picking = false;
});
d3.select(".CodeMirror").on("click", function() {
that.sliding = false;
that.picking = false;
});
this.code_editor = CodeMirror(d3.select("#editor").node(), {
//value: "function myScript(){return 100;}\n",
mode: "javascript",
theme: "lesser-dark",
lineNumbers: true,
onChange: function() {
thisCode = that.code_editor.getValue();
that.model.trigger("code", thisCode);
}
});
//datgui things
this.controls = {};
//keep track of whether or not datGui is being used
this.dating = false;
this.gui = new dat.GUI();
this.make_ui = function() {
//we only need to remake the ui if we are not using it
if(!that.dating) {
//reset everything
that.gui.destroy();
that.gui = new dat.GUI();
var key;
_.each(_.keys(trib), function(key) {
if(that.controls[key] !== undefined) {
delete that.controls[key];
}
//console.log key, trib[key]
if(trib_options !== undefined && trib_options[key] !== undefined) {
that.controls[key] = that.gui.add(trib, key, trib_options[key].min, trib_options[key].max);
} else {
//automatically make the range for the slider since its not provided
val = trib[key];
if(typeof(val) === "number") {
var min, max, slider_min, slider_max;
if(val === 0) {
min = -100;
max = 100;
} else {
min = -10 * val;
max = 10 * val;
slider_min = _.min([min, max]);
slider_max = _.max([min, max]);
}
that.controls[key] = that.gui.add(trib, key, slider_min, slider_max);
}
}
that.controls[key].onChange(function(key) {
return function(value) {
//console.log("args", arguments)
that.dating = true;
//console.log(value)
//search for this in the code and replace
//number regex taken from d3 source
//var txt = new RegExp("trib\." + key + "\\s*=(\\s*)[-+]?(?:\\d+\\.?\\d*|\\.?\\d+)(?:[eE][-+]?\\d+)?");
var txt = new RegExp("trib." + key + "\\s*=(\\s*)[-+]?(?:\\d+\\.?\\d*|\\.?\\d+)(?:[eE][-+]?\\d+)?");
//console.log("TXT", txt)
var cursor = that.code_editor.getSearchCursor(txt);
if(cursor.findNext()) {
var newtxt = "trib." + key + " = " + value;
cursor.replace(newtxt);
}
};
});
});
}
};
this.inlet = Inlet(this.code_editor);
this.init_gui();
var code = this.model.get("code");
//check if we already have the code
if(code !== undefined && code !== "") {
this.code_editor.setValue(code);
this.model.execute();
} else {
//fill in the editor with text we get back from the gist
this.model.get_code(function(error, got_code) {
that.code_editor.setValue(got_code);
});
}
//Hook up drag and drop for code file
$('body')[0].addEventListener('dragover', this._dragOver, false);
$('body')[0].addEventListener('drop', this._fileDrop, false);
//Setup loop to check for file date
this.code_last_modified = new Date(0,0,0);
this.past = new Date();
d3.timer(function() {
if(new Date() - that.past > 300) {
if(that.file !== undefined) {
that._loadFile();
}
that.past = new Date();
}
return false;
});
},
init_gui: function() {
var that = this;
//Setup the gui elements for this page
//Setup tweet link
/*
$('#tweet_this').append("tweet this");
$('#tweetPanel').on("click", function(e) {
that.save_gist(function(newurl, newgist) {
var tweetlink = "http://twitter.com/home/?status=See my latest %23tributary here "+"http://mainstem.org" + newurl;
window.location = tweetlink;
//window.open(tweetlink, 'twitte')
});
});
*/
//Setup the save panel
$('#savePanel').on('click', function(e) {
that.save_gist(function(newurl, newgist) {
window.location = newurl;
});
});
//Setup editor controls
this.editor_width = 600;
this.editor_height = 300;
var editor = $('#editor');
editor.css('width', this.editor_width);
editor.css('height', this.editor_height);
var editor_drag = d3.behavior.drag()
.on("drag", function(d,i) {
var dx = d3.event.dx;
var dy = d3.event.dy;
d.x -= dx;
d.y -= dy;
that.editor_handle.style("bottom", that.editor_height + d.y + "px");
that.editor_handle.style("right", -10 + that.editor_width + d.x + "px");
editor.css('width', that.editor_width + d.x + "px");
editor.css('height', that.editor_height + d.y + "px");
editor.find('.CodeMirror-scroll').css('height', that.editor_height + d.y + "px");
editor.find('.CodeMirror-gutter').css('height', that.editor_height + d.y + "px");
});
var handle_data = {
x: 0,
y: 0
};
//d3.select("#editor").append("div")
//TODO: make this not append to body, but @el (need @el)
this.editor_handle = d3.select("body").append("div")
.attr("id", "editor_handle")
.data([handle_data])
.style("position", "fixed")
.style("display", "block")
.style("float", "left")
.style("bottom", this.editor_height + "px")
.style("right", -11 + this.editor_width + "px")
.style("width", "20px")
.style("height", "20px")
.style("background-color", "rgba(50, 50, 50, .4)")
.style("z-index", 999)
.call(editor_drag);
this.model.on("error", function() {
that.editor_handle.style("background-color", "rgba(250, 50, 50, .7)");
});
this.model.on("noerror", function() {
that.editor_handle.style("background-color", "rgba(50, 250, 50, .4)");
that.make_ui();
that.dating = false;
});
//Setup Hide the editor button
var he = $('#hideEditor');
he.on("click", function(e) {
$("#editor").toggle();
$("#editor_handle").toggle();
//toggle the gui for delta/flow
//$('#gui').toggle()
var txt = he.html();
//console.log("txt", txt)
if(txt === "Hide") {
he.html("Show");
} else {
he.html("Hide");
}
});
},
save_gist: function(callback) {
//console.log("ENDPOINT", @endpoint)
//Save the current code to a public gist
var oldgist = parseInt(this.model.get("gist"), 10);
//We now assume all tributaries will be saved as inlet.js
//so this code is a bit redundant, but it might be useful in the future
filename = this.model.get("filename");
if(filename === ""){
filename = "inlet.js";
}
var gist = {
description: 'just another inlet to tributary',
public: true,
files: {}
};
gist.files[filename] = {
content: this.model.get("code")
};
//turn the save button into a saving animation
d3.select("#saveButton").style("background-image", "url(/static/img/ajax-loader.gif)");
d3.select("#saveButton").style("background-repeat", "no-repeat");
d3.select("#saveButton").style("top", "0px");
var that = this;
$.post('/tributary/save', {"gist":JSON.stringify(gist)}, function(data) {
if(typeof(data) === "string") {
data = JSON.parse(data);
}
var newgist = data.id;
var newurl = "/" + that.endpoint + "/" + newgist;// + "/" + filename;
callback(newurl, newgist);
//window.location = newurl;
});
},
//------------------------------------
//Drop file functions
//------------------------------------
_dragOver: function(ev) {
//Called when a user drags a file over the #drop_file div
ev.stopPropagation();
ev.preventDefault();
ev.dataTransfer.dropEffect = 'copy';
//$('#drop_file').addClass('drop_file_active');
},
_fileDrop: function(ev) {
ev.stopPropagation();
ev.preventDefault();
this.file = ev.dataTransfer.files[0];
this.code_last_modified = new Date(0,0,0);
this._loadFile();
},
_loadFile: function() {
var that = this;
var reader = new FileReader();
// register an onload callback that gets fired after the reader has finished reading the file
if(!this.check_date || this.file.lastModifiedDate > this.code_last_modified) {
console.log("read file!");
reader.onload = function() {
//@executeCode({reader: reader})
that.code_editor.setValue(reader.result);
};
this.code_last_modified = this.file.lastModifiedDate;
reader.readAsText(this.file);
}
}
});