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