Created
April 19, 2014 19:34
-
-
Save Carreau/11095012 to your computer and use it in GitHub Desktop.
a test js extension
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
define(["require"], function(require) { | |
"use strict"; | |
// first param reference to a DOM div | |
// second param reference to the cell. | |
/** | |
* Build a list of already existing names, except on given cell | |
*/ | |
var existing_names = function(self){ | |
var names = [] | |
var cells = IPython.notebook.get_cells(); | |
for(var i in cells){ | |
var cell = cells[i]; | |
if(cell !== self){ | |
if (cell.metadata.name){ | |
names.push(cell.metadata.name) | |
} | |
} | |
} | |
return names | |
} | |
var make_ui = function(div, cell) { | |
var button_container = $(div) | |
var button = $('<div/>').addClass('btn btn-mini'); | |
// set the name of the cell across metadata and UI, | |
// return true if of, flase if issues (like already existing name) | |
var set_name = function(name){ | |
var existings = existing_names(cell) | |
for(var target in existings){ | |
if( name === existings[target]){ | |
return false | |
} | |
} | |
// ok, set name in metadata and on button | |
cell.metadata.name = name | |
if(!name){ | |
button.text("No Name") | |
} else { | |
button.text(name) | |
} | |
return true; | |
} | |
var current_name | |
if( !cell.metadata.name){ | |
current_name = "No name"; | |
} else { | |
current_name = cell.metadata.name; | |
} | |
button.text(current_name) | |
// On click, change the metadata value and update the button label | |
var error_div = $('<div/>').css('color', 'red'); | |
button.click(function(){ | |
var inputfield = $('<input/>').attr('type','text') | |
if(cell.metadata.name){ | |
inputfield.val(cell.metadata.name) | |
} | |
var dialogform = $('<div/>').attr('title', 'Edit cell Name') | |
.append( | |
$('<form/>').append( | |
$('<fieldset/>') | |
.append(inputfield) | |
.append($('<br/>')) | |
.append(error_div) | |
) | |
); | |
IPython.dialog.modal({ | |
title: "Edit Cell name", | |
body: dialogform, | |
buttons: { | |
OK: { | |
class : "btn-primary", | |
click: function() { | |
var newname = inputfield.val(); | |
if(!set_name(newname)){ | |
error_div.text('WARNING: This name already exist'); | |
return false | |
} | |
} | |
}, | |
Cancel: {} | |
} | |
}) | |
}) | |
// add the button to the DOM div. | |
button_container.append(button); | |
} | |
// now we register the callback under the name foo to give the | |
// user the ability to use it later | |
IPython.CellToolbar.register_callback('edit_name', make_ui); | |
IPython.CellToolbar.register_preset('meta.edit_name',['edit_name']); | |
console.log('preset shoudl be register') | |
}); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment