script.js 14.1 KB
Newer Older
1 2 3 4
$.ajaxSetup({
    cache: false,
    dataType: "text"
});
J
Jason Park 已提交
5

6
$(document).on('click', 'a', function(e) {
J
Jason Park 已提交
7 8
    e.preventDefault();

J
Jason Park 已提交
9
    if (!window.open($(this).attr('href'), '_blank')) {
J
Jason Park 已提交
10 11 12 13
        alert('Please allow popups for this site');
    }
});

J
Jason Park 已提交
14 15
var tm = new TracerManager();

16
$('#btn_interval input').on('change', function() {
17 18 19 20
    tm.interval = Number.parseFloat($(this).val() * 1000);
    showInfoToast('Tracing interval has been set to ' + tm.interval / 1000 + ' second(s).');
});

J
Jason Park 已提交
21
var $module_container = $('.module_container');
J
Jason Park 已提交
22
ace.require("ace/ext/language_tools");
23
var initEditor = function(id) {
J
Jason Park 已提交
24
    var editor = ace.edit(id);
J
Jason Park 已提交
25 26 27
    editor.setOptions({
        enableBasicAutocompletion: true,
        enableSnippets: true,
T
TornjV 已提交
28
        enableLiveAutocompletion: true
J
Jason Park 已提交
29
    });
J
Jason Park 已提交
30 31 32 33 34 35 36
    editor.setTheme("ace/theme/tomorrow_night_eighties");
    editor.session.setMode("ace/mode/javascript");
    editor.$blockScrolling = Infinity;
    return editor;
};
var dataEditor = initEditor('data');
var codeEditor = initEditor('code');
37
var lastFile = null;
38
dataEditor.on('change', function() {
J
Jason Park 已提交
39
    var data = dataEditor.getValue();
40
    if (lastFile) cachedFile[lastFile].data = data;
J
Jason Park 已提交
41
    try {
J
Jason Park 已提交
42
        tm.deallocateAll();
J
Jason Park 已提交
43
        eval(data);
44
    } catch (err) {} finally {
J
Jason Park 已提交
45
        tm.visualize();
J
Jason Park 已提交
46
        tm.removeUnallocated();
J
Jason Park 已提交
47 48
    }
});
49
codeEditor.on('change', function() {
J
Jason Park 已提交
50
    var code = codeEditor.getValue();
51
    if (lastFile) cachedFile[lastFile].code = code;
J
Jason Park 已提交
52
});
J
Jason Park 已提交
53

