/usr/lib/python2.7/dist-packages/notebook/static/tree/js/notebooklist.js is in python-notebook 5.2.2-1.
This file is owned by root:root, with mode 0o644.
The actual contents of the file can be viewed below.
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 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 683 684 685 686 687 688 689 690 691 692 693 694 695 696 697 698 699 700 701 702 703 704 705 706 707 708 709 710 711 712 713 714 715 716 717 718 719 720 721 722 723 724 725 726 727 728 729 730 731 732 733 734 735 736 737 738 739 740 741 742 743 744 745 746 747 748 749 750 751 752 753 754 755 756 757 758 759 760 761 762 763 764 765 766 767 768 769 770 771 772 773 774 775 776 777 778 779 780 781 782 783 784 785 786 787 788 789 790 791 792 793 794 795 796 797 798 799 800 801 802 803 804 805 806 807 808 809 810 811 812 813 814 815 816 817 818 819 820 821 822 823 824 825 826 827 828 829 830 831 832 833 834 835 836 837 838 839 840 841 842 843 844 845 846 847 848 849 850 851 852 853 854 855 856 857 858 859 860 861 862 863 864 865 866 867 868 869 870 871 872 873 874 875 876 877 878 879 880 881 882 883 884 885 886 887 888 889 890 891 892 893 894 895 896 897 898 899 900 901 902 903 904 905 906 907 908 909 910 911 912 913 914 915 916 917 918 919 920 921 922 923 924 925 926 927 928 929 930 931 932 933 934 935 936 937 938 939 940 941 942 943 944 945 946 947 948 949 950 951 952 953 954 955 956 957 958 959 960 961 962 963 964 965 966 967 968 969 970 971 972 973 974 975 976 977 978 979 980 981 982 983 984 985 986 987 988 989 990 991 992 993 994 995 996 997 998 999 1000 1001 1002 1003 1004 1005 1006 1007 1008 1009 1010 1011 1012 1013 1014 1015 1016 1017 1018 1019 1020 1021 1022 1023 1024 1025 1026 1027 1028 1029 1030 1031 1032 1033 1034 1035 1036 1037 1038 1039 1040 1041 1042 1043 1044 1045 1046 1047 1048 1049 1050 1051 1052 1053 1054 1055 1056 1057 1058 1059 1060 1061 1062 1063 1064 1065 1066 1067 1068 1069 1070 1071 1072 1073 1074 1075 1076 1077 1078 1079 1080 1081 1082 1083 1084 1085 1086 1087 1088 1089 1090 1091 1092 1093 1094 1095 1096 1097 1098 1099 1100 1101 1102 1103 1104 1105 1106 1107 1108 1109 1110 1111 1112 1113 1114 1115 1116 1117 1118 1119 1120 1121 1122 1123 1124 1125 1126 1127 1128 1129 1130 1131 1132 1133 1134 1135 1136 1137 1138 1139 1140 1141 1142 1143 1144 1145 1146 1147 1148 1149 1150 1151 1152 1153 1154 1155 1156 1157 1158 1159 1160 1161 1162 1163 1164 1165 1166 1167 1168 1169 1170 1171 1172 1173 1174 1175 1176 1177 1178 1179 1180 1181 1182 1183 1184 1185 1186 1187 1188 1189 1190 1191 1192 1193 1194 1195 1196 1197 1198 1199 1200 1201 1202 1203 1204 1205 1206 1207 1208 1209 1210 1211 1212 1213 1214 1215 1216 1217 1218 1219 1220 1221 1222 1223 1224 1225 1226 1227 1228 1229 1230 1231 1232 1233 1234 1235 1236 1237 1238 1239 1240 1241 1242 1243 1244 1245 1246 1247 1248 1249 1250 1251 1252 1253 1254 1255 1256 1257 1258 1259 1260 1261 1262 1263 1264 1265 1266 1267 1268 1269 1270 1271 1272 1273 1274 1275 1276 1277 1278 1279 1280 1281 1282 1283 1284 1285 1286 1287 1288 1289 1290 1291 1292 1293 1294 1295 1296 1297 1298 1299 1300 1301 1302 1303 1304 1305 1306 1307 1308 1309 1310 1311 1312 1313 1314 1315 1316 1317 1318 1319 1320 1321 1322 1323 1324 1325 1326 1327 1328 1329 1330 1331 1332 1333 1334 1335 1336 1337 1338 1339 1340 1341 1342 1343 1344 1345 1346 1347 1348 1349 1350 1351 1352 1353 1354 1355 1356 1357 1358 1359 1360 1361 1362 1363 1364 1365 1366 1367 1368 1369 1370 1371 1372 1373 1374 1375 1376 1377 1378 1379 1380 1381 1382 1383 1384 1385 1386 1387 1388 1389 1390 1391 1392 1393 1394 1395 1396 1397 1398 1399 1400 1401 1402 1403 1404 1405 1406 1407 1408 1409 1410 1411 1412 1413 1414 1415 1416 1417 1418 1419 1420 1421 1422 1423 1424 1425 1426 1427 | // Copyright (c) Jupyter Development Team.
// Distributed under the terms of the Modified BSD License.
define([
'jquery',
'base/js/namespace',
'base/js/utils',
'base/js/i18n',
'base/js/dialog',
'base/js/events',
'base/js/keyboard',
'moment',
'bidi/bidi'
], function($, IPython, utils, i18n, dialog, events, keyboard, moment, bidi) {
"use strict";
var extension = function(path){
/**
* return the last pat after the dot in a filepath
* or the filepath itself if no dots present.
* Empty string if the filepath ends with a dot.
**/
var parts = path.split('.');
return parts[parts.length-1];
};
var item_in = function(item, list) {
// Normalize list and item to lowercase
var normalized_list = list.map(function(_item) {
return _item.toLowerCase();
});
return normalized_list.indexOf(item.toLowerCase()) != -1;
};
var includes_extension = function(filepath, extensionslist) {
return item_in(extension(filepath), extensionslist);
};
var json_or_xml_container_mimetype = function(mimetype) {
// Match */*+json or */*+xml
return (mimetype.substring(mimetype.length - 5) == '+json'
|| mimetype.substring(mimetype.length - 4) == '+xml');
};
function name_sorter(ascending) {
return (function(a, b) {
if (type_order[a['type']] < type_order[b['type']]) {
return -1;
}
if (type_order[a['type']] > type_order[b['type']]) {
return 1;
}
if (a['name'].toLowerCase() < b['name'].toLowerCase()) {
return (ascending) ? -1 : 1;
}
if (a['name'].toLowerCase() > b['name'].toLowerCase()) {
return (ascending) ? 1 : -1;
}
return 0;
});
};
function modified_sorter(ascending) {
var order = ascending ? 1 : 0;
return (function(a, b) {
return utils.datetime_sort_helper(a.last_modified, b.last_modified,
order)
});
}
var sort_functions = {
'sort-name': name_sorter,
'last-modified': modified_sorter
};
var NotebookList = function (selector, options) {
/**
* Constructor
*
* Parameters:
* selector: string
* options: dictionary
* Dictionary of keyword arguments.
* session_list: SessionList instance
* element_name: string
* base_url: string
* notebook_path: string
* contents: Contents instance
*/
var that = this;
this.session_list = options.session_list;
this.events = this.session_list.events;
// allow code re-use by just changing element_name in kernellist.js
this.element_name = options.element_name || 'notebook';
this.selector = selector;
if (this.selector !== undefined) {
this.element = $(selector);
this.style();
this.bind_events();
}
this.notebooks_list = [];
this.sessions = {};
this.base_url = options.base_url || utils.get_body_data("baseUrl");
this.notebook_path = options.notebook_path || utils.get_body_data("notebookPath");
this.contents = options.contents;
if (this.session_list && this.session_list.events) {
this.session_list.events.on('sessions_loaded.Dashboard',
function(e, d) { that.sessions_loaded(d); });
}
this.selected = [];
this.sort_function = name_sorter(1);
// 0 => descending, 1 => ascending
this.sort_id = 'sort-name';
this.sort_direction = 1;
this._max_upload_size_mb = 25;
this.EDIT_MIMETYPES = [
'application/javascript',
'application/x-sh',
'application/vnd.groove-tool-template'
];
};
NotebookList.prototype.style = function () {
var prefix = '#' + this.element_name;
$(prefix + '_toolbar').addClass('list_toolbar');
$(prefix + '_list_info').addClass('toolbar_info');
$(prefix + '_buttons').addClass('toolbar_buttons');
$(prefix + '_list_header').addClass('list_header');
this.element.addClass("list_container");
};
NotebookList.prototype.bind_events = function () {
var that = this;
$('#refresh_' + this.element_name + '_list').click(function () {
that.load_sessions();
});
this.element.bind('dragover', function () {
return false;
});
this.element.bind('drop', function(event){
that.handleFilesUpload(event,'drop');
return false;
});
// Bind events for singleton controls.
if (!NotebookList._bound_singletons) {
NotebookList._bound_singletons = true;
$('#new-file').click(function(e) {
var w = window.open('', IPython._target);
that.contents.new_untitled(that.notebook_path || '', {type: 'file', ext: '.txt'}).then(function(data) {
var url = utils.url_path_join(
that.base_url, 'edit',
utils.encode_uri_components(data.path)
);
w.location = url;
}).catch(function (e) {
w.close();
dialog.modal({
title: i18n.msg._('Creating File Failed'),
body: $('<div/>')
.text(i18n.msg._("An error occurred while creating a new file."))
.append($('<div/>')
.addClass('alert alert-danger')
.text(e.message || e)),
buttons: {
OK: {'class': 'btn-primary'}
}
});
console.warn('Error during New file creation', e);
});
that.load_sessions();
});
$('#new-folder').click(function(e) {
that.contents.new_untitled(that.notebook_path || '', {type: 'directory'})
.then(function(){
that.load_list();
}).catch(function (e) {
dialog.modal({
title: i18n.msg._('Creating Folder Failed'),
body: $('<div/>')
.text(i18n.msg._("An error occurred while creating a new folder."))
.append($('<div/>')
.addClass('alert alert-danger')
.text(e.message || e)),
buttons: {
OK: {'class': 'btn-primary'}
}
});
console.warn('Error during New directory creation', e);
});
that.load_sessions();
});
// Bind events for action buttons.
$('.rename-button').click($.proxy(this.rename_selected, this));
$('.move-button').click($.proxy(this.move_selected, this));
$('.download-button').click($.proxy(this.download_selected, this));
$('.shutdown-button').click($.proxy(this.shutdown_selected, this));
$('.duplicate-button').click($.proxy(this.duplicate_selected, this));
$('.view-button').click($.proxy(this.view_selected, this));
$('.edit-button').click($.proxy(this.edit_selected, this));
$('.delete-button').click($.proxy(this.delete_selected, this));
// Bind events for selection menu buttons.
$('#selector-menu').click(function (event) {
that.select($(event.target).attr('id'));
});
var select_all = $('#select-all');
select_all.change(function () {
if (!select_all.prop('checked') || select_all.data('indeterminate')) {
that.select('select-none');
} else {
that.select('select-all');
}
});
$('#button-select-all').click(function (e) {
// toggle checkbox if the click doesn't come from the checkbox already
if (!$(e.target).is('input[type=checkbox]')) {
if (select_all.prop('checked') || select_all.data('indeterminate')) {
that.select('select-none');
} else {
that.select('select-all');
}
}
});
$('.sort-action').click(function(e) {
var sort_on = e.target.id;
// Clear sort indications in UI
$(".sort-action i").removeClass("fa-arrow-up").removeClass("fa-arrow-down")
if ((that.sort_id === sort_on) && (that.sort_direction === 1)) {
that.sort_list(sort_on, 0);
$("#" + sort_on + " i").addClass("fa-arrow-up");
that.sort_direction = 0;
} else {
that.sort_list(sort_on, 1);
$("#" + sort_on + " i").addClass("fa-arrow-down");
that.sort_direction = 1;
}
that.sort_id = sort_on;
});
}
};
NotebookList.prototype.sort_list = function(id, order) {
if (sort_functions.hasOwnProperty(id)) {
this.sort_function = sort_functions[id](order);
this.draw_notebook_list(this.model_list, this.error_msg);
} else {
console.error("No such sort id: '" + id + "'")
}
};
NotebookList.prototype.handleFilesUpload = function(event, dropOrForm) {
var that = this;
var files;
if(dropOrForm === 'drop'){
files = event.originalEvent.dataTransfer.files;
} else
{
files = event.originalEvent.target.files;
}
var reader_onload = function (event) {
var item = $(event.target).data('item');
that.add_file_data(event.target.result, item);
that.add_upload_button(item);
};
var reader_onerror = function (event) {
var item = $(event.target).data('item');
var name = item.data('name');
item.remove();
dialog.modal({
title : i18n.msg._('Failed to read file'),
body : i18n.msg.sprintf(i18n.msg._("Failed to read file %s"),name),
buttons : {'OK' : { 'class' : 'btn-primary' }}
});
};
for (var i = 0; i < files.length; i++) {
var f = files[i];
var name_and_ext = utils.splitext(f.name);
var file_ext = name_and_ext[1];
if (f.size > this._max_upload_size_mb * 1024 * 1024) {
var body_msg = i18n.msg.sprintf(i18n.msg._("The file size is %d MB. Do you still want to upload it?"),
Math.round(f.size / (1024 * 1024)));
dialog.modal({
title : i18n.msg._('Large file size warning'),
body : body_msg,
buttons : {
Cancel: {},
Ok: {
class: "btn-primary",
click: function() {
that.add_large_file_upload_button(f);
}
}
}
});
}
else{
var reader = new FileReader();
if (file_ext === '.ipynb') {
reader.readAsText(f);
} else {
// read non-notebook files as binary
reader.readAsArrayBuffer(f);
}
var item = that.new_item(0, true);
item.addClass('new-file');
that.add_name_input(f.name, item, file_ext === '.ipynb' ? 'notebook' : 'file');
// Store the list item in the reader so we can use it later
// to know which item it belongs to.
$(reader).data('item', item);
reader.onload = reader_onload;
reader.onerror = reader_onerror;
}
}
// Replace the file input form wth a clone of itself. This is required to
// reset the form. Otherwise, if you upload a file, delete it and try to
// upload it again, the changed event won't fire.
var form = $('input.fileinput');
form.replaceWith(form.clone(true));
return false;
};
NotebookList.prototype.clear_list = function (remove_uploads) {
/**
* Clears the navigation tree.
*
* Parameters
* remove_uploads: bool=False
* Should upload prompts also be removed from the tree.
*/
if (remove_uploads) {
this.element.children('.list_item').remove();
} else {
this.element.children('.list_item:not(.new-file)').remove();
}
};
NotebookList.prototype.load_sessions = function(){
this.session_list.load_sessions();
};
NotebookList.prototype.sessions_loaded = function(data){
this.sessions = data;
this.load_list();
};
NotebookList.prototype.load_list = function () {
var that = this;
this.contents.list_contents(that.notebook_path).then(
$.proxy(this.draw_notebook_list, this),
function(error) {
that.draw_notebook_list({content: []}, i18n.msg._("Server error: ") + error.message);
}
);
};
/**
* Draw the list of notebooks
* @method draw_notebook_list
* @param {Array} list An array of dictionaries representing files or
* directories.
* @param {String} error_msg An error message
*/
var type_order = {'directory':0,'notebook':1,'file':2};
NotebookList.prototype.draw_notebook_list = function (list, error_msg) {
// Remember what was selected before the refresh.
var selected_before = this.selected;
// Store the data to be redrawn by sorting
this.model_list = list;
this.error_msg = error_msg;
list.content.sort(this.sort_function);
var message = error_msg || i18n.msg._('The notebook list is empty.');
var item = null;
var model = null;
var len = list.content.length;
this.clear_list();
var n_uploads = this.element.children('.list_item').length;
if (len === 0) {
item = this.new_item(0);
var span12 = item.children().first();
span12.empty();
span12.append($('<div style="margin:auto;text-align:center;color:grey"/>').text(message));
}
var path = this.notebook_path;
var offset = n_uploads;
if (path !== '') {
item = this.new_item(offset, false);
model = {
type: 'directory',
name: '..',
path: utils.url_path_split(path)[0],
};
this.add_link(model, item);
offset += 1;
}
for (var i=0; i<len; i++) {
model = list.content[i];
item = this.new_item(i+offset, true);
try {
this.add_link(model, item);
} catch(err) {
console.log('Error adding link: ' + err);
}
}
// Trigger an event when we've finished drawing the notebook list.
events.trigger('draw_notebook_list.NotebookList');
// Reselect the items that were selected before. Notify listeners
// that the selected items may have changed. O(n^2) operation.
selected_before.forEach(function(item) {
var list_items = $('.list_item');
for (var i=0; i<list_items.length; i++) {
var $list_item = $(list_items[i]);
if ($list_item.data('path') === item.path) {
$list_item.find('input[type=checkbox]').prop('checked', true);
break;
}
}
});
this._selection_changed();
};
/**
* Creates a new item.
* @param {integer} index
* @param {boolean} [selectable] - tristate, undefined: don't draw checkbox,
* false: don't draw checkbox but pad
* where it should be, true: draw checkbox.
* @return {JQuery} row
*/
NotebookList.prototype.new_item = function (index, selectable) {
var row = $('<div/>')
.addClass("list_item")
.addClass("row");
var item = $("<div/>")
.addClass("col-md-12")
.appendTo(row);
var checkbox;
if (selectable !== undefined) {
checkbox = $('<input/>')
.attr('type', 'checkbox')
.attr('title', i18n.msg._('Click here to rename, delete, etc.'))
.appendTo(item);
}
$('<i/>')
.addClass('item_icon')
.appendTo(item);
var link = $("<a/>")
.addClass("item_link")
.appendTo(item);
$("<span/>")
.addClass("item_name")
.appendTo(link);
$("<span/>")
.addClass("item_modified")
.addClass("pull-right")
.appendTo(item);
if (selectable === false) {
checkbox.css('visibility', 'hidden');
} else if (selectable === true) {
var that = this;
row.click(function(e) {
// toggle checkbox only if the click doesn't come from the checkbox or the link
if (!$(e.target).is('span[class=item_name]') && !$(e.target).is('input[type=checkbox]')) {
checkbox.prop('checked', !checkbox.prop('checked'));
}
that._selection_changed();
});
}
var buttons = $('<div/>')
.addClass("item_buttons pull-right")
.appendTo(item);
$('<div/>')
.addClass('running-indicator')
.text(i18n.msg._('Running'))
.css('visibility', 'hidden')
.appendTo(buttons);
if (index === -1) {
this.element.append(row);
} else {
this.element.children().eq(index).after(row);
}
return row;
};
NotebookList.icons = {
directory: 'folder_icon',
notebook: 'notebook_icon',
file: 'file_icon',
};
NotebookList.uri_prefixes = {
directory: 'tree',
notebook: 'notebooks',
file: 'edit',
};
/**
* Select all items in the tree of specified type.
* selection_type : string among "select-all", "select-folders", "select-notebooks", "select-running-notebooks", "select-files"
* any other string (like "select-none") deselects all items
*/
NotebookList.prototype.select = function(selection_type) {
var that = this;
$('.list_item').each(function(index, item) {
var item_type = $(item).data('type');
var state = false;
state = state || (selection_type === "select-all");
state = state || (selection_type === "select-folders" && item_type === 'directory');
state = state || (selection_type === "select-notebooks" && item_type === 'notebook');
state = state || (selection_type === "select-running-notebooks" && item_type === 'notebook' && that.sessions[$(item).data('path')] !== undefined);
state = state || (selection_type === "select-files" && item_type === 'file');
$(item).find('input[type=checkbox]').prop('checked', state);
});
this._selection_changed();
};
NotebookList.prototype._is_notebook = function(model) {
var ipynb_extensions = ['ipynb'];
return includes_extension(model.path, ipynb_extensions);
};
NotebookList.prototype._is_editable = function(model) {
// Allow any file to be "edited"
// Non-text files will display the following error:
// Error: [FILE] is not UTF-8 encoded
// Saving is disabled.
// See Console for more details.
return true;
};
NotebookList.prototype._is_viewable = function(model) {
var html_types = ['htm', 'html', 'xhtml', 'xml', 'mht', 'mhtml'];
var media_extension = ['3gp', 'avi', 'mov', 'mp4', 'm4v', 'm4a', 'mp3', 'mkv', 'ogv', 'ogm', 'ogg', 'oga', 'webm', 'wav'];
var image_type = ['bmp', 'gif', 'jpg', 'jpeg', 'png', 'webp'];
var other_type = ['ico'];
var viewable_extensions = [].concat(html_types, media_extension, image_type, other_type);
return model.mimetype === 'text/html'
|| includes_extension(model.path, viewable_extensions);
};
/**
* Handles when any row selector checkbox is toggled.
*/
NotebookList.prototype._selection_changed = function() {
// Use a JQuery selector to find each row with a checked checkbox. If
// we decide to add more checkboxes in the future, this code will need
// to be changed to distinguish which checkbox is the row selector.
var that = this;
var selected = [];
var has_running_notebook = false;
var has_directory = false;
var has_file = false;
var that = this;
var checked = 0;
$('.list_item :checked').each(function(index, item) {
var parent = $(item).parent().parent();
// If the item doesn't have an upload button, isn't the
// breadcrumbs and isn't the parent folder '..', then it can be selected.
// Breadcrumbs path == ''.
if (parent.find('.upload_button').length === 0 && parent.data('path') !== '' && parent.data('path') !== utils.url_path_split(that.notebook_path)[0]) {
checked++;
selected.push({
name: parent.data('name'),
path: parent.data('path'),
type: parent.data('type')
});
// Set flags according to what is selected. Flags are later
// used to decide which action buttons are visible.
has_running_notebook = has_running_notebook ||
(parent.data('type') === 'notebook' && that.sessions[parent.data('path')] !== undefined);
has_file = has_file || (parent.data('type') === 'file');
has_directory = has_directory || (parent.data('type') === 'directory');
}
});
this.selected = selected;
// Rename is only visible when one item is selected, and it is not a running notebook
if (selected.length === 1 && !has_running_notebook) {
$('.rename-button').css('display', 'inline-block');
} else {
$('.rename-button').css('display', 'none');
}
// Move is visible if at least one item is selected, and none of them
// are a running notebook.
if (selected.length > 0 && !has_running_notebook) {
$('.move-button').css('display', 'inline-block');
} else {
$('.move-button').css('display', 'none');
}
// Download is only visible when one item is selected, and it is not a
// running notebook or a directory
// TODO(nhdaly): Add support for download multiple items at once.
if (selected.length === 1 && !has_running_notebook && !has_directory) {
$('.download-button').css('display', 'inline-block');
} else {
$('.download-button').css('display', 'none');
}
// Shutdown is only visible when one or more notebooks running notebooks
// are selected and no non-notebook items are selected.
if (has_running_notebook && !(has_file || has_directory)) {
$('.shutdown-button').css('display', 'inline-block');
} else {
$('.shutdown-button').css('display', 'none');
}
// Duplicate isn't visible when a directory is selected.
if (selected.length > 0 && !has_directory) {
$('.duplicate-button').css('display', 'inline-block');
} else {
$('.duplicate-button').css('display', 'none');
}
// Delete is visible if one or more items are selected.
if (selected.length > 0) {
$('.delete-button').css('display', 'inline-block');
} else {
$('.delete-button').css('display', 'none');
}
// View is visible in the following case:
//
// - the item is editable
// - it is not a notebook
//
// If it's not editable or unknown, the default action should be view
// already so no need to show the button.
// That should include things like, html, py, txt, json....
if (selected.length >= 1 && !has_directory) {
$('.view-button').css('display', 'inline-block');
} else {
$('.view-button').css('display', 'none');
}
// Edit is visible when an item is unknown, that is to say:
// - not in the editable list
// - not in the known non-editable list.
// - not a notebook.
// Indeed if it's editable the default action is already to edit.
// And non editable files should not show edit button.
// for unknown we'll assume users know what they are doing.
if (selected.length >= 1 && !has_directory && selected.every(function(el) {
return that._is_editable(el);
})) {
$('.edit-button').css('display', 'inline-block');
} else {
$('.edit-button').css('display', 'none');
}
// If all of the items are selected, show the selector as checked. If
// some of the items are selected, show it as checked. Otherwise,
// uncheck it.
var total = 0;
$('.list_item input[type=checkbox]').each(function(index, item) {
var parent = $(item).parent().parent();
// If the item doesn't have an upload button and it's not the
// breadcrumbs, it can be selected. Breadcrumbs path == ''.
if (parent.find('.upload_button').length === 0 && parent.data('path') !== '' && parent.data('path') !== utils.url_path_split(that.notebook_path)[0]) {
total++;
}
});
var select_all = $("#select-all");
if (checked === 0) {
select_all.prop('checked', false);
select_all.prop('indeterminate', false);
select_all.data('indeterminate', false);
} else if (checked === total) {
select_all.prop('checked', true);
select_all.prop('indeterminate', false);
select_all.data('indeterminate', false);
} else {
select_all.prop('checked', false);
select_all.prop('indeterminate', true);
select_all.data('indeterminate', true);
}
// Update total counter
checked = bidi.applyBidi(checked);
$('#counter-select-all').html(checked===0 ? ' ' : checked);
// If at aleast on item is selected, hide the selection instructions.
if (checked > 0) {
$('.dynamic-instructions').hide();
} else {
$('.dynamic-instructions').show();
}
};
NotebookList.prototype.add_link = function (model, item) {
var running = (model.type === 'notebook' && this.sessions[model.path] !== undefined);
item.data('name',model.name);
item.data('path', model.path);
item.data('modified', model.last_modified);
item.data('type', model.type);
item.find(".item_name").text(bidi.applyBidi(model.name));
var icon = NotebookList.icons[model.type];
if (running) {
icon = 'running_' + icon;
}
var uri_prefix = NotebookList.uri_prefixes[model.type];
if (model.type === 'file' && this._is_viewable(model))
{
uri_prefix = 'view';
}
if (model.type === 'file' && this._is_notebook(model))
{
uri_prefix = 'notebooks';
}
item.find(".item_icon").addClass(icon).addClass('icon-fixed-width');
var link = item.find("a.item_link")
.attr('href',
utils.url_path_join(
this.base_url,
uri_prefix,
utils.encode_uri_components(model.path)
)
);
item.find(".item_buttons .running-indicator").css('visibility', running ? '' : 'hidden');
// directory nav doesn't open new tabs
// files, notebooks do
if (model.type !== "directory") {
link.attr('target',IPython._target);
}
// Add in the date that the file was last modified
item.find(".item_modified").text(utils.format_datetime(model.last_modified));
item.find(".item_modified").attr("title", moment(model.last_modified).format("YYYY-MM-DD HH:mm"));
};
NotebookList.prototype.add_name_input = function (name, item, icon_type) {
item.data('name', name);
item.find(".item_icon").addClass(NotebookList.icons[icon_type]).addClass('icon-fixed-width');
item.find(".item_name").empty().append(
$('<input/>')
.addClass("filename_input")
.attr('value', name)
.attr('size', '30')
.attr('type', 'text')
.keyup(function(event){
if(event.keyCode === 13){item.find('.upload_button').click();}
else if(event.keyCode === 27){item.remove();}
})
);
};
NotebookList.prototype.add_file_data = function (data, item) {
item.data('filedata', data);
};
NotebookList.prototype.shutdown_selected = function() {
var that = this;
this.selected.forEach(function(item) {
if (item.type === 'notebook') {
that.shutdown_notebook(item.path);
}
});
// Deselect items after successful shutdown.
that.select('select-none');
};
NotebookList.prototype.shutdown_notebook = function(path) {
var that = this;
var settings = {
processData : false,
cache : false,
type : "DELETE",
dataType : "json",
success : function () {
that.load_sessions();
},
error : utils.log_ajax_error,
};
var session = this.sessions[path];
if (session) {
var url = utils.url_path_join(
this.base_url,
'api/sessions',
encodeURIComponent(session.id)
);
utils.ajax(url, settings);
}
};
NotebookList.prototype.rename_selected = function() {
if (this.selected.length !== 1){
return;
}
var that = this;
var item_path = this.selected[0].path;
var item_name = this.selected[0].name;
var item_type = this.selected[0].type;
var input = $('<input/>').attr('type','text').attr('size','25').addClass('form-control')
.val(item_name);
var rename_msg = function (type) {
switch(type) {
case 'file': return i18n.msg._("Enter a new file name:");
case 'directory': return i18n.msg._("Enter a new directory name:");
case 'notebook': return i18n.msg._("Enter a new notebook name:");
default: return i18n.msg._("Enter a new name:");
}
}
var rename_title = function (type) {
switch(type) {
case 'file': return i18n.msg._("Rename file");
case 'directory': return i18n.msg._("Rename directory");
case 'notebook': return i18n.msg._("Rename notebook");
default: return i18n.msg._("Rename");
}
}
var dialog_body = $('<div/>').append(
$("<p/>").addClass("rename-message")
.text(rename_msg(item_type))
).append(
$("<br/>")
).append(input);
// This statement is used simply so that message extraction
// will pick up the strings. The actual setting of the text
// for the button is in dialog.js.
var button_labels = [ i18n.msg._("Cancel"), i18n.msg._("Rename"), i18n.msg._("OK"), i18n.msg._("Move")];
var d = dialog.modal({
title : rename_title(item_type),
body : dialog_body,
default_button: "Cancel",
buttons : {
Cancel: {},
Rename : {
class: "btn-primary",
click: function() {
that.contents.rename(item_path, utils.url_path_join(that.notebook_path, input.val())).then(function() {
that.load_list();
// Deselect items after successful rename.
that.select('select-none');
}).catch(function(e) {
var template = i18n.msg._("An error occurred while renaming \"%1$s\" to \"%2$s\".");
var failmsg = i18n.msg.sprintf(template,item_name,input.val());
dialog.modal({
title: i18n.msg._("Rename Failed"),
body: $('<div/>')
.text(failmsg)
.append($('<div/>')
.addClass('alert alert-danger')
.text(e.message || e)),
buttons: {
OK: {'class': 'btn-primary'}
}
});
console.warn('Error during renaming :', e);
});
}
}
},
open : function () {
// Upon ENTER, click the OK button.
input.keydown(function (event) {
if (event.which === keyboard.keycodes.enter) {
d.find('.btn-primary').first().click();
return false;
}
});
input.focus();
// Highlight the filename (up to the filetype suffix) in the input field.
if (input.val().indexOf(".") > 0) {
input[0].setSelectionRange(0,input.val().indexOf("."));
} else {
input.select();
}
}
});
};
NotebookList.prototype.move_selected = function() {
var that = this;
var selected = that.selected.slice(); // Don't let that.selected change out from under us
var num_items = selected.length;
// Can move one or more selected items.
if (!(num_items >= 1)) {
return;
}
// Open a dialog to enter the new path, with current path as default.
var input = $('<input/>').attr('type','text').attr('size','25').addClass('form-control')
.val(utils.url_path_join('/', that.notebook_path));
var dialog_body = $('<div/>').append(
$("<p/>").addClass("rename-message")
.text(i18n.msg.sprintf(i18n.msg.ngettext("Enter a new destination directory path for this item:",
"Enter a new destination directory path for these %d items:", num_items),num_items))
).append(
$("<br/>")
).append(
$("<div/>").append(
// $("<i/>").addClass("fa fa-folder").addClass("server-root")
$("<span/>").text(utils.get_body_data("serverRoot")).addClass("server-root")
).append(
input.addClass("path-input")
).addClass("move-path")
);
var d = dialog.modal({
title : i18n.msg.sprintf(i18n.msg.ngettext("Move an Item","Move %d Items",num_items),num_items),
body : dialog_body,
default_button: "Cancel",
buttons : {
Cancel : {},
Move : {
class: "btn-primary",
click: function() {
// Move all the items.
selected.forEach(function(item) {
var item_path = item.path;
var item_name = item.name;
// Construct the new path using the user input and the item's name.
var new_path = utils.url_path_join(input.val(), item_name);
that.contents.rename(item_path, new_path).then(function() {
// After each move finishes, reload the list.
that.load_list();
}).catch(function(e) {
// If any of the moves fails, show this dialog for that move.
var failmsg = i18n.msg._("An error occurred while moving \"%1$s\" from \"%2$s\" to \"%3$s\".");
dialog.modal({
title: i18n.msg._("Move Failed"),
body: $('<div/>')
.text(i18n.msg.sprintf(failmsg,item_name,item_path,new_path))
.append($('<div/>')
.addClass('alert alert-danger')
.text(e.message || e)),
buttons: {
OK: {'class': 'btn-primary'}
}
});
console.warn('Error during moving :', e);
});
}); // End of forEach.
}
}
},
// TODO: Consider adding fancier UI per Issue #941.
open : function () {
// Upon ENTER, click the OK button.
input.keydown(function (event) {
if (event.which === keyboard.keycodes.enter) {
d.find('.btn-primary').first().click();
return false;
}
});
// Put the cursor at the end of the input.
input.focus();
}
});
};
NotebookList.prototype.download_selected = function() {
var that = this;
// TODO(nhdaly): Support download multiple items at once.
if (that.selected.length !== 1){
return;
}
var item_path = that.selected[0].path;
window.open(utils.url_path_join(that.base_url, 'files', utils.encode_uri_components(item_path)) + '?download=1', IPython._target);
};
NotebookList.prototype.delete_selected = function() {
var selected = this.selected.slice(); // Don't let that.selected change out from under us
var template = i18n.msg.ngettext("Are you sure you want to permanently delete: \"%s\"?",
"Are you sure you want to permanently delete the %d files or folders selected?",
selected.length);
var delete_msg;
if (selected.length === 1) {
delete_msg = i18n.msg.sprintf(template, selected[0].name);
} else {
delete_msg = i18n.msg.sprintf(template, selected.length);
}
var that = this;
dialog.modal({
title : i18n.msg._("Delete"),
body : delete_msg,
default_button: "Cancel",
buttons : {
Cancel: {},
Delete : {
class: "btn-danger",
click: function() {
// Shutdown any/all selected notebooks before deleting
// the files.
that.shutdown_selected();
// Delete selected.
selected.forEach(function(item) {
that.contents.delete(item.path).then(function() {
that.notebook_deleted(item.path);
}).catch(function(e) {
var failmsg = i18n.msg._("An error occurred while deleting \"%s\".");
dialog.modal({
title: i18n.msg._("Delete Failed"),
body: $('<div/>')
.text(i18n.msg.sprintf(failmsg, item.path))
.append($('<div/>')
.addClass('alert alert-danger')
.text(e.message || e)),
buttons: {
OK: {'class': 'btn-primary'}
}
});
console.warn('Error during content deletion:', e);
});
});
}
}
}
});
};
NotebookList.prototype.view_selected = function() {
var that = this;
that.selected.forEach(function(item) {
var item_path = utils.encode_uri_components(item.path);
var item_type = that._is_notebook(item) ? 'notebooks' : that._is_viewable(item) ? 'view' : 'files';
window.open(utils.url_path_join(that.base_url, item_type, item_path), IPython._target);
});
};
NotebookList.prototype.edit_selected = function() {
var that = this;
that.selected.forEach(function(item) {
var item_path = utils.encode_uri_components(item.path);
window.open(utils.url_path_join(that.base_url, 'edit', item_path), IPython._target);
});
};
NotebookList.prototype.duplicate_selected = function() {
var selected = this.selected.slice(); // Don't let that.selected change out from under us
var template = i18n.msg.ngettext("Are you sure you want to duplicate: \"%s\"?",
"Are you sure you want to duplicate the %d files selected?",selected.length);
var dup_msg;
if (selected.length === 1) {
dup_msg = i18n.msg.sprintf(template,selected[0].name);
} else {
dup_msg = i18n.msg.sprintf(template,selected.length);
}
var that = this;
dialog.modal({
title : i18n.msg._("Duplicate"),
body : dup_msg,
default_button: "Cancel",
buttons : {
Cancel: {},
Duplicate : {
class: "btn-primary",
click: function() {
selected.forEach(function(item) {
that.contents.copy(item.path, that.notebook_path).then(function () {
that.load_list();
// Deselect items after successful duplication.
that.select('select-none');
}).catch(function(e) {
var failmsg = i18n.msg._("An error occurred while duplicating \"%s\".");
dialog.modal({
title: i18n.msg._("Duplicate Failed"),
body: $('<div/>')
.text(i18n.msg.sprintf(failmsg,item.path))
.append($('<div/>')
.addClass('alert alert-danger')
.text(e.message || e)),
buttons: {
OK: {'class': 'btn-primary'}
}
});
console.warn('Error during content duplication', e);
});
});
}
}
}
});
};
NotebookList.prototype.notebook_deleted = function(path) {
/**
* Remove the deleted notebook.
*/
var that = this;
$(".list_item").each(function() {
var element = $(this);
if (element.data("path") === path) {
element.remove();
events.trigger('notebook_deleted.NotebookList');
that._selection_changed();
}
});
};
// Add a new class for large file upload
NotebookList.prototype.add_large_file_upload_button = function (file) {
var that = this;
var item = that.new_item(0, true);
item.addClass('new-file');
that.add_name_input(file.name, item, 'file');
var cancel_button = $('<button/>').text("Cancel")
.addClass("btn btn-default btn-xs")
.click(function (e) {
item.remove();
return false;
});
var upload_button = $('<button/>').text("Upload")
.addClass('btn btn-primary btn-xs upload_button')
.click(function (e) {
var filename = item.find('.item_name > input').val();
var path = utils.url_path_join(that.notebook_path, filename);
var format = 'text';
if (filename.length === 0 || filename[0] === '.') {
dialog.modal({
title : 'Invalid file name',
body : "File names must be at least one character and not start with a dot",
buttons : {'OK' : { 'class' : 'btn-primary' }}
});
return false;
}
var check_exist = function () {
var exists = false;
$.each(that.element.find('.list_item:not(.new-file)'), function(k,v){
if ($(v).data('name') === filename) { exists = true; return false; }
});
return exists
}
var exists = check_exist();
var add_uploading_button = function (f, item) {
// change buttons, add a progress bar
var uploading_button = item.find('.upload_button').text("Uploading");
uploading_button.off('click'); // Prevent double upload
var progress_bar = $('<span/>')
.addClass('progress-bar')
.css('top', '0')
.css('left', '0')
.css('width', '0')
.css('height', '3px')
.css('border-radius', '0 0 0 0')
.css('display', 'inline-block')
.css('position', 'absolute');
var parse_large_file = function (f, item) {
// codes inspired by http://stackoverflow.com/a/28318964
var chunk_size = 1024 * 1024;
var offset = 0;
var chunk = 0;
var chunk_reader = null;
var upload_file = null;
var large_reader_onload = function (event) {
if (event.target.error == null) {
offset += chunk_size;
if (offset >= f.size) {
chunk = -1;
} else {
chunk += 1;
}
// callback for handling reading: reader_onload in add_upload_button
var item = $(event.target).data('item');
that.add_file_data(event.target.result, item);
upload_file(item, chunk); // Do the upload
} else {
console.log("Read error: " + event.target.error);
return;
}
};
var on_error = function (event) {
var item = $(event.target).data('item');
var name = item.data('name');
item.remove();
var _exists = check_exist();
if (_exists) {
that.contents.delete(path);
}
dialog.modal({
title : 'Failed to read file',
body : "Failed to read file '" + name + "'",
buttons : {'OK' : { 'class' : 'btn-primary' }}
});
}
chunk_reader = function (_offset, _f) {
var reader = new FileReader();
var blob = _f.slice(_offset, chunk_size + _offset);
// Load everything as ArrayBuffer
reader.readAsArrayBuffer(blob);
// Store the list item in the reader so we can use it later
// to know which item it belongs to.
$(reader).data('item', item);
reader.onload = large_reader_onload;
reader.onerror = on_error;
};
// These codes to upload file in original class
var upload_file = function(item, chunk) {
var filedata = item.data('filedata');
if (filedata instanceof ArrayBuffer) {
// base64-encode binary file data
var bytes = '';
var buf = new Uint8Array(filedata);
var nbytes = buf.byteLength;
for (var i=0; i<nbytes; i++) {
bytes += String.fromCharCode(buf[i]);
}
filedata = btoa(bytes);
format = 'base64';
}
var model = { name: filename, path: path };
var name_and_ext = utils.splitext(filename);
var file_ext = name_and_ext[1];
var content_type;
// Treat everything as generic file
model.type = 'file';
model.format = format;
content_type = 'application/octet-stream';
model.chunk = chunk;
model.content = filedata;
var on_success = function (event) {
if (offset < f.size) {
// of to the next chunk
chunk_reader(offset, f);
// change progress bar and progress button
var progress = offset / f.size * 100;
progress = progress > 100 ? 100 : progress;
uploading_button.text(progress.toFixed(0)+'%');
progress_bar.css('width', progress+'%')
.attr('aria-valuenow', progress.toString());
} else {
item.removeClass('new-file');
that.add_link(model, item);
that.session_list.load_sessions();
}
};
that.contents.save(path, model).then(on_success, on_error);
}
// now let's start the read with the first block
chunk_reader(offset, f);
};
item.find('.item_buttons')
.append(progress_bar);
parse_large_file(f, item);
};
if (exists) {
dialog.modal({
title : "Replace file",
body : 'There is already a file named ' + filename + ', do you want to replace it?',
default_button: "Cancel",
buttons : {
Overwrite : {
class: "btn-danger",
click: function () {
add_uploading_button(file, item);
}
},
Cancel : {
click: function() { item.remove(); }
}
}
});
} else {
add_uploading_button(file, item);
}
return false;
});
item.find(".item_buttons").empty()
.append(upload_button)
.append(cancel_button);
}
NotebookList.prototype.add_upload_button = function (item) {
var that = this;
var upload_button = $('<button/>').text(i18n.msg._("Upload"))
.addClass('btn btn-primary btn-xs upload_button')
.click(function (e) {
var filename = item.find('.item_name > input').val();
var path = utils.url_path_join(that.notebook_path, filename);
var filedata = item.data('filedata');
var format = 'text';
if (filename.length === 0 || filename[0] === '.') {
dialog.modal({
title : i18n.msg._('Invalid file name'),
body : i18n.msg._("File names must be at least one character and not start with a period"),
buttons : {'OK' : { 'class' : 'btn-primary' }}
});
return false;
}
if (filedata instanceof ArrayBuffer) {
// base64-encode binary file data
var bytes = '';
var buf = new Uint8Array(filedata);
var nbytes = buf.byteLength;
for (var i=0; i<nbytes; i++) {
bytes += String.fromCharCode(buf[i]);
}
filedata = btoa(bytes);
format = 'base64';
}
var model = { name: filename, path: path };
var name_and_ext = utils.splitext(filename);
var file_ext = name_and_ext[1];
var content_type;
if (file_ext === '.ipynb') {
model.type = 'notebook';
model.format = 'json';
try {
model.content = JSON.parse(filedata);
} catch (e) {
var failbody = i18n.msg._("The error was: %s");
dialog.modal({
title : i18n.msg._('Cannot upload invalid Notebook'),
body : i18n.msg.sprintf(failbody,e),
buttons : {'OK' : {
'class' : 'btn-primary',
click: function () {
item.remove();
}
}}
});
console.warn('Error during notebook uploading', e);
return false;
}
content_type = 'application/json';
} else {
model.type = 'file';
model.format = format;
model.content = filedata;
content_type = 'application/octet-stream';
}
filedata = item.data('filedata');
var on_success = function () {
item.removeClass('new-file');
that.add_link(model, item);
that.session_list.load_sessions();
};
var exists = false;
$.each(that.element.find('.list_item:not(.new-file)'), function(k,v){
if ($(v).data('name') === filename) { exists = true; return false; }
});
if (exists) {
var body = i18n.msg._("There is already a file named \"%s\". Do you want to replace it?");
dialog.modal({
title : i18n.msg._("Replace file"),
body : i18n.msg.sprintf(body,filename),
default_button: "Cancel",
buttons : {
Cancel : {
click: function() { item.remove(); }
},
Overwrite : {
class: "btn-danger",
click: function () {
that.contents.save(path, model).then(on_success);
}
}
}
});
} else {
that.contents.save(path, model).then(on_success);
}
return false;
});
var cancel_button = $('<button/>').text(i18n.msg._("Cancel"))
.addClass("btn btn-default btn-xs")
.click(function (e) {
item.remove();
return false;
});
item.find(".item_buttons").empty()
.append(upload_button)
.append(cancel_button);
};
return {'NotebookList': NotebookList};
});
|