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

J
Jason Park 已提交
3 4 5
$(document).on('click', 'a', function (e) {
    e.preventDefault();

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

J
Jason Park 已提交
11 12
var tm = new TracerManager();

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

J
Jason Park 已提交
18
var $module_container = $('.module_container');
J
Jason Park 已提交
19
ace.require("ace/ext/language_tools");
J
Jason Park 已提交
20 21
var initEditor = function (id) {
    var editor = ace.edit(id);
J
Jason Park 已提交
22 23 24 25 26
    editor.setOptions({
        enableBasicAutocompletion: true,
        enableSnippets: true,
        enableLiveAutocompletion: true
    });
J
Jason Park 已提交
27 28 29 30 31 32 33
    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');
J
Jason Park 已提交
34
var lastDir = null;
J
Jason Park 已提交
35
dataEditor.on('change', function () {
J
Jason Park 已提交
36 37
    var data = dataEditor.getValue();
    if (lastDir) cachedFile[lastDir].data = data;
J
Jason Park 已提交
38
    try {
J
Jason Park 已提交
39
        tm.deallocateAll();
J
Jason Park 已提交
40
        eval(data);
J
Jason Park 已提交
41
    } catch (err) {
J
Jason Park 已提交
42
    } finally {
J
Jason Park 已提交
43
        tm.visualize();
J
Jason Park 已提交
44
        tm.removeUnallocated();
J
Jason Park 已提交
45 46
    }
});
J
Jason Park 已提交
47 48 49 50
codeEditor.on('change', function () {
    var code = codeEditor.getValue();
    if (lastDir) cachedFile[lastDir].code = code;
});
J
Jason Park 已提交
51

J
Jason Park 已提交
52
var cachedFile = {};
J
Jason Park 已提交
53
var loading = false;
J
Jason Park 已提交
54
var loadFile = function (category, algorithm, file, explanation) {
J
Jason Park 已提交
55
    if (checkLoading()) return;
J
Jason Park 已提交
56 57
    $('#explanation').html(explanation);

J
Jason Park 已提交
58 59 60 61 62
    var dir = lastDir = './algorithm/' + category + '/' + algorithm + '/' + file + '/';
    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 已提交
63
        loading = true;
J
Jason Park 已提交
64
        cachedFile[dir] = {};
J
Jason Park 已提交
65 66
        dataEditor.setValue('');
        codeEditor.setValue('');
J
Jason Park 已提交
67 68 69 70
        var onFail = function (jqXHR, textStatus, errorThrown) {
            loading = false;
            alert("AJAX call failed: " + textStatus + ", " + errorThrown);
        };
J
Jason Park 已提交
71
        $.get(dir + 'data.js', function (data) {
J
Jason Park 已提交
72
            cachedFile[dir].data = data;
J
Jason Park 已提交
73
            dataEditor.setValue(data, -1);
J
Jason Park 已提交
74

J
Jason Park 已提交
75 76 77
            $.get(dir + 'code.js', function (code) {
                cachedFile[dir].code = code;
                codeEditor.setValue(code, -1);
J
Jason Park 已提交
78 79 80 81 82 83 84
                loading = false;
            }).fail(onFail);
        }).fail(onFail);
    }
};
var checkLoading = function () {
    if (loading) {
J
Jason Park 已提交
85
        showErrorToast('Wait until it completes loading of previous file.');
J
Jason Park 已提交
86
        return true;
J
Jason Park 已提交
87
    }
J
Jason Park 已提交
88
    return false;
J
Jason Park 已提交
89 90
};
var loadAlgorithm = function (category, algorithm) {
J
Jason Park 已提交
91
    if (checkLoading()) return;
J
Jason Park 已提交
92 93
    $('#list > button').removeClass('active');
    $('[data-category="' + category + '"][data-algorithm="' + algorithm + '"]').addClass('active');
J
Jason Park 已提交
94
    $('#btn_desc').click();
J
Jason Park 已提交
95

J
Jason Park 已提交
96 97
    $('#category').html(list[category].name);
    $('#algorithm, #desc_title').html(list[category].list[algorithm]);
J
Jason Park 已提交
98
    $('#tab_desc > .wrapper').empty();
J
Jason Park 已提交
99 100
    $('.files_bar').empty();
    $('#explanation').html('');
J
Jason Park 已提交
101
    lastDir = null;
J
tree  
Jason Park 已提交
102
    dataEditor.setValue('');
J
Jason Park 已提交
103 104 105
    codeEditor.setValue('');

    var dir = './algorithm/' + category + '/' + algorithm + '/';
J
Jason Park 已提交
106
    $.getJSON(dir + 'desc.json', function (data) {
J
Jason Park 已提交
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
        var files = data.files;
        delete data.files;

        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);
                value.forEach(function (li) {
                    $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]));
                }
            }
        }

