##// END OF EJS Templates
Dont prompt for name.
Jonathan Frederic -
Show More
@@ -1,630 +1,540 b''
1 1 // Copyright (c) IPython Development Team.
2 2 // Distributed under the terms of the Modified BSD License.
3 3
4 4 define([
5 5 'base/js/namespace',
6 6 'jquery',
7 7 'base/js/utils',
8 8 'base/js/dialog',
9 9 'base/js/events',
10 10 'base/js/keyboard',
11 11 ], function(IPython, $, utils, dialog, events, keyboard) {
12 12 "use strict";
13 13
14 14 var NotebookList = function (selector, options) {
15 15 /**
16 16 * Constructor
17 17 *
18 18 * Parameters:
19 19 * selector: string
20 20 * options: dictionary
21 21 * Dictionary of keyword arguments.
22 22 * session_list: SessionList instance
23 23 * element_name: string
24 24 * base_url: string
25 25 * notebook_path: string
26 26 * contents: Contents instance
27 27 */
28 28 var that = this;
29 29 this.session_list = options.session_list;
30 30 // allow code re-use by just changing element_name in kernellist.js
31 31 this.element_name = options.element_name || 'notebook';
32 32 this.selector = selector;
33 33 if (this.selector !== undefined) {
34 34 this.element = $(selector);
35 35 this.style();
36 36 this.bind_events();
37 37 }
38 38 this.notebooks_list = [];
39 39 this.sessions = {};
40 40 this.base_url = options.base_url || utils.get_body_data("baseUrl");
41 41 this.notebook_path = options.notebook_path || utils.get_body_data("notebookPath");
42 42 this.contents = options.contents;
43 43 if (this.session_list && this.session_list.events) {
44 44 this.session_list.events.on('sessions_loaded.Dashboard',
45 45 function(e, d) { that.sessions_loaded(d); });
46 46 }
47 47 };
48 48
49 49 NotebookList.prototype.style = function () {
50 50 var prefix = '#' + this.element_name;
51 51 $(prefix + '_toolbar').addClass('list_toolbar');
52 52 $(prefix + '_list_info').addClass('toolbar_info');
53 53 $(prefix + '_buttons').addClass('toolbar_buttons');
54 54 $(prefix + '_list_header').addClass('list_header');
55 55 this.element.addClass("list_container");
56 56 };
57 57
58 58 NotebookList.prototype.bind_events = function () {
59 59 var that = this;
60 60 $('#refresh_' + this.element_name + '_list').click(function () {
61 61 that.load_sessions();
62 62 });
63 63 this.element.bind('dragover', function () {
64 64 return false;
65 65 });
66 66 this.element.bind('drop', function(event){
67 67 that.handleFilesUpload(event,'drop');
68 68 return false;
69 69 });
70 70
71 71 // Bind events for singleton controls.
72 72 if (!NotebookList._bound_singletons) {
73 73 NotebookList._bound_singletons = true;
74 74 $('#new-file').click(function(e) {
75 that._prompt_name('File').then(function(name) {
76 that._create('file', name).then(function() {
75 that.contents.new_untitled(that.notebook_path || '', {type: 'file', ext: '.txt'});
77 76 that.load_sessions();
78 77 });
79 });
80 });
81 78 $('#new-folder').click(function(e) {
82 that._prompt_name('Folder').then(function(name) {
83 that._create('directory', name).then(function() {
79 that.contents.new_untitled(that.notebook_path || '', {type: 'directory'});
84 80 that.load_sessions();
85 81 });
86 });
87 });
88 82 }
89 83 };
90 84
91 85 NotebookList.prototype.handleFilesUpload = function(event, dropOrForm) {
92 86 var that = this;
93 87 var files;
94 88 if(dropOrForm =='drop'){
95 89 files = event.originalEvent.dataTransfer.files;
96 90 } else
97 91 {
98 92 files = event.originalEvent.target.files;
99 93 }
100 94 for (var i = 0; i < files.length; i++) {
101 95 var f = files[i];
102 96 var name_and_ext = utils.splitext(f.name);
103 97 var file_ext = name_and_ext[1];
104 98
105 99 var reader = new FileReader();
106 100 if (file_ext === '.ipynb') {
107 101 reader.readAsText(f);
108 102 } else {
109 103 // read non-notebook files as binary
110 104 reader.readAsArrayBuffer(f);
111 105 }
112 106 var item = that.new_item(0);
113 107 item.addClass('new-file');
114 108 that.add_name_input(f.name, item, file_ext == '.ipynb' ? 'notebook' : 'file');
115 109 // Store the list item in the reader so we can use it later
116 110 // to know which item it belongs to.
117 111 $(reader).data('item', item);
118 112 reader.onload = function (event) {
119 113 var item = $(event.target).data('item');
120 114 that.add_file_data(event.target.result, item);
121 115 that.add_upload_button(item);
122 116 };
123 117 reader.onerror = function (event) {
124 118 var item = $(event.target).data('item');
125 119 var name = item.data('name');
126 120 item.remove();
127 121 dialog.modal({
128 122 title : 'Failed to read file',
129 123 body : "Failed to read file '" + name + "'",
130 124 buttons : {'OK' : { 'class' : 'btn-primary' }}
131 125 });
132 126 };
133 127 }
134 128 // Replace the file input form wth a clone of itself. This is required to
135 129 // reset the form. Otherwise, if you upload a file, delete it and try to
136 130 // upload it again, the changed event won't fire.
137 131 var form = $('input.fileinput');
138 132 form.replaceWith(form.clone(true));
139 133 return false;
140 134 };
141 135
142 136 NotebookList.prototype.clear_list = function (remove_uploads) {
143 137 /**
144 138 * Clears the navigation tree.
145 139 *
146 140 * Parameters
147 141 * remove_uploads: bool=False
148 142 * Should upload prompts also be removed from the tree.
149 143 */
150 144 if (remove_uploads) {
151 145 this.element.children('.list_item').remove();
152 146 } else {
153 147 this.element.children('.list_item:not(.new-file)').remove();
154 148 }
155 149 };
156 150
157 151 NotebookList.prototype.load_sessions = function(){
158 152 this.session_list.load_sessions();
159 153 };
160 154
161 155
162 156 NotebookList.prototype.sessions_loaded = function(data){
163 157 this.sessions = data;
164 158 this.load_list();
165 159 };
166 160
167 161 NotebookList.prototype.load_list = function () {
168 162 var that = this;
169 163 this.contents.list_contents(that.notebook_path).then(
170 164 $.proxy(this.draw_notebook_list, this),
171 165 function(error) {
172 166 that.draw_notebook_list({content: []}, "Server error: " + error.message);
173 167 }
174 168 );
175 169 };
176 170
177 171 /**
178 172 * Draw the list of notebooks
179 173 * @method draw_notebook_list
180 174 * @param {Array} list An array of dictionaries representing files or
181 175 * directories.
182 176 * @param {String} error_msg An error message
183 177 */
184 178
185 179
186 180 var type_order = {'directory':0,'notebook':1,'file':2};
187 181
188 182 NotebookList.prototype.draw_notebook_list = function (list, error_msg) {
189 183 list.content.sort(function(a, b) {
190 184 if (type_order[a['type']] < type_order[b['type']]) {
191 185 return -1;
192 186 }
193 187 if (type_order[a['type']] > type_order[b['type']]) {
194 188 return 1;
195 189 }
196 190 if (a['name'] < b['name']) {
197 191 return -1;
198 192 }
199 193 if (a['name'] > b['name']) {
200 194 return 1;
201 195 }
202 196 return 0;
203 197 });
204 198 var message = error_msg || 'Notebook list empty.';
205 199 var item = null;
206 200 var model = null;
207 201 var len = list.content.length;
208 202 this.clear_list();
209 203 var n_uploads = this.element.children('.list_item').length;
210 204 if (len === 0) {
211 205 item = this.new_item(0);
212 206 var span12 = item.children().first();
213 207 span12.empty();
214 208 span12.append($('<div style="margin:auto;text-align:center;color:grey"/>').text(message));
215 209 }
216 210 var path = this.notebook_path;
217 211 var offset = n_uploads;
218 212 if (path !== '') {
219 213 item = this.new_item(offset);
220 214 model = {
221 215 type: 'directory',
222 216 name: '..',
223 217 path: utils.url_path_split(path)[0],
224 218 };
225 219 this.add_link(model, item);
226 220 offset += 1;
227 221 }
228 222 for (var i=0; i<len; i++) {
229 223 model = list.content[i];
230 224 item = this.new_item(i+offset);
231 225 this.add_link(model, item);
232 226 }
233 227 // Trigger an event when we've finished drawing the notebook list.
234 228 events.trigger('draw_notebook_list.NotebookList');
235 229 };
236 230
237 231
238 232 NotebookList.prototype.new_item = function (index) {
239 233 var item = $('<div/>').addClass("list_item").addClass("row");
240 234 // item.addClass('list_item ui-widget ui-widget-content ui-helper-clearfix');
241 235 // item.css('border-top-style','none');
242 236 item.append($("<div/>").addClass("col-md-12").append(
243 237 $('<i/>').addClass('item_icon')
244 238 ).append(
245 239 $("<a/>").addClass("item_link").append(
246 240 $("<span/>").addClass("item_name")
247 241 )
248 242 ).append(
249 243 $('<div/>').addClass("item_buttons pull-right")
250 244 ));
251 245
252 246 if (index === -1) {
253 247 this.element.append(item);
254 248 } else {
255 249 this.element.children().eq(index).after(item);
256 250 }
257 251 return item;
258 252 };
259 253
260 254
261 255 NotebookList.icons = {
262 256 directory: 'folder_icon',
263 257 notebook: 'notebook_icon',
264 258 file: 'file_icon',
265 259 };
266 260
267 261 NotebookList.uri_prefixes = {
268 262 directory: 'tree',
269 263 notebook: 'notebooks',
270 264 file: 'edit',
271 265 };
272 266
273 267
274 268 NotebookList.prototype.add_link = function (model, item) {
275 269 var path = model.path,
276 270 name = model.name;
277 271 item.data('name', name);
278 272 item.data('path', path);
279 273 item.find(".item_name").text(name);
280 274 var icon = NotebookList.icons[model.type];
281 275 var uri_prefix = NotebookList.uri_prefixes[model.type];
282 276 item.find(".item_icon").addClass(icon).addClass('icon-fixed-width');
283 277 var link = item.find("a.item_link")
284 278 .attr('href',
285 279 utils.url_join_encode(
286 280 this.base_url,
287 281 uri_prefix,
288 282 path
289 283 )
290 284 );
291 285 // directory nav doesn't open new tabs
292 286 // files, notebooks do
293 287 if (model.type !== "directory") {
294 288 link.attr('target','_blank');
295 289 }
296 290 if (model.type !== 'directory') {
297 291 this.add_duplicate_button(item);
298 292 }
299 293 if (model.type == 'file') {
300 294 this.add_delete_button(item);
301 295 } else if (model.type == 'notebook') {
302 296 if (this.sessions[path] === undefined){
303 297 this.add_delete_button(item);
304 298 } else {
305 299 this.add_shutdown_button(item, this.sessions[path]);
306 300 }
307 301 }
308 302 };
309 303
310 304
311 305 NotebookList.prototype.add_name_input = function (name, item, icon_type) {
312 306 item.data('name', name);
313 307 item.find(".item_icon").addClass(NotebookList.icons[icon_type]).addClass('icon-fixed-width');
314 308 item.find(".item_name").empty().append(
315 309 $('<input/>')
316 310 .addClass("filename_input")
317 311 .attr('value', name)
318 312 .attr('size', '30')
319 313 .attr('type', 'text')
320 314 .keyup(function(event){
321 315 if(event.keyCode == 13){item.find('.upload_button').click();}
322 316 else if(event.keyCode == 27){item.remove();}
323 317 })
324 318 );
325 319 };
326 320
327 321
328 322 NotebookList.prototype.add_file_data = function (data, item) {
329 323 item.data('filedata', data);
330 324 };
331 325
332 326
333 327 NotebookList.prototype.add_shutdown_button = function (item, session) {
334 328 var that = this;
335 329 var shutdown_button = $("<button/>").text("Shutdown").addClass("btn btn-xs btn-warning").
336 330 click(function (e) {
337 331 var settings = {
338 332 processData : false,
339 333 cache : false,
340 334 type : "DELETE",
341 335 dataType : "json",
342 336 success : function () {
343 337 that.load_sessions();
344 338 },
345 339 error : utils.log_ajax_error,
346 340 };
347 341 var url = utils.url_join_encode(
348 342 that.base_url,
349 343 'api/sessions',
350 344 session
351 345 );
352 346 $.ajax(url, settings);
353 347 return false;
354 348 });
355 349 item.find(".item_buttons").append(shutdown_button);
356 350 };
357 351
358 352 NotebookList.prototype.add_duplicate_button = function (item) {
359 353 var notebooklist = this;
360 354 var duplicate_button = $("<button/>").text("Duplicate").addClass("btn btn-default btn-xs").
361 355 click(function (e) {
362 356 // $(this) is the button that was clicked.
363 357 var that = $(this);
364 358 var name = item.data('name');
365 359 var path = item.data('path');
366 360 var message = 'Are you sure you want to duplicate ' + name + '?';
367 361 var copy_from = {copy_from : path};
368 362 IPython.dialog.modal({
369 363 title : "Duplicate " + name,
370 364 body : message,
371 365 buttons : {
372 366 Duplicate : {
373 367 class: "btn-primary",
374 368 click: function() {
375 369 notebooklist.contents.copy(path, notebooklist.notebook_path).then(function () {
376 370 notebooklist.load_list();
377 371 });
378 372 }
379 373 },
380 374 Cancel : {}
381 375 }
382 376 });
383 377 return false;
384 378 });
385 379 item.find(".item_buttons").append(duplicate_button);
386 380 };
387 381
388 382 NotebookList.prototype.add_delete_button = function (item) {
389 383 var notebooklist = this;
390 384 var delete_button = $("<button/>").text("Delete").addClass("btn btn-default btn-xs").
391 385 click(function (e) {
392 386 // $(this) is the button that was clicked.
393 387 var that = $(this);
394 388 // We use the filename from the parent list_item element's
395 389 // data because the outer scope's values change as we iterate through the loop.
396 390 var parent_item = that.parents('div.list_item');
397 391 var name = parent_item.data('name');
398 392 var path = parent_item.data('path');
399 393 var message = 'Are you sure you want to permanently delete the file: ' + name + '?';
400 394 dialog.modal({
401 395 title : "Delete file",
402 396 body : message,
403 397 buttons : {
404 398 Delete : {
405 399 class: "btn-danger",
406 400 click: function() {
407 401 notebooklist.contents.delete(path).then(
408 402 function() {
409 403 notebooklist.notebook_deleted(path);
410 404 }
411 405 );
412 406 }
413 407 },
414 408 Cancel : {}
415 409 }
416 410 });
417 411 return false;
418 412 });
419 413 item.find(".item_buttons").append(delete_button);
420 414 };
421 415
422 416 NotebookList.prototype.notebook_deleted = function(path) {
423 417 /**
424 418 * Remove the deleted notebook.
425 419 */
426 420 $( ":data(path)" ).each(function() {
427 421 var element = $(this);
428 422 if (element.data("path") == path) {
429 423 element.remove();
430 424 events.trigger('notebook_deleted.NotebookList');
431 425 }
432 426 });
433 427 };
434 428
435 429
436 430 NotebookList.prototype.add_upload_button = function (item) {
437 431 var that = this;
438 432 var upload_button = $('<button/>').text("Upload")
439 433 .addClass('btn btn-primary btn-xs upload_button')
440 434 .click(function (e) {
441 435 var filename = item.find('.item_name > input').val();
442 436 var path = utils.url_path_join(that.notebook_path, filename);
443 437 var filedata = item.data('filedata');
444 438 var format = 'text';
445 439 if (filename.length === 0 || filename[0] === '.') {
446 440 dialog.modal({
447 441 title : 'Invalid file name',
448 442 body : "File names must be at least one character and not start with a dot",
449 443 buttons : {'OK' : { 'class' : 'btn-primary' }}
450 444 });
451 445 return false;
452 446 }
453 447 if (filedata instanceof ArrayBuffer) {
454 448 // base64-encode binary file data
455 449 var bytes = '';
456 450 var buf = new Uint8Array(filedata);
457 451 var nbytes = buf.byteLength;
458 452 for (var i=0; i<nbytes; i++) {
459 453 bytes += String.fromCharCode(buf[i]);
460 454 }
461 455 filedata = btoa(bytes);
462 456 format = 'base64';
463 457 }
464 458 var model = {};
465 459
466 460 var name_and_ext = utils.splitext(filename);
467 461 var file_ext = name_and_ext[1];
468 462 var content_type;
469 463 if (file_ext === '.ipynb') {
470 464 model.type = 'notebook';
471 465 model.format = 'json';
472 466 try {
473 467 model.content = JSON.parse(filedata);
474 468 } catch (e) {
475 469 dialog.modal({
476 470 title : 'Cannot upload invalid Notebook',
477 471 body : "The error was: " + e,
478 472 buttons : {'OK' : {
479 473 'class' : 'btn-primary',
480 474 click: function () {
481 475 item.remove();
482 476 }
483 477 }}
484 478 });
485 479 return false;
486 480 }
487 481 content_type = 'application/json';
488 482 } else {
489 483 model.type = 'file';
490 484 model.format = format;
491 485 model.content = filedata;
492 486 content_type = 'application/octet-stream';
493 487 }
494 488 filedata = item.data('filedata');
495 489
496 490 var on_success = function () {
497 491 item.removeClass('new-file');
498 492 that.add_link(model, item);
499 493 that.add_delete_button(item);
500 494 that.session_list.load_sessions();
501 495 };
502 496
503 497 var exists = false;
504 498 $.each(that.element.find('.list_item:not(.new-file)'), function(k,v){
505 499 if ($(v).data('name') === filename) { exists = true; return false; }
506 500 });
507 501
508 502 if (exists) {
509 503 dialog.modal({
510 504 title : "Replace file",
511 505 body : 'There is already a file named ' + filename + ', do you want to replace it?',
512 506 buttons : {
513 507 Overwrite : {
514 508 class: "btn-danger",
515 509 click: function () {
516 510 that.contents.save(path, model).then(on_success);
517 511 }
518 512 },
519 513 Cancel : {
520 514 click: function() { item.remove(); }
521 515 }
522 516 }
523 517 });
524 518 } else {
525 519 that.contents.save(path, model).then(on_success);
526 520 }
527 521
528 522 return false;
529 523 });
530 524 var cancel_button = $('<button/>').text("Cancel")
531 525 .addClass("btn btn-default btn-xs")
532 526 .click(function (e) {
533 527 item.remove();
534 528 return false;
535 529 });
536 530 item.find(".item_buttons").empty()
537 531 .append(upload_button)
538 532 .append(cancel_button);
539 533 };
540 534
541 /**
542 * Prompt the user for a name.
543 * @param {string} what - What you want a name for.
544 * @return {Promise} Promise that resolve with a string name
545 */
546 NotebookList.prototype._prompt_name = function(what) {
547 var that = this;
548 var dialog_body = $('<div/>').append(
549 $("<p/>").addClass("rename-message")
550 .text(what + ' name:')
551 ).append(
552 $("<br/>")
553 ).append(
554 $('<input/>').attr('type','text').attr('size','25').addClass('form-control')
555 .val('') // Default to empty
556 );
557
558 return new Promise(function(resolve, reject) {
559 var dialog_inst = dialog.modal({
560 title: "Rename Notebook",
561 body: dialog_body,
562 buttons: {
563 "OK": {
564 class: "btn-primary",
565 click: function () {
566 resolve(dialog_inst.find('input').val());
567 }
568 },
569 "Cancel": {
570 click: function () {
571 reject();
572 }
573 }
574 }, open: function () {
575 /**
576 * Upon ENTER, click the OK button.
577 */
578 dialog_inst.find('input[type="text"]').keydown(function (event) {
579 if (event.which === keyboard.keycodes.enter) {
580 dialog_inst.find('.btn-primary').first().click();
581 return false;
582 }
583 });
584 dialog_inst.find('input[type="text"]').focus().select();
585 }
586 });
587 });
588 };
589
590 /**
591 * Creates a `file` or `directory`
592 * @param {string} type - "file" or "directory"
593 * @param {string} name - name of the thing to create
594 * @return {Promise} success
595 */
596 NotebookList.prototype._create = function(type, name) {
597 var that = this;
598 return new Promise(function(resolve, reject) {
599 var settings = {
600 processData : false,
601 cache : false,
602 type : "PUT",
603 data: JSON.stringify({
604 type: type,
605 format: 'text',
606 content: '',
607 }),
608 dataType: "json",
609 success: function () {
610 resolve();
611 },
612 error: function() {
613 reject();
614 utils.log_ajax_error.apply(this, arguments);
615 },
616 };
617 var url = utils.url_join_encode(
618 that.base_url,
619 'api/contents/' + name
620 );
621 $.ajax(url, settings);
622 });
623 };
624
625 535
626 536 // Backwards compatability.
627 537 IPython.NotebookList = NotebookList;
628 538
629 539 return {'NotebookList': NotebookList};
630 540 });
General Comments 0
You need to be logged in to leave comments. Login now