J
Jason Park 已提交
54
var cachedFile = {};
J
Jason Park 已提交
55
var loading = false;
56
var isScratchPaper = function(category, algorithm) {
57 58
    return category == null && algorithm == 'scratch_paper';
};
59
var getAlgorithmDir = function(category, algorithm) {
60 61 62
    if (isScratchPaper(category, algorithm)) return './algorithm/scratch_paper/';
    return './algorithm/' + category + '/' + algorithm + '/';
};
63
var getFileDir = function(category, algorithm, file) {
64 65 66
    if (isScratchPaper(category, algorithm)) return './algorithm/scratch_paper/';
    return './algorithm/' + category + '/' + algorithm + '/' + file + '/';
};
67
var loadFile = function(category, algorithm, file, explanation) {
J
Jason Park 已提交
68
    if (checkLoading()) return;
J
Jason Park 已提交
69 70
    $('#explanation').html(explanation);

71 72
    var dir = lastFile = getFileDir(category, algorithm, file);

J
Jason Park 已提交
73 74 75 76
    if (cachedFile[dir] && cachedFile[dir].data !== undefined && cachedFile[dir].code !== undefined) {
        dataEditor.setValue(cachedFile[dir].data, -1);
        codeEditor.setValue(cachedFile[dir].code, -1);
    } else {
J
Jason Park 已提交
77
        loading = true;
J
Jason Park 已提交
78
        cachedFile[dir] = {};
J
Jason Park 已提交
79 80
        dataEditor.setValue('');
        codeEditor.setValue('');
81
        var onFail = function(jqXHR, textStatus, errorThrown) {
J
Jason Park 已提交
82 83 84
            loading = false;
            alert("AJAX call failed: " + textStatus + ", " + errorThrown);
        };
85
        $.get(dir + 'data.js', function(data) {
J
Jason Park 已提交
86
            cachedFile[dir].data = data;
J
Jason Park 已提交
87
            dataEditor.setValue(data, -1);
J
Jason Park 已提交
88

89
            $.get(dir + 'code.js', function(code) {
J
Jason Park 已提交
90 91
                cachedFile[dir].code = code;
                codeEditor.setValue(code, -1);
J
Jason Park 已提交
92 93 94 95 96
                loading = false;
            }).fail(onFail);
        }).fail(onFail);
    }
};
97
var checkLoading = function() {
J
Jason Park 已提交
98
    if (loading) {
J
Jason Park 已提交
99
        showErrorToast('Wait until it completes loading of previous file.');
J
Jason Park 已提交
100
        return true;
J
Jason Park 已提交
101
    }
J
Jason Park 已提交
102
    return false;
J
Jason Park 已提交
103
};
104
var showDescription = function(data) {
105 106 107 108 109 110 111 112 113 114
    var $container = $('#tab_desc > .wrapper');
    $container.empty();
    for (var key in data) {
        if (key) $container.append($('<h3>').html(key));
        var value = data[key];
        if (typeof value === "string") {
            $container.append($('<p>').html(value));
        } else if (Array.isArray(value)) {
            var $ul = $('<ul>');
            $container.append($ul);
115
            value.forEach(function(li) {
116 117 118 119 120 121 122 123 124 125 126
                $ul.append($('<li>').html(li));
            });
        } else if (typeof value === "object") {
            var $ul = $('<ul>');
            $container.append($ul);
            for (var prop in value) {
                $ul.append($('<li>').append($('<strong>').html(prop)).append(' ' + value[prop]));
            }
        }
    }
};
127
var showAlgorithm = function(category, algorithm) {
128 129 130 131 132 133 134 135 136 137 138 139 140 141
    var $menu;
    var category_name;
    var algorithm_name;
    if (isScratchPaper(category, algorithm)) {
        $menu = $('#scratch-paper');
        category_name = '';
        algorithm_name = 'Scratch Paper';
    } else {
        $menu = $('[data-category="' + category + '"][data-algorithm="' + algorithm + '"]');
        category_name = list[category].name;
        algorithm_name = list[category].list[algorithm];
    }
    $('.sidemenu button').removeClass('active');
    $menu.addClass('active');
J
Jason Park 已提交
142
    $('#btn_desc').click();
J
Jason Park 已提交
143

144 145
    $('#category').html(category_name);
    $('#algorithm').html(algorithm_name);
J
Jason Park 已提交
146
    $('#tab_desc > .wrapper').empty();
J
Jason Park 已提交
147 148
    $('.files_bar').empty();
    $('#explanation').html('');
149
    lastFile = null;
J
tree  
Jason Park 已提交
150
    dataEditor.setValue('');
J
Jason Park 已提交
151
    codeEditor.setValue('');
152
};
153
var showFiles = function(category, algorithm, files) {
154 155 156
    $('.files_bar').empty();
    var init = false;
    for (var file in files) {
157 158
        (function(file, explanation) {
            var $file = $('<button>').append(file).click(function() {
159 160 161 162 163 164 165 166 167 168 169 170
                loadFile(category, algorithm, file, explanation);
                $('.files_bar > button').removeClass('active');
                $(this).addClass('active');
            });
            $('.files_bar').append($file);
            if (!init) {
                init = true;
                $file.click();
            }
        })(file, files[file]);
    }
};
171
var loadAlgorithm = function(category, algorithm) {
172 173 174 175
    if (checkLoading()) return;
    showAlgorithm(category, algorithm);

    var dir = getAlgorithmDir(category, algorithm);
J
Jason Park 已提交
176

177
    $.getJSON(dir + 'desc.json', function(data) {
J
Jason Park 已提交
178 179 180
        var files = data.files;
        delete data.files;

181 182
        showDescription(data);
        showFiles(category, algorithm, files);
J
Jason Park 已提交
183 184 185
    });
};
var list = {};
186
$.getJSON('./algorithm/category.json', function(data) {
J
Jason Park 已提交
187 188 189
    list = data;
    var init = false;
    for (var category in list) {
190 191 192 193 194
        (function(category) {
            var $category = $('<button class="category">')
                .append('<i class="fa fa-fw fa-caret-down">')
                .append(list[category].name);
            $category.click(function() {
J
Jason Park 已提交
195
                $('[data-category="' + category + '"]').toggleClass('collapse');
196
                $(this).find('i.fa').toggleClass('fa-caret-down fa-caret-up');
J
Jason Park 已提交
197
            });
J
Jason Park 已提交
198 199 200
            $('#list').append($category);
            var subList = list[category].list;
            for (var algorithm in subList) {
201
                (function(category, subList, algorithm) {
J
Jason Park 已提交
202 203 204 205
                    var $algorithm = $('<button class="indent">')
                        .append(subList[algorithm])
                        .attr('data-algorithm', algorithm)
                        .attr('data-category', category)
206
                        .click(function() {
J
Jason Park 已提交
207 208 209 210 211 212 213 214 215 216 217 218
                            loadAlgorithm(category, algorithm);
                        });
                    $('#list').append($algorithm);
                    if (!init) {
                        init = true;
                        $algorithm.click();
                    }
                })(category, subList, algorithm);
            }
        })(category);
    }
});
219
$('#powered-by').click(function() {
220 221
    $('#powered-by-list button').toggleClass('collapse');
});
222
$('#scratch-paper').click(function() {
223 224
    loadAlgorithm(null, 'scratch_paper');
});
J
Jason Park 已提交
225 226

var sidemenu_percent;
227
$('#navigation').click(function() {
J
Jason Park 已提交
228 229 230 231 232 233 234 235 236 237 238 239
    var $sidemenu = $('.sidemenu');
    var $workspace = $('.workspace');
    $sidemenu.toggleClass('active');
    $('.nav-dropdown').toggleClass('fa-caret-down fa-caret-up');
    if ($sidemenu.hasClass('active')) {
        $sidemenu.css('right', (100 - sidemenu_percent) + '%');
        $workspace.css('left', sidemenu_percent + '%');
    } else {
        sidemenu_percent = $workspace.position().left / $('body').width() * 100;
        $sidemenu.css('right', 0);
        $workspace.css('left', 0);
    }
240
    tm.resize();
J
Jason Park 已提交
241 242
});

243
var showErrorToast = function(err) {
J
Jason Park 已提交
244 245
    var $toast = $('<div class="toast error">').append(err);
    $('.toast_container').append($toast);
246 247
    setTimeout(function() {
        $toast.fadeOut(function() {
J
Jason Park 已提交
248 249 250 251 252
            $toast.remove();
        });
    }, 3000);
};

253
var showInfoToast = function(info) {
254 255
    var $toast = $('<div class="toast info">').append(info);
    $('.toast_container').append($toast);
256 257
    setTimeout(function() {
        $toast.fadeOut(function() {
258 259 260 261 262
            $toast.remove();
        });
    }, 3000);
};

263
$('#btn_run').click(function() {
J
Jason Park 已提交
264
    $('#btn_trace').click();
J
Jason Park 已提交
265
    try {
J
Jason Park 已提交
266
        tm.deallocateAll();
J
Jason Park 已提交
267 268
        eval(dataEditor.getValue());
        eval(codeEditor.getValue());
269
        tm.visualize();
J
Jason Park 已提交
270
    } catch (err) {
271
        console.error(err);
J
Jason Park 已提交
272
        showErrorToast(err);
J
Jason Park 已提交
273 274
    } finally {
        tm.removeUnallocated();
J
Jason Park 已提交
275 276
    }
});
277
$('#btn_pause').click(function() {
J
Jason Park 已提交
278
    if (tm.isPause()) {
279
        tm.resumeStep();
J
Jason Park 已提交
280
    } else {
281
        tm.pauseStep();
J
Jason Park 已提交
282 283
    }
});
284
$('#btn_prev').click(function() {
285 286
    tm.pauseStep();
    tm.prevStep();
J
Jason Park 已提交
287
});
288
$('#btn_next').click(function() {
289 290
    tm.pauseStep();
    tm.nextStep();
J
Jason Park 已提交
291 292
});

293
$('#btn_desc').click(function() {
J
Jason Park 已提交
294
    $('.tab_container > .tab').removeClass('active');
J
Jason Park 已提交
295
    $('#tab_desc').addClass('active');
J
Jason Park 已提交
296 297 298
    $('.tab_bar > button').removeClass('active');
    $(this).addClass('active');
});
299
$('#btn_trace').click(function() {
J
Jason Park 已提交
300
    $('.tab_container > .tab').removeClass('active');
J
Jason Park 已提交
301
    $('#tab_module').addClass('active');
J
Jason Park 已提交
302 303 304 305
    $('.tab_bar > button').removeClass('active');
    $(this).addClass('active');
});

306
$(window).resize(function() {
307
    tm.resize();
J
Jason Park 已提交
308
});
J
Jason Park 已提交
309 310 311 312 313 314 315 316

