-
Notifications
You must be signed in to change notification settings - Fork 59
/
slide_maker.js
112 lines (92 loc) · 2.58 KB
/
slide_maker.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
(function() {
"use strict"
var slide = {};
window.slide = slide;
function fn_to_string(fn) {
var lines = fn.toString()
.replace(/^function\s*\([^)]*\)\s*{\s*\n/, '')
.replace(/\s*}\s*$/, '')
.split('\n');
// remove common pre-space
var minSpace = d3.min(lines.map(function(line) {
return line ? line.match(/^\s*/)[0].length : Infinity;
}));
if (minSpace && isFinite(minSpace)) {
lines = lines.map(function(line) { return line.substr(minSpace); })
}
return lines.join('\n');
}
slide.code = function(title, init, code) {
var out, codeText;
function myInit() {
out.selectAll('*').remove();
init(out.node());
}
var section = d3.select('body')
.append('section')
.data([myInit])
.attr('class', "code_slide")
section.append('h1')
.text(title)
var codes = section.append('div')
.attr('class', 'codes')
function myConsoleLog() {
var str = Array.prototype.slice.call(arguments).join(' ') + '\n';
var pre = out.select('pre.log');
if (pre.empty()) {
out.append('pre')
.attr('class', 'log')
.text(str)
} else {
pre.text(pre.text() + str);
}
}
function run() {
var code = codeText.property('value');
code = '(function(console) { \n' + code + '\n})({ log: myConsoleLog })';
out.select('div.error').remove();
out.select('pre.log').remove();
try {
eval(code);
} catch(err) {
out.append('div')
.attr('class', 'error')
.text('Error: ' + err.message)
}
}
codeText = codes.append('textarea')
.attr('class', 'code')
.property('value', fn_to_string(code))
.on('keydown', function() {
// Run if command + enter
if (d3.event.keyCode === 13 && d3.event.metaKey) run();
d3.event.stopPropagation();
})
var buttonBar = codes.append('div')
.attr('class', 'button_bar')
buttonBar.append('div')
.attr('class', 'run btn')
.text('Run')
.on('click', run)
buttonBar.append('div')
.attr('class', 'reset btn')
.text('Reset')
.on('click', myInit)
out = section.append('div')
.attr('class', "out")
}
slide.code_title = function(title) {
d3.select('body')
.append('section')
.attr('class', "code_title")
.append('h1')
.text(title);
}
slide.title = function(title) {
d3.select('body')
.append('section')
.attr('class', "title")
.append('h1')
.text(title);
}
})();