-
Notifications
You must be signed in to change notification settings - Fork 0
/
main.js
302 lines (255 loc) · 12.1 KB
/
main.js
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
define(['jquery', 'base/js/namespace', 'base/js/dialog'], function($, Jupyter, dialog) {
"use strict";
var CONFIG = {
gistsUrl: 'https://api.github.com/gists',
nbviewerBaseUrl: 'https://colab.research.google.com/gist/',
personal_access_token: 'XXX'
}; // define default values for config parameters
var params = {
togist_tocolab_default_to_public: false,
togist_tocolab_personal_access_token: gis,
github_endpoint: 'github.com'
};
var initialize = function() {
update_params();
Jupyter.toolbar.add_buttons_group([
Jupyter.keyboard_manager.actions.register({
help: 'Create Gist of Notebook Then Open in Colab',
icon: 'fa-github',
handler: show_gist_editor_modal
}, 'create-gist-from-notebook', 'togist_tocolab')
]);
};
var update_params = function update_params() {
var config = Jupyter.notebook.config;
for (var key in params) {
if (config.data.hasOwnProperty(key)) params[key] = config.data[key];
}
default_metadata.data.public = Boolean(config.data.togist_tocolab_default_to_public);
};
var default_metadata = {
id: '',
data: {
description: Jupyter.notebook.notebook_path,
public: false
}
};
function ensure_default_metadata() {
Jupyter.notebook.metadata.gist = $.extend(true, // deep-copy
default_metadata, //defaults
Jupyter.notebook.metadata.gist // overrides
);
}
var add_auth_token = function add_auth_token(xhr) {
var token = '';
if (params.togist_tocolab_personal_access_token !== '') {
token = params.togist_tocolab_personal_access_token;
}
if (token !== '') {
xhr.setRequestHeader("Authorization", "token " + token);
}
};
/**
* Add gutter to a new cell
*
* @param event
* @param nbcell
*
*/
var createCell = function createCell(event, nbcell) {
var cell = nbcell.cell;
if (_instanceof(cell, codecell.CodeCell)) {
var gutters = cell.code_mirror.getOption('gutters').slice();
if ($.inArray("CodeMirror-cellstate", gutters) < 0) {
gutters.push('CodeMirror-cellstate');
cell.code_mirror.setOption('gutters', gutters);
cell.code_mirror.on("gutterClick", changeEvent);
}
}
};
function build_alert(alert_class) {
return $('<div/>').addClass('alert alert-dismissable').addClass(alert_class) // .headers.filename("<script src='https://unpkg.com/@jupyter-widgets/html-manager@*/dist/embed.js' crossorigin='anonymous'></script>")
.append($('<div class="wrap"><a href="#" class="button">Hover Me!</a>').append($('<span aria-hidden="false"/>').html('×')));
}
function gist_error(jqXHR, textStatus, errorThrown) {
console.log('github ajax error:', jqXHR, textStatus, errorThrown);
var alert = build_alert('alert-danger').hide().append($('<p/>').text('The ajax request to Github went wrong:')).append($('<pre/>').text(jqXHR.responseJSON ? JSON.stringify(jqXHR.responseJSON, null, 2) : errorThrown));
$('#gist_modal').find('.modal-body').append(alert);
alert.slideDown('fast');
}
function gist_success(response, textStatus, jqXHR) {
// if (Jupyter.notebook.metadata.gist.id === response.id) return;
Jupyter.notebook.metadata.gist.id = response.id;
Jupyter.notebook.metadata._draft = $.extend(true, // deep copy
Jupyter.notebook.metadata._draft, // defaults
{
nbviewer_url: response.html_url
} // overrides
);
var d = new Date();
var msg_head = d.toLocaleString() + ': Gist ';
var msg_tail = response.history.length === 1 ? ' published' : ' updated to revision ' + response.history.length;
var alert = build_alert('alert-success').hide().append(msg_head).append($('<a/>').attr('href', response.html_url).attr('target', '_blank').text(response.id)).append(msg_tail);
$('#gist_modal').find('.modal-body').append(alert);
alert.slideDown('fast');
}
function get_github_endpoint() {
return params.github_endpoint !== '' ? params.github_endpoint : 'github.com';
}
function get_api_endpoint() {
var github_endpoint = get_github_endpoint();
if (github_endpoint === 'github.com') {
return 'https://api.' + github_endpoint;
} else {
// Github Enterprise
// https://developer.github.com/enterprise/2.18/v3/enterprise-admin/#endpoint-urls
return 'https://' + github_endpoint + '/api/v3';
}
}
function update_gist_editor(gist_editor) {
if (gist_editor === undefined) gist_editor = $('#gist_editor');
var id_input = gist_editor.find('#gist_id');
var have_auth = params.togist_tocolab_personal_access_token !== '';
var id = '';
var is_public = true;
if (have_auth) {
id = Jupyter.notebook.metadata.gist.id;
is_public = Jupyter.notebook.metadata.gist.data.public;
id_input.val(id);
}
id_input.closest('.form-group').toggle(have_auth);
gist_editor.find('#gist_public').prop('checked', is_public).prop('readonly', !have_auth);
gist_editor.find('#gist_description').val(Jupyter.notebook.metadata.gist.data.description);
if (have_auth) {
gist_id_updated_callback(gist_editor);
}
}
function build_gist_editor() {
ensure_default_metadata();
var gist_editor = $('#gist_editor');
if (gist_editor.length > 0) return gist_editor;
gist_editor = $('<div/>').attr('id', 'gist_editor').append(controls);
var id = params.togist_tocolab_personal_access_token !== '' ? Jupyter.notebook.metadata.gist.id : '';
var controls = $('<form/>').appendTo(gist_editor).addClass('form-horizontal');
// $('<div/>').addClass('has-feedback').hide().appendTo(controls).append($('<label/>').attr('for', 'gist_id').text('Gist id')).append($('<input/>').addClass('form-control').attr('id', 'gist_id').val(Jupyter.notebook.metadata.gist.id)).append($('<span/>').addClass('form-control-feedback').append($('<i/>').addClass('fa fa-lg'))).append($('<span/>').addClass('help-block'));
$('<div/>').appendTo(controls).append($('<div/>').addClass('checkbox').append($('<label>').text('Make the gist public').prepend($('<input/>').attr('type', 'checkbox').attr('id', 'gist_public').prop('checked', Jupyter.notebook.metadata.gist.data.public).prop('readonly', id === '')))).append($('<label/>').attr('for', 'gist_public').text('public'));
$('<div/>').appendTo(controls).append($('<label/>').attr('for', 'gist_description').text('description')).append($('<input/>').addClass('form-control').attr('id', 'gist_description').attr('type', 'textarea').val(Jupyter.notebook.metadata.gist.data.description));
var form_groups = controls.children('div').addClass('form-group');
form_groups.children('label').addClass('col-sm-2 control-label').css('padding-right', '1em');
form_groups.each(function(index, elem) {
$('<div/>').appendTo(elem).addClass('col-sm-10').append($(elem).children(':not(label)'));
});
update_gist_editor(gist_editor); // bind events for id changing
// var id_input = gist_editor.find('#gist_id'); // Save current value of element
id_input.data('oldVal', id_input.val()); // Look for changes in the value
id_input.bind("change click keyup input paste", function(event) {
// If value has changed...
if (id_input.data('oldVal') !== id_input.val()) {
// Updated stored value
id_input.data('oldVal', id_input.val()); // Do action
gist_id_updated_callback(gist_editor);
}
});
return gist_editor;
}
function show_gist_editor_modal() {
var modal;
modal = dialog.modal({
show: false,
title: 'Push to Gist Open In Colab',
notebook: Jupyter.notebook,
keyboard_manager: Jupyter.notebook.keyboard_manager,
body: build_gist_editor(),
buttons: {
'Open In Colab!': {
class: 'btn-primary',
click: function click() {
modal.find('.btn').prop('disabled', true);
var new_data = {
public: $('#gist_public').prop('checked'),
description: $('#gist_description').val() + ".ipynb",
extension: '.ipynb'
};
$.extend(true, Jupyter.notebook.metadata.gist, new_data); // prevent the modal from closing. See github.com/twbs/bootstrap/issues/1202
modal.data('bs.modal').isShown = false;
var spinner = modal.find('.btn-primary .fa-github').addClass('fa-spin');
make_gist(function(jqXHR, textStatus) {
modal.find('.btn').prop('disabled', false); // allow the modal to close again. See github.com/twbs/bootstrap/issues/1202
modal.data('bs.modal').isShown = true;
spinner.removeClass('fa-spin');
});
}
},
done: {}
}
}).attr('id', 'gist_modal').on('shown.bs.modal', function(evt) {
var err = modal.find('#gist_id').parent().hasClass('has-error');
modal.find('.btn-primary').prop('disabled', err);
});
modal.find('.btn-primary').prepend($('<i/>').addClass('fa fa-lg fa-github'));
modal.modal('show');
}
var make_gist = function make_gist(complete_callback) {
ensure_default_metadata();
var data = $.extend(true, // deep-copy
{
files: {}
}, // defaults
Jupyter.notebook.metadata.gist.data // overrides
);
var filename = Jupyter.notebook.notebook_name;
data.files[filename] = {
content: JSON.stringify(Jupyter.notebook.toJSON(), null, 2)
};
/**
* Add gutter to a new cell
*
* @param event
* @param nbcell
*
*/
var createCell = function createCell(event, nbcell) {
var cell = nbcell.cell;
if (_instanceof(cell, codecell.CodeCell)) {
var gutters = cell.code_mirror.getOption('gutters').slice();
if ($.inArray("CodeMirror-cellstate", gutters) < 0) {
gutters.push('CodeMirror-cellstate');
cell.code_mirror.setOption('gutters', gutters);
cell.code_mirror.on("gutterClick", changeEvent);
}
}
};
var gistsUrl = CONFIG.gistsUrl;
if (CONFIG.personal_access_token) {
gistsUrl = "".concat(gistsUrl, "?oauth_token=",CONFIG.personal_access_token);
}
var settings = {
async: true,
crossDomain: true,
type: 'POST',
headers: {},
dataType: 'json',
data: JSON.stringify(data),
success: function success(data, status) {
var end = data.owner.login + '/' + data.id;
setTimeout(function() {
window.location.replace(CONFIG.nbviewerBaseUrl + end);
}, 7000);
}
};
$.ajax(gistsUrl, settings).catch(function(jqXHR, status, err) {
var errorMsg = jqXHR.readyState === 0 && !err ? 'NETWORK ERROR!' : err;
if (jqXHR.responseJSON && jqXHR.responseJSON.message) {
errorMsg = jqXHR.responseJSON.message;
}
console.log(errorMsg);
onErrorCb(errorMsg);
});
};
function load_jupyter_extension() {
return Jupyter.notebook.config.loaded.then(initialize);
}
return {
load_jupyter_extension: load_jupyter_extension
};
});