##// END OF EJS Templates
Load the utils module
Jason Grout -
Show More
@@ -1,600 +1,601 b''
1 1 // Copyright (c) IPython Development Team.
2 2 // Distributed under the terms of the Modified BSD License.
3 3
4 4 define(["widgets/js/manager",
5 5 "underscore",
6 6 "backbone",
7 7 "jquery",
8 "base/js/utils",
8 9 "base/js/namespace",
9 ], function(widgetmanager, _, Backbone, $, IPython){
10 ], function(widgetmanager, _, Backbone, $, utils, IPython){
10 11
11 12 var WidgetModel = Backbone.Model.extend({
12 13 constructor: function (widget_manager, model_id, comm) {
13 14 // Constructor
14 15 //
15 16 // Creates a WidgetModel instance.
16 17 //
17 18 // Parameters
18 19 // ----------
19 20 // widget_manager : WidgetManager instance
20 21 // model_id : string
21 22 // An ID unique to this model.
22 23 // comm : Comm instance (optional)
23 24 this.widget_manager = widget_manager;
24 25 this.state_change = Promise.resolve();
25 26 this._buffered_state_diff = {};
26 27 this.pending_msgs = 0;
27 28 this.msg_buffer = null;
28 29 this.state_lock = null;
29 30 this.id = model_id;
30 31 this.views = {};
31 32
32 33 if (comm !== undefined) {
33 34 // Remember comm associated with the model.
34 35 this.comm = comm;
35 36 comm.model = this;
36 37
37 38 // Hook comm messages up to model.
38 39 comm.on_close($.proxy(this._handle_comm_closed, this));
39 40 comm.on_msg($.proxy(this._handle_comm_msg, this));
40 41 }
41 42 return Backbone.Model.apply(this);
42 43 },
43 44
44 45 send: function (content, callbacks) {
45 46 // Send a custom msg over the comm.
46 47 if (this.comm !== undefined) {
47 48 var data = {method: 'custom', content: content};
48 49 this.comm.send(data, callbacks);
49 50 this.pending_msgs++;
50 51 }
51 52 },
52 53
53 54 _handle_comm_closed: function (msg) {
54 55 // Handle when a widget is closed.
55 56 this.trigger('comm:close');
56 57 this.stopListening();
57 58 this.trigger('destroy', this);
58 59 delete this.comm.model; // Delete ref so GC will collect widget model.
59 60 delete this.comm;
60 61 delete this.model_id; // Delete id from model so widget manager cleans up.
61 62 for (var id in this.views) {
62 63 if (this.views.hasOwnProperty(id)) {
63 64 this.views[id].remove();
64 65 }
65 66 }
66 67 },
67 68
68 69 _handle_comm_msg: function (msg) {
69 70 // Handle incoming comm msg.
70 71 var method = msg.content.data.method;
71 72 switch (method) {
72 73 case 'update':
73 74 this.state_change = this.state_change.then(function() {
74 75 this.set_state(msg.content.data.state);
75 76 });
76 77 break;
77 78 case 'custom':
78 79 this.trigger('msg:custom', msg.content.data.content);
79 80 break;
80 81 case 'display':
81 82 this.widget_manager.display_view(msg, this);
82 83 break;
83 84 }
84 85 },
85 86
86 87 set_state: function (state) {
87 88 var that = this;
88 89 // Handle when a widget is updated via the python side.
89 90 this._unpack_models(state).then(function(state) {
90 91 that.state_lock = state;
91 92 try {
92 93 WidgetModel.__super__.set.call(this, state);
93 94 } finally {
94 95 that.state_lock = null;
95 96 }
96 97 }, $.proxy(console.error, console));
97 98 },
98 99
99 100 _handle_status: function (msg, callbacks) {
100 101 // Handle status msgs.
101 102
102 103 // execution_state : ('busy', 'idle', 'starting')
103 104 if (this.comm !== undefined) {
104 105 if (msg.content.execution_state ==='idle') {
105 106 // Send buffer if this message caused another message to be
106 107 // throttled.
107 108 if (this.msg_buffer !== null &&
108 109 (this.get('msg_throttle') || 3) === this.pending_msgs) {
109 110 var data = {method: 'backbone', sync_method: 'update', sync_data: this.msg_buffer};
110 111 this.comm.send(data, callbacks);
111 112 this.msg_buffer = null;
112 113 } else {
113 114 --this.pending_msgs;
114 115 }
115 116 }
116 117 }
117 118 },
118 119
119 120 callbacks: function(view) {
120 121 // Create msg callbacks for a comm msg.
121 122 var callbacks = this.widget_manager.callbacks(view);
122 123
123 124 if (callbacks.iopub === undefined) {
124 125 callbacks.iopub = {};
125 126 }
126 127
127 128 var that = this;
128 129 callbacks.iopub.status = function (msg) {
129 130 that._handle_status(msg, callbacks);
130 131 };
131 132 return callbacks;
132 133 },
133 134
134 135 set: function(key, val, options) {
135 136 // Set a value.
136 137 var return_value = WidgetModel.__super__.set.apply(this, arguments);
137 138
138 139 // Backbone only remembers the diff of the most recent set()
139 140 // operation. Calling set multiple times in a row results in a
140 141 // loss of diff information. Here we keep our own running diff.
141 142 this._buffered_state_diff = $.extend(this._buffered_state_diff, this.changedAttributes() || {});
142 143 return return_value;
143 144 },
144 145
145 146 sync: function (method, model, options) {
146 147 // Handle sync to the back-end. Called when a model.save() is called.
147 148
148 149 // Make sure a comm exists.
149 150 var error = options.error || function() {
150 151 console.error('Backbone sync error:', arguments);
151 152 };
152 153 if (this.comm === undefined) {
153 154 error();
154 155 return false;
155 156 }
156 157
157 158 // Delete any key value pairs that the back-end already knows about.
158 159 var attrs = (method === 'patch') ? options.attrs : model.toJSON(options);
159 160 if (this.state_lock !== null) {
160 161 var keys = Object.keys(this.state_lock);
161 162 for (var i=0; i<keys.length; i++) {
162 163 var key = keys[i];
163 164 if (attrs[key] === this.state_lock[key]) {
164 165 delete attrs[key];
165 166 }
166 167 }
167 168 }
168 169
169 170 // Only sync if there are attributes to send to the back-end.
170 171 attrs = this._pack_models(attrs);
171 172 if (_.size(attrs) > 0) {
172 173
173 174 // If this message was sent via backbone itself, it will not
174 175 // have any callbacks. It's important that we create callbacks
175 176 // so we can listen for status messages, etc...
176 177 var callbacks = options.callbacks || this.callbacks();
177 178
178 179 // Check throttle.
179 180 if (this.pending_msgs >= (this.get('msg_throttle') || 3)) {
180 181 // The throttle has been exceeded, buffer the current msg so
181 182 // it can be sent once the kernel has finished processing
182 183 // some of the existing messages.
183 184
184 185 // Combine updates if it is a 'patch' sync, otherwise replace updates
185 186 switch (method) {
186 187 case 'patch':
187 188 this.msg_buffer = $.extend(this.msg_buffer || {}, attrs);
188 189 break;
189 190 case 'update':
190 191 case 'create':
191 192 this.msg_buffer = attrs;
192 193 break;
193 194 default:
194 195 error();
195 196 return false;
196 197 }
197 198 this.msg_buffer_callbacks = callbacks;
198 199
199 200 } else {
200 201 // We haven't exceeded the throttle, send the message like
201 202 // normal.
202 203 var data = {method: 'backbone', sync_data: attrs};
203 204 this.comm.send(data, callbacks);
204 205 this.pending_msgs++;
205 206 }
206 207 }
207 208 // Since the comm is a one-way communication, assume the message
208 209 // arrived. Don't call success since we don't have a model back from the server
209 210 // this means we miss out on the 'sync' event.
210 211 this._buffered_state_diff = {};
211 212 },
212 213
213 214 save_changes: function(callbacks) {
214 215 // Push this model's state to the back-end
215 216 //
216 217 // This invokes a Backbone.Sync.
217 218 this.save(this._buffered_state_diff, {patch: true, callbacks: callbacks});
218 219 },
219 220
220 221 _pack_models: function(value) {
221 222 // Replace models with model ids recursively.
222 223 var that = this;
223 224 var packed;
224 225 if (value instanceof Backbone.Model) {
225 226 return "IPY_MODEL_" + value.id;
226 227
227 228 } else if ($.isArray(value)) {
228 229 packed = [];
229 230 _.each(value, function(sub_value, key) {
230 231 packed.push(that._pack_models(sub_value));
231 232 });
232 233 return packed;
233 234 } else if (value instanceof Date || value instanceof String) {
234 235 return value;
235 236 } else if (value instanceof Object) {
236 237 packed = {};
237 238 _.each(value, function(sub_value, key) {
238 239 packed[key] = that._pack_models(sub_value);
239 240 });
240 241 return packed;
241 242
242 243 } else {
243 244 return value;
244 245 }
245 246 },
246 247
247 248 _unpack_models: function(value) {
248 249 // Replace model ids with models recursively.
249 250 var that = this;
250 251 var unpacked;
251 252 if ($.isArray(value)) {
252 253 unpacked = [];
253 254 _.each(value, function(sub_value, key) {
254 255 unpacked.push(that._unpack_models(sub_value));
255 256 });
256 257 return Promise.all(unpacked);
257 258 } else if (value instanceof Object) {
258 259 var unpacked = {};
259 260 _.each(value, function(sub_value, key) {
260 261 unpacked[key] = that._unpack_models(sub_value)
261 262 });
262 return util.resolve_dict(unpacked);
263 return utils.resolve_dict(unpacked);
263 264 } else if (typeof value === 'string' && value.slice(0,10) === "IPY_MODEL_") {
264 265 // get_model returns a promise already
265 266 return this.widget_manager.get_model(value.slice(10, value.length));
266 267 } else {
267 268 return Promise.resolve(value);
268 269 }
269 270 },
270 271
271 272 on_some_change: function(keys, callback, context) {
272 273 // on_some_change(["key1", "key2"], foo, context) differs from
273 274 // on("change:key1 change:key2", foo, context).
274 275 // If the widget attributes key1 and key2 are both modified,
275 276 // the second form will result in foo being called twice
276 277 // while the first will call foo only once.
277 278 this.on('change', function() {
278 279 if (keys.some(this.hasChanged, this)) {
279 280 callback.apply(context);
280 281 }
281 282 }, this);
282 283
283 284 },
284 285 });
285 286 widgetmanager.WidgetManager.register_widget_model('WidgetModel', WidgetModel);
286 287
287 288
288 289 var WidgetView = Backbone.View.extend({
289 290 initialize: function(parameters) {
290 291 // Public constructor.
291 292 this.model.on('change',this.update,this);
292 293 this.options = parameters.options;
293 294 this.child_model_views = {};
294 295 this.child_views = {};
295 this.id = this.id || IPython.utils.uuid();
296 this.id = this.id || utils.uuid();
296 297 this.model.views[this.id] = this;
297 298 this.on('displayed', function() {
298 299 this.is_displayed = true;
299 300 }, this);
300 301 },
301 302
302 303 update: function(){
303 304 // Triggered on model change.
304 305 //
305 306 // Update view to be consistent with this.model
306 307 },
307 308
308 309 create_child_view: function(child_model, options) {
309 310 // Create and promise that resolves to a child view of a given model
310 311 var that = this;
311 312 options = $.extend({ parent: this }, options || {});
312 313 return this.model.widget_manager.create_view(child_model, options).then(function(child_view) {
313 314 // Associate the view id with the model id.
314 315 if (that.child_model_views[child_model.id] === undefined) {
315 316 that.child_model_views[child_model.id] = [];
316 317 }
317 318 that.child_model_views[child_model.id].push(child_view.id);
318 319 // Remember the view by id.
319 320 that.child_views[child_view.id] = child_view;
320 321 return child_view;
321 322 });
322 323 },
323 324
324 325 pop_child_view: function(child_model) {
325 326 // Delete a child view that was previously created using create_child_view.
326 327 var view_ids = this.child_model_views[child_model.id];
327 328 if (view_ids !== undefined) {
328 329
329 330 // Only delete the first view in the list.
330 331 var view_id = view_ids[0];
331 332 var view = this.child_views[view_id];
332 333 delete this.child_views[view_id];
333 334 view_ids.splice(0,1);
334 335 delete child_model.views[view_id];
335 336
336 337 // Remove the view list specific to this model if it is empty.
337 338 if (view_ids.length === 0) {
338 339 delete this.child_model_views[child_model.id];
339 340 }
340 341 return view;
341 342 }
342 343 return null;
343 344 },
344 345
345 346 do_diff: function(old_list, new_list, removed_callback, added_callback) {
346 347 // Difference a changed list and call remove and add callbacks for
347 348 // each removed and added item in the new list.
348 349 //
349 350 // Parameters
350 351 // ----------
351 352 // old_list : array
352 353 // new_list : array
353 354 // removed_callback : Callback(item)
354 355 // Callback that is called for each item removed.
355 356 // added_callback : Callback(item)
356 357 // Callback that is called for each item added.
357 358
358 359 // Walk the lists until an unequal entry is found.
359 360 var i;
360 361 for (i = 0; i < new_list.length; i++) {
361 362 if (i >= old_list.length || new_list[i] !== old_list[i]) {
362 363 break;
363 364 }
364 365 }
365 366
366 367 // Remove the non-matching items from the old list.
367 368 for (var j = i; j < old_list.length; j++) {
368 369 removed_callback(old_list[j]);
369 370 }
370 371
371 372 // Add the rest of the new list items.
372 373 for (; i < new_list.length; i++) {
373 374 added_callback(new_list[i]);
374 375 }
375 376 },
376 377
377 378 callbacks: function(){
378 379 // Create msg callbacks for a comm msg.
379 380 return this.model.callbacks(this);
380 381 },
381 382
382 383 render: function(){
383 384 // Render the view.
384 385 //
385 386 // By default, this is only called the first time the view is created
386 387 },
387 388
388 389 show: function(){
389 390 // Show the widget-area
390 391 if (this.options && this.options.cell &&
391 392 this.options.cell.widget_area !== undefined) {
392 393 this.options.cell.widget_area.show();
393 394 }
394 395 },
395 396
396 397 send: function (content) {
397 398 // Send a custom msg associated with this view.
398 399 this.model.send(content, this.callbacks());
399 400 },
400 401
401 402 touch: function () {
402 403 this.model.save_changes(this.callbacks());
403 404 },
404 405
405 406 after_displayed: function (callback, context) {
406 407 // Calls the callback right away is the view is already displayed
407 408 // otherwise, register the callback to the 'displayed' event.
408 409 if (this.is_displayed) {
409 410 callback.apply(context);
410 411 } else {
411 412 this.on('displayed', callback, context);
412 413 }
413 414 },
414 415 });
415 416
416 417
417 418 var DOMWidgetView = WidgetView.extend({
418 419 initialize: function (parameters) {
419 420 // Public constructor
420 421 DOMWidgetView.__super__.initialize.apply(this, [parameters]);
421 422 this.on('displayed', this.show, this);
422 423 this.model.on('change:visible', this.update_visible, this);
423 424 this.model.on('change:_css', this.update_css, this);
424 425
425 426 this.model.on('change:_dom_classes', function(model, new_classes) {
426 427 var old_classes = model.previous('_dom_classes');
427 428 this.update_classes(old_classes, new_classes);
428 429 }, this);
429 430
430 431 this.model.on('change:color', function (model, value) {
431 432 this.update_attr('color', value); }, this);
432 433
433 434 this.model.on('change:background_color', function (model, value) {
434 435 this.update_attr('background', value); }, this);
435 436
436 437 this.model.on('change:width', function (model, value) {
437 438 this.update_attr('width', value); }, this);
438 439
439 440 this.model.on('change:height', function (model, value) {
440 441 this.update_attr('height', value); }, this);
441 442
442 443 this.model.on('change:border_color', function (model, value) {
443 444 this.update_attr('border-color', value); }, this);
444 445
445 446 this.model.on('change:border_width', function (model, value) {
446 447 this.update_attr('border-width', value); }, this);
447 448
448 449 this.model.on('change:border_style', function (model, value) {
449 450 this.update_attr('border-style', value); }, this);
450 451
451 452 this.model.on('change:font_style', function (model, value) {
452 453 this.update_attr('font-style', value); }, this);
453 454
454 455 this.model.on('change:font_weight', function (model, value) {
455 456 this.update_attr('font-weight', value); }, this);
456 457
457 458 this.model.on('change:font_size', function (model, value) {
458 459 this.update_attr('font-size', this._default_px(value)); }, this);
459 460
460 461 this.model.on('change:font_family', function (model, value) {
461 462 this.update_attr('font-family', value); }, this);
462 463
463 464 this.model.on('change:padding', function (model, value) {
464 465 this.update_attr('padding', value); }, this);
465 466
466 467 this.model.on('change:margin', function (model, value) {
467 468 this.update_attr('margin', this._default_px(value)); }, this);
468 469
469 470 this.model.on('change:border_radius', function (model, value) {
470 471 this.update_attr('border-radius', this._default_px(value)); }, this);
471 472
472 473 this.after_displayed(function() {
473 474 this.update_visible(this.model, this.model.get("visible"));
474 475 this.update_classes([], this.model.get('_dom_classes'));
475 476
476 477 this.update_attr('color', this.model.get('color'));
477 478 this.update_attr('background', this.model.get('background_color'));
478 479 this.update_attr('width', this.model.get('width'));
479 480 this.update_attr('height', this.model.get('height'));
480 481 this.update_attr('border-color', this.model.get('border_color'));
481 482 this.update_attr('border-width', this.model.get('border_width'));
482 483 this.update_attr('border-style', this.model.get('border_style'));
483 484 this.update_attr('font-style', this.model.get('font_style'));
484 485 this.update_attr('font-weight', this.model.get('font_weight'));
485 486 this.update_attr('font-size', this.model.get('font_size'));
486 487 this.update_attr('font-family', this.model.get('font_family'));
487 488 this.update_attr('padding', this.model.get('padding'));
488 489 this.update_attr('margin', this.model.get('margin'));
489 490 this.update_attr('border-radius', this.model.get('border_radius'));
490 491
491 492 this.update_css(this.model, this.model.get("_css"));
492 493 }, this);
493 494 },
494 495
495 496 _default_px: function(value) {
496 497 // Makes browser interpret a numerical string as a pixel value.
497 498 if (/^\d+\.?(\d+)?$/.test(value.trim())) {
498 499 return value.trim() + 'px';
499 500 }
500 501 return value;
501 502 },
502 503
503 504 update_attr: function(name, value) {
504 505 // Set a css attr of the widget view.
505 506 this.$el.css(name, value);
506 507 },
507 508
508 509 update_visible: function(model, value) {
509 510 // Update visibility
510 511 this.$el.toggle(value);
511 512 },
512 513
513 514 update_css: function (model, css) {
514 515 // Update the css styling of this view.
515 516 var e = this.$el;
516 517 if (css === undefined) {return;}
517 518 for (var i = 0; i < css.length; i++) {
518 519 // Apply the css traits to all elements that match the selector.
519 520 var selector = css[i][0];
520 521 var elements = this._get_selector_element(selector);
521 522 if (elements.length > 0) {
522 523 var trait_key = css[i][1];
523 524 var trait_value = css[i][2];
524 525 elements.css(trait_key ,trait_value);
525 526 }
526 527 }
527 528 },
528 529
529 530 update_classes: function (old_classes, new_classes, $el) {
530 531 // Update the DOM classes applied to an element, default to this.$el.
531 532 if ($el===undefined) {
532 533 $el = this.$el;
533 534 }
534 535 this.do_diff(old_classes, new_classes, function(removed) {
535 536 $el.removeClass(removed);
536 537 }, function(added) {
537 538 $el.addClass(added);
538 539 });
539 540 },
540 541
541 542 update_mapped_classes: function(class_map, trait_name, previous_trait_value, $el) {
542 543 // Update the DOM classes applied to the widget based on a single
543 544 // trait's value.
544 545 //
545 546 // Given a trait value classes map, this function automatically
546 547 // handles applying the appropriate classes to the widget element
547 548 // and removing classes that are no longer valid.
548 549 //
549 550 // Parameters
550 551 // ----------
551 552 // class_map: dictionary
552 553 // Dictionary of trait values to class lists.
553 554 // Example:
554 555 // {
555 556 // success: ['alert', 'alert-success'],
556 557 // info: ['alert', 'alert-info'],
557 558 // warning: ['alert', 'alert-warning'],
558 559 // danger: ['alert', 'alert-danger']
559 560 // };
560 561 // trait_name: string
561 562 // Name of the trait to check the value of.
562 563 // previous_trait_value: optional string, default ''
563 564 // Last trait value
564 565 // $el: optional jQuery element handle, defaults to this.$el
565 566 // Element that the classes are applied to.
566 567 var key = previous_trait_value;
567 568 if (key === undefined) {
568 569 key = this.model.previous(trait_name);
569 570 }
570 571 var old_classes = class_map[key] ? class_map[key] : [];
571 572 key = this.model.get(trait_name);
572 573 var new_classes = class_map[key] ? class_map[key] : [];
573 574
574 575 this.update_classes(old_classes, new_classes, $el || this.$el);
575 576 },
576 577
577 578 _get_selector_element: function (selector) {
578 579 // Get the elements via the css selector.
579 580 var elements;
580 581 if (!selector) {
581 582 elements = this.$el;
582 583 } else {
583 584 elements = this.$el.find(selector).addBack(selector);
584 585 }
585 586 return elements;
586 587 },
587 588 });
588 589
589 590
590 591 var widget = {
591 592 'WidgetModel': WidgetModel,
592 593 'WidgetView': WidgetView,
593 594 'DOMWidgetView': DOMWidgetView,
594 595 };
595 596
596 597 // For backwards compatability.
597 598 $.extend(IPython, widget);
598 599
599 600 return widget;
600 601 });
General Comments 0
You need to be logged in to leave comments. Login now