##// END OF EJS Templates
Merge pull request #6920 from SylvainCorlay/serialize_date...
Min RK -
r18833:25c9cfb8 merge
parent child Browse files
Show More
@@ -1,621 +1,622 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/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
239 } else if (value instanceof Date || value instanceof String) {
240 return value;
240 241 } else if (value instanceof Object) {
241 242 packed = {};
242 243 _.each(value, function(sub_value, key) {
243 244 packed[key] = that._pack_models(sub_value);
244 245 });
245 246 return packed;
246 247
247 248 } else {
248 249 return value;
249 250 }
250 251 },
251 252
252 253 _unpack_models: function(value) {
253 254 // Replace model ids with models recursively.
254 255 var that = this;
255 256 var unpacked;
256 257 if ($.isArray(value)) {
257 258 unpacked = [];
258 259 _.each(value, function(sub_value, key) {
259 260 unpacked.push(that._unpack_models(sub_value));
260 261 });
261 262 return unpacked;
262 263
263 264 } else if (value instanceof Object) {
264 265 unpacked = {};
265 266 _.each(value, function(sub_value, key) {
266 267 unpacked[key] = that._unpack_models(sub_value);
267 268 });
268 269 return unpacked;
269 270
270 271 } else if (typeof value === 'string' && value.slice(0,10) === "IPY_MODEL_") {
271 272 var model = this.widget_manager.get_model(value.slice(10, value.length));
272 273 if (model) {
273 274 return model;
274 275 } else {
275 276 return value;
276 277 }
277 278 } else {
278 279 return value;
279 280 }
280 281 },
281 282
282 283 on_some_change: function(keys, callback, context) {
283 284 // on_some_change(["key1", "key2"], foo, context) differs from
284 285 // on("change:key1 change:key2", foo, context).
285 286 // If the widget attributes key1 and key2 are both modified,
286 287 // the second form will result in foo being called twice
287 288 // while the first will call foo only once.
288 289 this.on('change', function() {
289 290 if (keys.some(this.hasChanged, this)) {
290 291 callback.apply(context);
291 292 }
292 293 }, this);
293 294
294 295 },
295 296 });
296 297 widgetmanager.WidgetManager.register_widget_model('WidgetModel', WidgetModel);
297 298
298 299
299 300 var WidgetView = Backbone.View.extend({
300 301 initialize: function(parameters) {
301 302 // Public constructor.
302 303 this.model.on('change',this.update,this);
303 304 this.options = parameters.options;
304 305 this.child_model_views = {};
305 306 this.child_views = {};
306 307 this.id = this.id || IPython.utils.uuid();
307 308 this.model.views[this.id] = this;
308 309 this.on('displayed', function() {
309 310 this.is_displayed = true;
310 311 }, this);
311 312 },
312 313
313 314 update: function(){
314 315 // Triggered on model change.
315 316 //
316 317 // Update view to be consistent with this.model
317 318 },
318 319
319 320 create_child_view: function(child_model, options) {
320 321 // Create and return a child view.
321 322 //
322 323 // -given a model and (optionally) a view name if the view name is
323 324 // not given, it defaults to the model's default view attribute.
324 325
325 326 // TODO: this is hacky, and makes the view depend on this cell attribute and widget manager behavior
326 327 // it would be great to have the widget manager add the cell metadata
327 328 // to the subview without having to add it here.
328 329 var that = this;
329 330 var old_callback = options.callback || function(view) {};
330 331 options = $.extend({ parent: this, success: function(child_view) {
331 332 // Associate the view id with the model id.
332 333 if (that.child_model_views[child_model.id] === undefined) {
333 334 that.child_model_views[child_model.id] = [];
334 335 }
335 336 that.child_model_views[child_model.id].push(child_view.id);
336 337
337 338 // Remember the view by id.
338 339 that.child_views[child_view.id] = child_view;
339 340 old_callback(child_view);
340 341 }}, options || {});
341 342
342 343 this.model.widget_manager.create_view(child_model, options);
343 344 },
344 345
345 346 pop_child_view: function(child_model) {
346 347 // Delete a child view that was previously created using create_child_view.
347 348 var view_ids = this.child_model_views[child_model.id];
348 349 if (view_ids !== undefined) {
349 350
350 351 // Only delete the first view in the list.
351 352 var view_id = view_ids[0];
352 353 var view = this.child_views[view_id];
353 354 delete this.child_views[view_id];
354 355 view_ids.splice(0,1);
355 356 delete child_model.views[view_id];
356 357
357 358 // Remove the view list specific to this model if it is empty.
358 359 if (view_ids.length === 0) {
359 360 delete this.child_model_views[child_model.id];
360 361 }
361 362 return view;
362 363 }
363 364 return null;
364 365 },
365 366
366 367 do_diff: function(old_list, new_list, removed_callback, added_callback) {
367 368 // Difference a changed list and call remove and add callbacks for
368 369 // each removed and added item in the new list.
369 370 //
370 371 // Parameters
371 372 // ----------
372 373 // old_list : array
373 374 // new_list : array
374 375 // removed_callback : Callback(item)
375 376 // Callback that is called for each item removed.
376 377 // added_callback : Callback(item)
377 378 // Callback that is called for each item added.
378 379
379 380 // Walk the lists until an unequal entry is found.
380 381 var i;
381 382 for (i = 0; i < new_list.length; i++) {
382 383 if (i >= old_list.length || new_list[i] !== old_list[i]) {
383 384 break;
384 385 }
385 386 }
386 387
387 388 // Remove the non-matching items from the old list.
388 389 for (var j = i; j < old_list.length; j++) {
389 390 removed_callback(old_list[j]);
390 391 }
391 392
392 393 // Add the rest of the new list items.
393 394 for (; i < new_list.length; i++) {
394 395 added_callback(new_list[i]);
395 396 }
396 397 },
397 398
398 399 callbacks: function(){
399 400 // Create msg callbacks for a comm msg.
400 401 return this.model.callbacks(this);
401 402 },
402 403
403 404 render: function(){
404 405 // Render the view.
405 406 //
406 407 // By default, this is only called the first time the view is created
407 408 },
408 409
409 410 show: function(){
410 411 // Show the widget-area
411 412 if (this.options && this.options.cell &&
412 413 this.options.cell.widget_area !== undefined) {
413 414 this.options.cell.widget_area.show();
414 415 }
415 416 },
416 417
417 418 send: function (content) {
418 419 // Send a custom msg associated with this view.
419 420 this.model.send(content, this.callbacks());
420 421 },
421 422
422 423 touch: function () {
423 424 this.model.save_changes(this.callbacks());
424 425 },
425 426
426 427 after_displayed: function (callback, context) {
427 428 // Calls the callback right away is the view is already displayed
428 429 // otherwise, register the callback to the 'displayed' event.
429 430 if (this.is_displayed) {
430 431 callback.apply(context);
431 432 } else {
432 433 this.on('displayed', callback, context);
433 434 }
434 435 },
435 436 });
436 437
437 438
438 439 var DOMWidgetView = WidgetView.extend({
439 440 initialize: function (parameters) {
440 441 // Public constructor
441 442 DOMWidgetView.__super__.initialize.apply(this, [parameters]);
442 443 this.on('displayed', this.show, this);
443 444 this.model.on('change:visible', this.update_visible, this);
444 445 this.model.on('change:_css', this.update_css, this);
445 446
446 447 this.model.on('change:_dom_classes', function(model, new_classes) {
447 448 var old_classes = model.previous('_dom_classes');
448 449 this.update_classes(old_classes, new_classes);
449 450 }, this);
450 451
451 452 this.model.on('change:color', function (model, value) {
452 453 this.update_attr('color', value); }, this);
453 454
454 455 this.model.on('change:background_color', function (model, value) {
455 456 this.update_attr('background', value); }, this);
456 457
457 458 this.model.on('change:width', function (model, value) {
458 459 this.update_attr('width', value); }, this);
459 460
460 461 this.model.on('change:height', function (model, value) {
461 462 this.update_attr('height', value); }, this);
462 463
463 464 this.model.on('change:border_color', function (model, value) {
464 465 this.update_attr('border-color', value); }, this);
465 466
466 467 this.model.on('change:border_width', function (model, value) {
467 468 this.update_attr('border-width', value); }, this);
468 469
469 470 this.model.on('change:border_style', function (model, value) {
470 471 this.update_attr('border-style', value); }, this);
471 472
472 473 this.model.on('change:font_style', function (model, value) {
473 474 this.update_attr('font-style', value); }, this);
474 475
475 476 this.model.on('change:font_weight', function (model, value) {
476 477 this.update_attr('font-weight', value); }, this);
477 478
478 479 this.model.on('change:font_size', function (model, value) {
479 480 this.update_attr('font-size', this._default_px(value)); }, this);
480 481
481 482 this.model.on('change:font_family', function (model, value) {
482 483 this.update_attr('font-family', value); }, this);
483 484
484 485 this.model.on('change:padding', function (model, value) {
485 486 this.update_attr('padding', value); }, this);
486 487
487 488 this.model.on('change:margin', function (model, value) {
488 489 this.update_attr('margin', this._default_px(value)); }, this);
489 490
490 491 this.model.on('change:border_radius', function (model, value) {
491 492 this.update_attr('border-radius', this._default_px(value)); }, this);
492 493
493 494 this.after_displayed(function() {
494 495 this.update_visible(this.model, this.model.get("visible"));
495 496 this.update_classes([], this.model.get('_dom_classes'));
496 497
497 498 this.update_attr('color', this.model.get('color'));
498 499 this.update_attr('background', this.model.get('background_color'));
499 500 this.update_attr('width', this.model.get('width'));
500 501 this.update_attr('height', this.model.get('height'));
501 502 this.update_attr('border-color', this.model.get('border_color'));
502 503 this.update_attr('border-width', this.model.get('border_width'));
503 504 this.update_attr('border-style', this.model.get('border_style'));
504 505 this.update_attr('font-style', this.model.get('font_style'));
505 506 this.update_attr('font-weight', this.model.get('font_weight'));
506 507 this.update_attr('font-size', this.model.get('font_size'));
507 508 this.update_attr('font-family', this.model.get('font_family'));
508 509 this.update_attr('padding', this.model.get('padding'));
509 510 this.update_attr('margin', this.model.get('margin'));
510 511 this.update_attr('border-radius', this.model.get('border_radius'));
511 512
512 513 this.update_css(this.model, this.model.get("_css"));
513 514 }, this);
514 515 },
515 516
516 517 _default_px: function(value) {
517 518 // Makes browser interpret a numerical string as a pixel value.
518 519 if (/^\d+\.?(\d+)?$/.test(value.trim())) {
519 520 return value.trim() + 'px';
520 521 }
521 522 return value;
522 523 },
523 524
524 525 update_attr: function(name, value) {
525 526 // Set a css attr of the widget view.
526 527 this.$el.css(name, value);
527 528 },
528 529
529 530 update_visible: function(model, value) {
530 531 // Update visibility
531 532 this.$el.toggle(value);
532 533 },
533 534
534 535 update_css: function (model, css) {
535 536 // Update the css styling of this view.
536 537 var e = this.$el;
537 538 if (css === undefined) {return;}
538 539 for (var i = 0; i < css.length; i++) {
539 540 // Apply the css traits to all elements that match the selector.
540 541 var selector = css[i][0];
541 542 var elements = this._get_selector_element(selector);
542 543 if (elements.length > 0) {
543 544 var trait_key = css[i][1];
544 545 var trait_value = css[i][2];
545 546 elements.css(trait_key ,trait_value);
546 547 }
547 548 }
548 549 },
549 550
550 551 update_classes: function (old_classes, new_classes, $el) {
551 552 // Update the DOM classes applied to an element, default to this.$el.
552 553 if ($el===undefined) {
553 554 $el = this.$el;
554 555 }
555 556 this.do_diff(old_classes, new_classes, function(removed) {
556 557 $el.removeClass(removed);
557 558 }, function(added) {
558 559 $el.addClass(added);
559 560 });
560 561 },
561 562
562 563 update_mapped_classes: function(class_map, trait_name, previous_trait_value, $el) {
563 564 // Update the DOM classes applied to the widget based on a single
564 565 // trait's value.
565 566 //
566 567 // Given a trait value classes map, this function automatically
567 568 // handles applying the appropriate classes to the widget element
568 569 // and removing classes that are no longer valid.
569 570 //
570 571 // Parameters
571 572 // ----------
572 573 // class_map: dictionary
573 574 // Dictionary of trait values to class lists.
574 575 // Example:
575 576 // {
576 577 // success: ['alert', 'alert-success'],
577 578 // info: ['alert', 'alert-info'],
578 579 // warning: ['alert', 'alert-warning'],
579 580 // danger: ['alert', 'alert-danger']
580 581 // };
581 582 // trait_name: string
582 583 // Name of the trait to check the value of.
583 584 // previous_trait_value: optional string, default ''
584 585 // Last trait value
585 586 // $el: optional jQuery element handle, defaults to this.$el
586 587 // Element that the classes are applied to.
587 588 var key = previous_trait_value;
588 589 if (key === undefined) {
589 590 key = this.model.previous(trait_name);
590 591 }
591 592 var old_classes = class_map[key] ? class_map[key] : [];
592 593 key = this.model.get(trait_name);
593 594 var new_classes = class_map[key] ? class_map[key] : [];
594 595
595 596 this.update_classes(old_classes, new_classes, $el || this.$el);
596 597 },
597 598
598 599 _get_selector_element: function (selector) {
599 600 // Get the elements via the css selector.
600 601 var elements;
601 602 if (!selector) {
602 603 elements = this.$el;
603 604 } else {
604 605 elements = this.$el.find(selector).addBack(selector);
605 606 }
606 607 return elements;
607 608 },
608 609 });
609 610
610 611
611 612 var widget = {
612 613 'WidgetModel': WidgetModel,
613 614 'WidgetView': WidgetView,
614 615 'DOMWidgetView': DOMWidgetView,
615 616 };
616 617
617 618 // For backwards compatability.
618 619 $.extend(IPython, widget);
619 620
620 621 return widget;
621 622 });
@@ -1,176 +1,177 b''
1 1 var xor = function (a, b) {return !a ^ !b;};
2 2 var isArray = function (a) {
3 3 try {
4 4 return Object.toString.call(a) === "[object Array]" || Object.toString.call(a) === "[object RuntimeArray]";
5 5 } catch (e) {
6 6 return Array.isArray(a);
7 7 }
8 8 };
9 9 var recursive_compare = function(a, b) {
10 10 // Recursively compare two objects.
11 11 var same = true;
12 12 same = same && !xor(a instanceof Object || typeof a == 'object', b instanceof Object || typeof b == 'object');
13 13 same = same && !xor(isArray(a), isArray(b));
14 14
15 15 if (same) {
16 16 if (a instanceof Object) {
17 17 var key;
18 18 for (key in a) {
19 19 if (a.hasOwnProperty(key) && !recursive_compare(a[key], b[key])) {
20 20 same = false;
21 21 break;
22 22 }
23 23 }
24 24 for (key in b) {
25 25 if (b.hasOwnProperty(key) && !recursive_compare(a[key], b[key])) {
26 26 same = false;
27 27 break;
28 28 }
29 29 }
30 30 } else {
31 31 return a === b;
32 32 }
33 33 }
34 34
35 35 return same;
36 36 };
37 37
38 38 // Test the widget framework.
39 39 casper.notebook_test(function () {
40 40 var index;
41 41
42 42 index = this.append_cell(
43 43 'from IPython.html import widgets\n' +
44 44 'from IPython.display import display, clear_output\n' +
45 45 'print("Success")');
46 46 this.execute_cell_then(index);
47 47
48 48 this.then(function () {
49 49
50 50 // Functions that can be used to test the packing and unpacking APIs
51 51 var that = this;
52 52 var test_pack = function (input) {
53 53 var output = that.evaluate(function(input) {
54 54 var model = new IPython.WidgetModel(IPython.notebook.kernel.widget_manager, undefined);
55 55 var results = model._pack_models(input);
56 56 return results;
57 57 }, {input: input});
58 58 that.test.assert(recursive_compare(input, output),
59 59 JSON.stringify(input) + ' passed through Model._pack_model unchanged');
60 60 };
61 61 var test_unpack = function (input) {
62 62 var output = that.evaluate(function(input) {
63 63 var model = new IPython.WidgetModel(IPython.notebook.kernel.widget_manager, undefined);
64 64 var results = model._unpack_models(input);
65 65 return results;
66 66 }, {input: input});
67 67 that.test.assert(recursive_compare(input, output),
68 68 JSON.stringify(input) + ' passed through Model._unpack_model unchanged');
69 69 };
70 70 var test_packing = function(input) {
71 71 test_pack(input);
72 72 test_unpack(input);
73 73 };
74 74
75 75 test_packing({0: 'hi', 1: 'bye'});
76 76 test_packing(['hi', 'bye']);
77 77 test_packing(['hi', 5]);
78 78 test_packing(['hi', '5']);
79 79 test_packing([1.0, 0]);
80 80 test_packing([1.0, false]);
81 81 test_packing([1, false]);
82 82 test_packing([1, false, {a: 'hi'}]);
83 83 test_packing([1, false, ['hi']]);
84 test_packing([String('hi'), Date("Thu Nov 13 2014 13:46:21 GMT-0500")])
84 85
85 86 // Test multi-set, single touch code. First create a custom widget.
86 87 this.evaluate(function() {
87 88 var MultiSetView = IPython.DOMWidgetView.extend({
88 89 render: function(){
89 90 this.model.set('a', 1);
90 91 this.model.set('b', 2);
91 92 this.model.set('c', 3);
92 93 this.touch();
93 94 },
94 95 });
95 96 IPython.WidgetManager.register_widget_view('MultiSetView', MultiSetView);
96 97 }, {});
97 98 });
98 99
99 100 // Try creating the multiset widget, verify that sets the values correctly.
100 101 var multiset = {};
101 102 multiset.index = this.append_cell(
102 103 'from IPython.utils.traitlets import Unicode, CInt\n' +
103 104 'class MultiSetWidget(widgets.Widget):\n' +
104 105 ' _view_name = Unicode("MultiSetView", sync=True)\n' +
105 106 ' a = CInt(0, sync=True)\n' +
106 107 ' b = CInt(0, sync=True)\n' +
107 108 ' c = CInt(0, sync=True)\n' +
108 109 ' d = CInt(-1, sync=True)\n' + // See if it sends a full state.
109 110 ' def set_state(self, sync_data):\n' +
110 111 ' widgets.Widget.set_state(self, sync_data)\n'+
111 112 ' self.d = len(sync_data)\n' +
112 113 'multiset = MultiSetWidget()\n' +
113 114 'display(multiset)\n' +
114 115 'print(multiset.model_id)');
115 116 this.execute_cell_then(multiset.index, function(index) {
116 117 multiset.model_id = this.get_output_cell(index).text.trim();
117 118 });
118 119
119 120 this.wait_for_widget(multiset);
120 121
121 122 index = this.append_cell(
122 123 'print("%d%d%d" % (multiset.a, multiset.b, multiset.c))');
123 124 this.execute_cell_then(index, function(index) {
124 125 this.test.assertEquals(this.get_output_cell(index).text.trim(), '123',
125 126 'Multiple model.set calls and one view.touch update state in back-end.');
126 127 });
127 128
128 129 index = this.append_cell(
129 130 'print("%d" % (multiset.d))');
130 131 this.execute_cell_then(index, function(index) {
131 132 this.test.assertEquals(this.get_output_cell(index).text.trim(), '3',
132 133 'Multiple model.set calls sent a partial state.');
133 134 });
134 135
135 136 var textbox = {};
136 137 throttle_index = this.append_cell(
137 138 'import time\n' +
138 139 'textbox = widgets.Text()\n' +
139 140 'display(textbox)\n' +
140 141 'textbox._dom_classes = ["my-throttle-textbox"]\n' +
141 142 'def handle_change(name, old, new):\n' +
142 143 ' display(len(new))\n' +
143 144 ' time.sleep(0.5)\n' +
144 145 'textbox.on_trait_change(handle_change, "value")\n' +
145 146 'print(textbox.model_id)');
146 147 this.execute_cell_then(throttle_index, function(index){
147 148 textbox.model_id = this.get_output_cell(index).text.trim();
148 149
149 150 this.test.assert(this.cell_element_exists(index,
150 151 '.widget-area .widget-subarea'),
151 152 'Widget subarea exists.');
152 153
153 154 this.test.assert(this.cell_element_exists(index,
154 155 '.my-throttle-textbox'), 'Textbox exists.');
155 156
156 157 // Send 20 characters
157 158 this.sendKeys('.my-throttle-textbox input', '....................');
158 159 });
159 160
160 161 this.wait_for_widget(textbox);
161 162
162 163 this.then(function () {
163 164 var outputs = this.evaluate(function(i) {
164 165 return IPython.notebook.get_cell(i).output_area.outputs;
165 166 }, {i : throttle_index});
166 167
167 168 // Only 4 outputs should have printed, but because of timing, sometimes
168 169 // 5 outputs will print. All we need to do is verify num outputs <= 5
169 170 // because that is much less than 20.
170 171 this.test.assert(outputs.length <= 5, 'Messages throttled.');
171 172
172 173 // We also need to verify that the last state sent was correct.
173 174 var last_state = outputs[outputs.length-1].data['text/plain'];
174 175 this.test.assertEquals(last_state, "20", "Last state sent when throttling.");
175 176 });
176 177 });
General Comments 0
You need to be logged in to leave comments. Login now