J
Jason Park 已提交
132 133
        $('.files_bar').empty();
        var init = false;
J
Jason Park 已提交
134
        for (var file in files) {
J
Jason Park 已提交
135 136 137 138 139 140 141 142 143 144 145
            (function (file, explanation) {
                var $file = $('<button>').append(file).click(function () {
                    loadFile(category, algorithm, file, explanation);
                    $('.files_bar > button').removeClass('active');
                    $(this).addClass('active');
                });
                $('.files_bar').append($file);
                if (!init) {
                    init = true;
                    $file.click();
                }
J
Jason Park 已提交
146
            })(file, files[file]);
J
Jason Park 已提交
147 148 149 150 151 152 153 154 155
        }
    });
};
var list = {};
$.getJSON('./algorithm/category.json', function (data) {
    list = data;
    var init = false;
    for (var category in list) {
        (function (category) {
J
Jason Park 已提交
156
            var $category = $('<button class="category">').append(list[category].name);
J
Jason Park 已提交
157 158 159
            $category.click(function () {
                $('[data-category="' + category + '"]').toggleClass('fold');
            });
J
Jason Park 已提交
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
            $('#list').append($category);
            var subList = list[category].list;
            for (var algorithm in subList) {
                (function (category, subList, algorithm) {
                    var $algorithm = $('<button class="indent">')
                        .append(subList[algorithm])
                        .attr('data-algorithm', algorithm)
                        .attr('data-category', category)
                        .click(function () {
                            loadAlgorithm(category, algorithm);
                        });
                    $('#list').append($algorithm);
                    if (!init) {
                        init = true;
                        $algorithm.click();
                    }
                })(category, subList, algorithm);
            }
        })(category);
    }
});

var sidemenu_percent;
$('#navigation').click(function () {
    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);
    }
196
    tm.resize();
J
Jason Park 已提交
197 198
});

J
Jason Park 已提交
199 200 201 202 203 204 205 206 207 208
var showErrorToast = function (err) {
    var $toast = $('<div class="toast error">').append(err);
    $('.toast_container').append($toast);
    setTimeout(function () {
        $toast.fadeOut(function () {
            $toast.remove();
        });
    }, 3000);
};

209 210 211 212 213 214 215 216 217 218
var showInfoToast = function (info) {
    var $toast = $('<div class="toast info">').append(info);
    $('.toast_container').append($toast);
    setTimeout(function () {
        $toast.fadeOut(function () {
            $toast.remove();
        });
    }, 3000);
};

J
Jason Park 已提交
219
$('#btn_run').click(function () {
J
Jason Park 已提交
220
    $('#btn_trace').click();
J
Jason Park 已提交
221
    try {
J
Jason Park 已提交
222
        tm.deallocateAll();
J
Jason Park 已提交
223 224
        eval(dataEditor.getValue());
        eval(codeEditor.getValue());
225
        tm.visualize();
J
Jason Park 已提交
226
    } catch (err) {
227
        console.error(err);
J
Jason Park 已提交
228
        showErrorToast(err);
J
Jason Park 已提交
229 230
    } finally {
        tm.removeUnallocated();
J
Jason Park 已提交
231 232 233
    }
});
$('#btn_pause').click(function () {
J
Jason Park 已提交
234
    if (tm.isPause()) {
235
        tm.resumeStep();
J
Jason Park 已提交
236
    } else {
237
        tm.pauseStep();
J
Jason Park 已提交
238 239 240
    }
});
$('#btn_prev').click(function () {
241 242
    tm.pauseStep();
    tm.prevStep();
J
Jason Park 已提交
243 244
});
$('#btn_next').click(function () {
245 246
    tm.pauseStep();
    tm.nextStep();
J
Jason Park 已提交
247 248
});