var dividers = [
    ['v', $('.sidemenu'), $('.workspace')],
    ['v', $('.viewer_container'), $('.editor_container')],
    ['h', $('.data_container'), $('.code_container')]
];
for (var i = 0; i < dividers.length; i++) {
    var divider = dividers[i];
317
    (function(divider) {
J
Jason Park 已提交
318 319 320 321 322 323 324
        var vertical = divider[0] == 'v';
        var $first = divider[1];
        var $second = divider[2];
        var $parent = $first.parent();
        var thickness = 5;

        var $divider = $('<div class="divider">');
J
Jason Park 已提交
325
        var dragging = false;
J
Jason Park 已提交
326 327 328 329 330 331 332 333 334
        if (vertical) {
            $divider.addClass('vertical');
            var _left = -thickness / 2;
            $divider.css({
                top: 0,
                bottom: 0,
                left: _left,
                width: thickness
            });
J
Jason Park 已提交
335
            var x;
336
            $divider.mousedown(function(e) {
J
Jason Park 已提交
337 338 339
                x = e.pageX;
                dragging = true;
            });
340
            $(document).mousemove(function(e) {
J
Jason Park 已提交
341 342 343 344 345 346 347
                if (dragging) {
                    var new_left = $second.position().left + e.pageX - x;
                    var percent = new_left / $parent.width() * 100;
                    percent = Math.min(90, Math.max(10, percent));
                    $first.css('right', (100 - percent) + '%');
                    $second.css('left', percent + '%');
                    x = e.pageX;
348
                    tm.resize();
J
Jason Park 已提交
349 350
                }
            });
351
            $(document).mouseup(function(e) {
J
Jason Park 已提交
352 353 354 355 356 357 358 359 360 361 362
                dragging = false;
            });
        } else {
            $divider.addClass('horizontal');
            var _top = -thickness / 2;
            $divider.css({
                top: _top,
                height: thickness,
                left: 0,
                right: 0
            });
J
Jason Park 已提交
363
            var y;
364
            $divider.mousedown(function(e) {
J
Jason Park 已提交
365 366 367
                y = e.pageY;
                dragging = true;
            });
368
            $(document).mousemove(function(e) {
J
Jason Park 已提交
369 370 371 372 373 374 375
                if (dragging) {
                    var new_top = $second.position().top + e.pageY - y;
                    var percent = new_top / $parent.height() * 100;
                    percent = Math.min(90, Math.max(10, percent));
                    $first.css('bottom', (100 - percent) + '%');
                    $second.css('top', percent + '%');
                    y = e.pageY;
376
                    tm.resize();
J
Jason Park 已提交
377 378
                }
            });
379
            $(document).mouseup(function(e) {
J
Jason Park 已提交
380 381 382 383 384 385
                dragging = false;
            });
        }

        $second.append($divider);
    })(divider);
J
Jason Park 已提交
386 387
}

388
$module_container.on('mousedown', '.module_wrapper', function(e) {
389
    tm.findOwner(this).mousedown(e);
J
Jason Park 已提交
390
});
391
$module_container.on('mousemove', '.module_wrapper', function(e) {
392
    tm.findOwner(this).mousemove(e);
J
Jason Park 已提交
393
});
394
$(document).mouseup(function(e) {
J
Jason Park 已提交
395
    tm.command('mouseup', e);
J
Jason Park 已提交
396
});
397
$module_container.on('DOMMouseScroll mousewheel', '.module_wrapper', function(e) {
398
    tm.findOwner(this).mousewheel(e);
T
TornjV 已提交
399 400 401 402
});

// Share scratch paper

403
var getParameterByName = function(name) {
404
    var url = window.location.href;
T
TornjV 已提交
405 406 407 408 409 410
    name = name.replace(/[\[\]]/g, "\\$&");
    var regex = new RegExp("[?&]" + name + "(=([^&#]*)|&|#|$)"),
        results = regex.exec(url);
    if (!results) return null;
    if (!results[2]) return '';
    return decodeURIComponent(results[2].replace(/\+/g, " "));
411
};
T
TornjV 已提交
412

413
var shareScratchPaper = function() {
T
TornjV 已提交
414
    var gist = {
415 416 417
        'description': 'temp',
        'public': true,
        'files': {
418 419 420 421 422 423
            'code.js': {
                'content': dataEditor.getValue()
            },
            'data.js': {
                'content': codeEditor.getValue()
            }
T
TornjV 已提交
424 425
        }
    };
426
    $.post('https://api.github.com/gists', JSON.stringify(gist), function(res) {
T
TornjV 已提交
427
        var data = JSON.parse(res);
428
        console.log(location.protocol + '//' + location.host + location.pathname + '?scratch-paper=' + data.id);
T
TornjV 已提交
429 430 431
    });
};

432 433
var loadScratchPaper = function(gistID) {
    $.get('https://api.github.com/gists/' + gistID, function(res) {
T
TornjV 已提交
434
        var data = JSON.parse(res);
435
        console.log(data);
T
TornjV 已提交
436
    });
437 438 439 440 441 442
};

if (/[?&]scratch-paper=/.test(location.search)) {
    var gistID = getParameterByName('scratch-paper');
    console.log(gistID);
    loadScratchPaper(gistID);
443 444
}

445 446
var toJSON = function(obj) {
    return JSON.stringify(obj, function(key, value) {
447 448 449 450
        return value === Infinity ? "Infinity" : value;
    });
};

451 452
var fromJSON = function(obj) {
    return JSON.parse(obj, function(key, value) {
453 454 455 456
        return value === "Infinity" ? Infinity : value;
    });
};

457
var refineNumber = function(number) {
458 459
    return number === Infinity ? '' : number;
};