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