J
Jason Park 已提交
249
$('#btn_desc').click(function () {
J
Jason Park 已提交
250
    $('.tab_container > .tab').removeClass('active');
J
Jason Park 已提交
251
    $('#tab_desc').addClass('active');
J
Jason Park 已提交
252 253 254 255 256
    $('.tab_bar > button').removeClass('active');
    $(this).addClass('active');
});
$('#btn_trace').click(function () {
    $('.tab_container > .tab').removeClass('active');
J
Jason Park 已提交
257
    $('#tab_module').addClass('active');
J
Jason Park 已提交
258 259 260 261
    $('.tab_bar > button').removeClass('active');
    $(this).addClass('active');
});

J
Jason Park 已提交
262
$(window).resize(function () {
263
    tm.resize();
J
Jason Park 已提交
264
});
J
Jason Park 已提交
265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280

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];
    (function (divider) {
        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 已提交
281
        var dragging = false;
J
Jason Park 已提交
282 283 284 285 286 287 288 289 290
        if (vertical) {
            $divider.addClass('vertical');
            var _left = -thickness / 2;
            $divider.css({
                top: 0,
                bottom: 0,
                left: _left,
                width: thickness
            });
J
Jason Park 已提交
291
            var x;
J
Jason Park 已提交
292 293 294 295 296 297 298 299 300 301 302 303
            $divider.mousedown(function (e) {
                x = e.pageX;
                dragging = true;
            });
            $(document).mousemove(function (e) {
                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;
304
                    tm.resize();
J
Jason Park 已提交
305 306 307 308 309 310 311 312 313 314 315 316 317 318
                }
            });
            $(document).mouseup(function (e) {
                dragging = false;
            });
        } else {
            $divider.addClass('horizontal');
            var _top = -thickness / 2;
            $divider.css({
                top: _top,
                height: thickness,
                left: 0,
                right: 0
            });
J
Jason Park 已提交
319
            var y;
J
Jason Park 已提交
320 321 322 323 324 325 326 327 328 329 330 331
            $divider.mousedown(function (e) {
                y = e.pageY;
                dragging = true;
            });
            $(document).mousemove(function (e) {
                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;
332
                    tm.resize();
J
Jason Park 已提交
333 334 335 336 337 338 339 340 341
                }
            });
            $(document).mouseup(function (e) {
                dragging = false;
            });
        }

        $second.append($divider);
    })(divider);
J
Jason Park 已提交
342 343
}

344 345
$module_container.on('mousedown', '.module_wrapper', function (e) {
    tm.findOwner(this).mousedown(e);
J
Jason Park 已提交
346
});
347 348
$module_container.on('mousemove', '.module_wrapper', function (e) {
    tm.findOwner(this).mousemove(e);
J
Jason Park 已提交
349 350
});
$(document).mouseup(function (e) {
J
Jason Park 已提交
351
    tm.command('mouseup', e);
J
Jason Park 已提交
352
});
353 354
$module_container.on('DOMMouseScroll mousewheel', '.module_wrapper', function (e) {
    tm.findOwner(this).mousewheel(e);
T
TornjV 已提交
355 356 357 358
});

// Share scratch paper

359 360
var getParameterByName = function (name) {
    var url = window.location.href;
T
TornjV 已提交
361 362 363 364 365 366
    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, " "));
367
};
T
TornjV 已提交
368

369
var shareScratchPaper = function () {
T
TornjV 已提交
370
    var gist = {
371 372 373 374 375
        'description': 'temp',
        'public': true,
        'files': {
            'code.js': {'content': dataEditor.getValue()},
            'data.js': {'content': codeEditor.getValue()}
T
TornjV 已提交
376 377
        }
    };
378
    $.post('https://api.github.com/gists', JSON.stringify(gist), function (res) {
T
TornjV 已提交
379
        var data = JSON.parse(res);
380
        console.log(location.protocol + '//' + location.host + location.pathname + '?scratch-paper=' + data.id);
T
TornjV 已提交
381 382 383 384
    });
};

var loadScratchPaper = function (gistID) {
385
    $.get('https://api.github.com/gists/' + gistID, function (res) {
T
TornjV 已提交
386
        var data = JSON.parse(res);
387
        console.log(data);
T
TornjV 已提交
388
    });
389 390 391 392 393 394
};

if (/[?&]scratch-paper=/.test(location.search)) {
    var gistID = getParameterByName('scratch-paper');
    console.log(gistID);
    loadScratchPaper(gistID);
395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411
}

var toJSON = function (obj) {
    return JSON.stringify(obj, function (key, value) {
        return value === Infinity ? "Infinity" : value;
    });
};

var fromJSON = function (obj) {
    return JSON.parse(obj, function (key, value) {
        return value === "Infinity" ? Infinity : value;
    });
};

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