Book a Demo!
CoCalc Logo Icon
StoreFeaturesDocsShareSupportNewsAboutPoliciesSign UpSign In
Avatar for KuCalc : devops.
Download
50659 views
1
// Copyright (c) IPython Development Team.
2
// Distributed under the terms of the Modified BSD License.
3
4
define(["widgets/js/manager",
5
"underscore",
6
"backbone",
7
"jquery",
8
"base/js/utils",
9
"base/js/namespace",
10
], function(widgetmanager, _, Backbone, $, utils, IPython){
11
"use strict";
12
13
var WidgetModel = Backbone.Model.extend({
14
constructor: function (widget_manager, model_id, comm) {
15
/**
16
* Constructor
17
*
18
* Creates a WidgetModel instance.
19
*
20
* Parameters
21
* ----------
22
* widget_manager : WidgetManager instance
23
* model_id : string
24
* An ID unique to this model.
25
* comm : Comm instance (optional)
26
*/
27
this.widget_manager = widget_manager;
28
this.state_change = Promise.resolve();
29
this._buffered_state_diff = {};
30
this.pending_msgs = 0;
31
this.msg_buffer = null;
32
this.state_lock = null;
33
this.id = model_id;
34
this.views = {};
35
this._resolve_received_state = {};
36
37
if (comm !== undefined) {
38
// Remember comm associated with the model.
39
this.comm = comm;
40
comm.model = this;
41
42
// Hook comm messages up to model.
43
comm.on_close($.proxy(this._handle_comm_closed, this));
44
comm.on_msg($.proxy(this._handle_comm_msg, this));
45
46
// Assume the comm is alive.
47
this.set_comm_live(true);
48
} else {
49
this.set_comm_live(false);
50
}
51
52
// Listen for the events that lead to the websocket being terminated.
53
var that = this;
54
var died = function() {
55
that.set_comm_live(false);
56
};
57
widget_manager.notebook.events.on('kernel_disconnected.Kernel', died);
58
widget_manager.notebook.events.on('kernel_killed.Kernel', died);
59
widget_manager.notebook.events.on('kernel_restarting.Kernel', died);
60
widget_manager.notebook.events.on('kernel_dead.Kernel', died);
61
62
return Backbone.Model.apply(this);
63
},
64
65
send: function (content, callbacks) {
66
/**
67
* Send a custom msg over the comm.
68
*/
69
if (this.comm !== undefined) {
70
var data = {method: 'custom', content: content};
71
this.comm.send(data, callbacks);
72
this.pending_msgs++;
73
}
74
},
75
76
request_state: function(callbacks) {
77
/**
78
* Request a state push from the back-end.
79
*/
80
if (!this.comm) {
81
console.error("Could not request_state because comm doesn't exist!");
82
return;
83
}
84
85
var msg_id = this.comm.send({method: 'request_state'}, callbacks || this.widget_manager.callbacks());
86
87
// Promise that is resolved when a state is received
88
// from the back-end.
89
var that = this;
90
var received_state = new Promise(function(resolve) {
91
that._resolve_received_state[msg_id] = resolve;
92
});
93
return received_state;
94
},
95
96
set_comm_live: function(live) {
97
/**
98
* Change the comm_live state of the model.
99
*/
100
if (this.comm_live === undefined || this.comm_live != live) {
101
this.comm_live = live;
102
this.trigger(live ? 'comm:live' : 'comm:dead', {model: this});
103
}
104
},
105
106
close: function(comm_closed) {
107
/**
108
* Close model
109
*/
110
if (this.comm && !comm_closed) {
111
this.comm.close();
112
}
113
this.stopListening();
114
this.trigger('destroy', this);
115
delete this.comm.model; // Delete ref so GC will collect widget model.
116
delete this.comm;
117
delete this.model_id; // Delete id from model so widget manager cleans up.
118
_.each(this.views, function(v, id, views) {
119
v.then(function(view) {
120
view.remove();
121
delete views[id];
122
});
123
});
124
},
125
126
_handle_comm_closed: function (msg) {
127
/**
128
* Handle when a widget is closed.
129
*/
130
this.trigger('comm:close');
131
this.close(true);
132
},
133
134
_handle_comm_msg: function (msg) {
135
/**
136
* Handle incoming comm msg.
137
*/
138
var method = msg.content.data.method;
139
var that = this;
140
switch (method) {
141
case 'update':
142
this.state_change = this.state_change
143
.then(function() {
144
return that.set_state(msg.content.data.state);
145
}).catch(utils.reject("Couldn't process update msg for model id '" + String(that.id) + "'", true))
146
.then(function() {
147
var parent_id = msg.parent_header.msg_id;
148
if (that._resolve_received_state[parent_id] !== undefined) {
149
that._resolve_received_state[parent_id].call();
150
delete that._resolve_received_state[parent_id];
151
}
152
}).catch(utils.reject("Couldn't resolve state request promise", true));
153
break;
154
case 'custom':
155
this.trigger('msg:custom', msg.content.data.content);
156
break;
157
case 'display':
158
this.state_change = this.state_change.then(function() {
159
that.widget_manager.display_view(msg, that);
160
}).catch(utils.reject('Could not process display view msg', true));
161
break;
162
}
163
},
164
165
set_state: function (state) {
166
var that = this;
167
// Handle when a widget is updated via the python side.
168
return this._unpack_models(state).then(function(state) {
169
that.state_lock = state;
170
try {
171
WidgetModel.__super__.set.call(that, state);
172
} finally {
173
that.state_lock = null;
174
}
175
}).catch(utils.reject("Couldn't set model state", true));
176
},
177
178
get_state: function() {
179
// Get the serializable state of the model.
180
var state = this.toJSON();
181
for (var key in state) {
182
if (state.hasOwnProperty(key)) {
183
state[key] = this._pack_models(state[key]);
184
}
185
}
186
return state;
187
},
188
189
_handle_status: function (msg, callbacks) {
190
/**
191
* Handle status msgs.
192
*
193
* execution_state : ('busy', 'idle', 'starting')
194
*/
195
if (this.comm !== undefined) {
196
if (msg.content.execution_state ==='idle') {
197
// Send buffer if this message caused another message to be
198
// throttled.
199
if (this.msg_buffer !== null &&
200
(this.get('msg_throttle') || 3) === this.pending_msgs) {
201
var data = {method: 'backbone', sync_method: 'update', sync_data: this.msg_buffer};
202
this.comm.send(data, callbacks);
203
this.msg_buffer = null;
204
} else {
205
--this.pending_msgs;
206
}
207
}
208
}
209
},
210
211
callbacks: function(view) {
212
/**
213
* Create msg callbacks for a comm msg.
214
*/
215
var callbacks = this.widget_manager.callbacks(view);
216
217
if (callbacks.iopub === undefined) {
218
callbacks.iopub = {};
219
}
220
221
var that = this;
222
callbacks.iopub.status = function (msg) {
223
that._handle_status(msg, callbacks);
224
};
225
return callbacks;
226
},
227
228
set: function(key, val, options) {
229
/**
230
* Set a value.
231
*/
232
var return_value = WidgetModel.__super__.set.apply(this, arguments);
233
234
// Backbone only remembers the diff of the most recent set()
235
// operation. Calling set multiple times in a row results in a
236
// loss of diff information. Here we keep our own running diff.
237
this._buffered_state_diff = $.extend(this._buffered_state_diff, this.changedAttributes() || {});
238
return return_value;
239
},
240
241
sync: function (method, model, options) {
242
/**
243
* Handle sync to the back-end. Called when a model.save() is called.
244
*
245
* Make sure a comm exists.
246
*/
247
var error = options.error || function() {
248
console.error('Backbone sync error:', arguments);
249
};
250
if (this.comm === undefined) {
251
error();
252
return false;
253
}
254
255
// Delete any key value pairs that the back-end already knows about.
256
var attrs = (method === 'patch') ? options.attrs : model.toJSON(options);
257
if (this.state_lock !== null) {
258
var keys = Object.keys(this.state_lock);
259
for (var i=0; i<keys.length; i++) {
260
var key = keys[i];
261
if (attrs[key] === this.state_lock[key]) {
262
delete attrs[key];
263
}
264
}
265
}
266
267
// Only sync if there are attributes to send to the back-end.
268
attrs = this._pack_models(attrs);
269
if (_.size(attrs) > 0) {
270
271
// If this message was sent via backbone itself, it will not
272
// have any callbacks. It's important that we create callbacks
273
// so we can listen for status messages, etc...
274
var callbacks = options.callbacks || this.callbacks();
275
276
// Check throttle.
277
if (this.pending_msgs >= (this.get('msg_throttle') || 3)) {
278
// The throttle has been exceeded, buffer the current msg so
279
// it can be sent once the kernel has finished processing
280
// some of the existing messages.
281
282
// Combine updates if it is a 'patch' sync, otherwise replace updates
283
switch (method) {
284
case 'patch':
285
this.msg_buffer = $.extend(this.msg_buffer || {}, attrs);
286
break;
287
case 'update':
288
case 'create':
289
this.msg_buffer = attrs;
290
break;
291
default:
292
error();
293
return false;
294
}
295
this.msg_buffer_callbacks = callbacks;
296
297
} else {
298
// We haven't exceeded the throttle, send the message like
299
// normal.
300
var data = {method: 'backbone', sync_data: attrs};
301
this.comm.send(data, callbacks);
302
this.pending_msgs++;
303
}
304
}
305
// Since the comm is a one-way communication, assume the message
306
// arrived. Don't call success since we don't have a model back from the server
307
// this means we miss out on the 'sync' event.
308
this._buffered_state_diff = {};
309
},
310
311
save_changes: function(callbacks) {
312
/**
313
* Push this model's state to the back-end
314
*
315
* This invokes a Backbone.Sync.
316
*/
317
this.save(this._buffered_state_diff, {patch: true, callbacks: callbacks});
318
},
319
320
_pack_models: function(value) {
321
/**
322
* Replace models with model ids recursively.
323
*/
324
var that = this;
325
var packed;
326
if (value instanceof Backbone.Model) {
327
return "IPY_MODEL_" + value.id;
328
329
} else if ($.isArray(value)) {
330
packed = [];
331
_.each(value, function(sub_value, key) {
332
packed.push(that._pack_models(sub_value));
333
});
334
return packed;
335
} else if (value instanceof Date || value instanceof String) {
336
return value;
337
} else if (value instanceof Object) {
338
packed = {};
339
_.each(value, function(sub_value, key) {
340
packed[key] = that._pack_models(sub_value);
341
});
342
return packed;
343
344
} else {
345
return value;
346
}
347
},
348
349
_unpack_models: function(value) {
350
/**
351
* Replace model ids with models recursively.
352
*/
353
var that = this;
354
var unpacked;
355
if ($.isArray(value)) {
356
unpacked = [];
357
_.each(value, function(sub_value, key) {
358
unpacked.push(that._unpack_models(sub_value));
359
});
360
return Promise.all(unpacked);
361
} else if (value instanceof Object) {
362
unpacked = {};
363
_.each(value, function(sub_value, key) {
364
unpacked[key] = that._unpack_models(sub_value);
365
});
366
return utils.resolve_promises_dict(unpacked);
367
} else if (typeof value === 'string' && value.slice(0,10) === "IPY_MODEL_") {
368
// get_model returns a promise already
369
return this.widget_manager.get_model(value.slice(10, value.length));
370
} else {
371
return Promise.resolve(value);
372
}
373
},
374
375
on_some_change: function(keys, callback, context) {
376
/**
377
* on_some_change(["key1", "key2"], foo, context) differs from
378
* on("change:key1 change:key2", foo, context).
379
* If the widget attributes key1 and key2 are both modified,
380
* the second form will result in foo being called twice
381
* while the first will call foo only once.
382
*/
383
this.on('change', function() {
384
if (keys.some(this.hasChanged, this)) {
385
callback.apply(context);
386
}
387
}, this);
388
389
},
390
});
391
widgetmanager.WidgetManager.register_widget_model('WidgetModel', WidgetModel);
392
393
394
var WidgetView = Backbone.View.extend({
395
initialize: function(parameters) {
396
/**
397
* Public constructor.
398
*/
399
this.model.on('change',this.update,this);
400
401
// Bubble the comm live events.
402
this.model.on('comm:live', function() {
403
this.trigger('comm:live', this);
404
}, this);
405
this.model.on('comm:dead', function() {
406
this.trigger('comm:dead', this);
407
}, this);
408
409
this.options = parameters.options;
410
this.on('displayed', function() {
411
this.is_displayed = true;
412
}, this);
413
},
414
415
update: function(){
416
/**
417
* Triggered on model change.
418
*
419
* Update view to be consistent with this.model
420
*/
421
},
422
423
create_child_view: function(child_model, options) {
424
/**
425
* Create and promise that resolves to a child view of a given model
426
*/
427
var that = this;
428
options = $.extend({ parent: this }, options || {});
429
return this.model.widget_manager.create_view(child_model, options).catch(utils.reject("Couldn't create child view"), true);
430
},
431
432
callbacks: function(){
433
/**
434
* Create msg callbacks for a comm msg.
435
*/
436
return this.model.callbacks(this);
437
},
438
439
render: function(){
440
/**
441
* Render the view.
442
*
443
* By default, this is only called the first time the view is created
444
*/
445
},
446
447
send: function (content) {
448
/**
449
* Send a custom msg associated with this view.
450
*/
451
this.model.send(content, this.callbacks());
452
},
453
454
touch: function () {
455
this.model.save_changes(this.callbacks());
456
},
457
458
after_displayed: function (callback, context) {
459
/**
460
* Calls the callback right away is the view is already displayed
461
* otherwise, register the callback to the 'displayed' event.
462
*/
463
if (this.is_displayed) {
464
callback.apply(context);
465
} else {
466
this.on('displayed', callback, context);
467
}
468
},
469
470
remove: function () {
471
// Raise a remove event when the view is removed.
472
WidgetView.__super__.remove.apply(this, arguments);
473
this.trigger('remove');
474
}
475
});
476
477
478
var DOMWidgetView = WidgetView.extend({
479
initialize: function (parameters) {
480
/**
481
* Public constructor
482
*/
483
DOMWidgetView.__super__.initialize.apply(this, [parameters]);
484
this.model.on('change:visible', this.update_visible, this);
485
this.model.on('change:_css', this.update_css, this);
486
487
this.model.on('change:_dom_classes', function(model, new_classes) {
488
var old_classes = model.previous('_dom_classes');
489
this.update_classes(old_classes, new_classes);
490
}, this);
491
492
this.model.on('change:color', function (model, value) {
493
this.update_attr('color', value); }, this);
494
495
this.model.on('change:background_color', function (model, value) {
496
this.update_attr('background', value); }, this);
497
498
this.model.on('change:width', function (model, value) {
499
this.update_attr('width', value); }, this);
500
501
this.model.on('change:height', function (model, value) {
502
this.update_attr('height', value); }, this);
503
504
this.model.on('change:border_color', function (model, value) {
505
this.update_attr('border-color', value); }, this);
506
507
this.model.on('change:border_width', function (model, value) {
508
this.update_attr('border-width', value); }, this);
509
510
this.model.on('change:border_style', function (model, value) {
511
this.update_attr('border-style', value); }, this);
512
513
this.model.on('change:font_style', function (model, value) {
514
this.update_attr('font-style', value); }, this);
515
516
this.model.on('change:font_weight', function (model, value) {
517
this.update_attr('font-weight', value); }, this);
518
519
this.model.on('change:font_size', function (model, value) {
520
this.update_attr('font-size', this._default_px(value)); }, this);
521
522
this.model.on('change:font_family', function (model, value) {
523
this.update_attr('font-family', value); }, this);
524
525
this.model.on('change:padding', function (model, value) {
526
this.update_attr('padding', value); }, this);
527
528
this.model.on('change:margin', function (model, value) {
529
this.update_attr('margin', this._default_px(value)); }, this);
530
531
this.model.on('change:border_radius', function (model, value) {
532
this.update_attr('border-radius', this._default_px(value)); }, this);
533
534
this.after_displayed(function() {
535
this.update_visible(this.model, this.model.get("visible"));
536
this.update_classes([], this.model.get('_dom_classes'));
537
538
this.update_attr('color', this.model.get('color'));
539
this.update_attr('background', this.model.get('background_color'));
540
this.update_attr('width', this.model.get('width'));
541
this.update_attr('height', this.model.get('height'));
542
this.update_attr('border-color', this.model.get('border_color'));
543
this.update_attr('border-width', this.model.get('border_width'));
544
this.update_attr('border-style', this.model.get('border_style'));
545
this.update_attr('font-style', this.model.get('font_style'));
546
this.update_attr('font-weight', this.model.get('font_weight'));
547
this.update_attr('font-size', this._default_px(this.model.get('font_size')));
548
this.update_attr('font-family', this.model.get('font_family'));
549
this.update_attr('padding', this.model.get('padding'));
550
this.update_attr('margin', this._default_px(this.model.get('margin')));
551
this.update_attr('border-radius', this._default_px(this.model.get('border_radius')));
552
553
this.update_css(this.model, this.model.get("_css"));
554
}, this);
555
},
556
557
_default_px: function(value) {
558
/**
559
* Makes browser interpret a numerical string as a pixel value.
560
*/
561
if (/^\d+\.?(\d+)?$/.test(value.trim())) {
562
return value.trim() + 'px';
563
}
564
return value;
565
},
566
567
update_attr: function(name, value) {
568
/**
569
* Set a css attr of the widget view.
570
*/
571
this.$el.css(name, value);
572
},
573
574
update_visible: function(model, value) {
575
/**
576
* Update visibility
577
*/
578
switch(value) {
579
case null: // python None
580
this.$el.show().css('visibility', 'hidden'); break;
581
case false:
582
this.$el.hide(); break;
583
case true:
584
this.$el.show().css('visibility', ''); break;
585
}
586
},
587
588
update_css: function (model, css) {
589
/**
590
* Update the css styling of this view.
591
*/
592
if (css === undefined) {return;}
593
for (var i = 0; i < css.length; i++) {
594
// Apply the css traits to all elements that match the selector.
595
var selector = css[i][0];
596
var elements = this._get_selector_element(selector);
597
if (elements.length > 0) {
598
var trait_key = css[i][1];
599
var trait_value = css[i][2];
600
elements.css(trait_key ,trait_value);
601
}
602
}
603
},
604
605
update_classes: function (old_classes, new_classes, $el) {
606
/**
607
* Update the DOM classes applied to an element, default to this.$el.
608
*/
609
if ($el===undefined) {
610
$el = this.$el;
611
}
612
_.difference(old_classes, new_classes).map(function(c) {$el.removeClass(c);})
613
_.difference(new_classes, old_classes).map(function(c) {$el.addClass(c);})
614
},
615
616
update_mapped_classes: function(class_map, trait_name, previous_trait_value, $el) {
617
/**
618
* Update the DOM classes applied to the widget based on a single
619
* trait's value.
620
*
621
* Given a trait value classes map, this function automatically
622
* handles applying the appropriate classes to the widget element
623
* and removing classes that are no longer valid.
624
*
625
* Parameters
626
* ----------
627
* class_map: dictionary
628
* Dictionary of trait values to class lists.
629
* Example:
630
* {
631
* success: ['alert', 'alert-success'],
632
* info: ['alert', 'alert-info'],
633
* warning: ['alert', 'alert-warning'],
634
* danger: ['alert', 'alert-danger']
635
* };
636
* trait_name: string
637
* Name of the trait to check the value of.
638
* previous_trait_value: optional string, default ''
639
* Last trait value
640
* $el: optional jQuery element handle, defaults to this.$el
641
* Element that the classes are applied to.
642
*/
643
var key = previous_trait_value;
644
if (key === undefined) {
645
key = this.model.previous(trait_name);
646
}
647
var old_classes = class_map[key] ? class_map[key] : [];
648
key = this.model.get(trait_name);
649
var new_classes = class_map[key] ? class_map[key] : [];
650
651
this.update_classes(old_classes, new_classes, $el || this.$el);
652
},
653
654
_get_selector_element: function (selector) {
655
/**
656
* Get the elements via the css selector.
657
*/
658
var elements;
659
if (!selector) {
660
elements = this.$el;
661
} else {
662
elements = this.$el.find(selector).addBack(selector);
663
}
664
return elements;
665
},
666
667
typeset: function(element, text){
668
utils.typeset.apply(null, arguments);
669
},
670
});
671
672
673
var ViewList = function(create_view, remove_view, context) {
674
/**
675
* - create_view and remove_view are default functions called when adding or removing views
676
* - create_view takes a model and returns a view or a promise for a view for that model
677
* - remove_view takes a view and destroys it (including calling `view.remove()`)
678
* - each time the update() function is called with a new list, the create and remove
679
* callbacks will be called in an order so that if you append the views created in the
680
* create callback and remove the views in the remove callback, you will duplicate
681
* the order of the list.
682
* - the remove callback defaults to just removing the view (e.g., pass in null for the second parameter)
683
* - the context defaults to the created ViewList. If you pass another context, the create and remove
684
* will be called in that context.
685
*/
686
687
this.initialize.apply(this, arguments);
688
};
689
690
_.extend(ViewList.prototype, {
691
initialize: function(create_view, remove_view, context) {
692
this._handler_context = context || this;
693
this._models = [];
694
this.views = []; // list of promises for views
695
this._create_view = create_view;
696
this._remove_view = remove_view || function(view) {view.remove();};
697
},
698
699
update: function(new_models, create_view, remove_view, context) {
700
/**
701
* the create_view, remove_view, and context arguments override the defaults
702
* specified when the list is created.
703
* after this function, the .views attribute is a list of promises for views
704
* if you want to perform some action on the list of views, do something like
705
* `Promise.all(myviewlist.views).then(function(views) {...});`
706
*/
707
var remove = remove_view || this._remove_view;
708
var create = create_view || this._create_view;
709
context = context || this._handler_context;
710
var i = 0;
711
// first, skip past the beginning of the lists if they are identical
712
for (; i < new_models.length; i++) {
713
if (i >= this._models.length || new_models[i] !== this._models[i]) {
714
break;
715
}
716
}
717
718
var first_removed = i;
719
// Remove the non-matching items from the old list.
720
var removed = this.views.splice(first_removed, this.views.length-first_removed);
721
for (var j = 0; j < removed.length; j++) {
722
removed[j].then(function(view) {
723
remove.call(context, view)
724
});
725
}
726
727
// Add the rest of the new list items.
728
for (; i < new_models.length; i++) {
729
this.views.push(Promise.resolve(create.call(context, new_models[i])));
730
}
731
// make a copy of the input array
732
this._models = new_models.slice();
733
},
734
735
remove: function() {
736
/**
737
* removes every view in the list; convenience function for `.update([])`
738
* that should be faster
739
* returns a promise that resolves after this removal is done
740
*/
741
var that = this;
742
return Promise.all(this.views).then(function(views) {
743
for (var i = 0; i < that.views.length; i++) {
744
that._remove_view.call(that._handler_context, views[i]);
745
}
746
that.views = [];
747
that._models = [];
748
});
749
},
750
});
751
752
var widget = {
753
'WidgetModel': WidgetModel,
754
'WidgetView': WidgetView,
755
'DOMWidgetView': DOMWidgetView,
756
'ViewList': ViewList,
757
};
758
759
// For backwards compatability.
760
$.extend(IPython, widget);
761
762
return widget;
763
});
764
765