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