##// END OF EJS Templates
Merge pull request #5059 from jdfreder/widgets-patch-fix...
Brian E. Granger -
r15300:5258b9ec merge
parent child Browse files
Show More
@@ -1,437 +1,451 b''
1 //----------------------------------------------------------------------------
1 //----------------------------------------------------------------------------
2 // Copyright (C) 2013 The IPython Development Team
2 // Copyright (C) 2013 The IPython Development Team
3 //
3 //
4 // Distributed under the terms of the BSD License. The full license is in
4 // Distributed under the terms of the BSD License. The full license is in
5 // the file COPYING, distributed as part of this software.
5 // the file COPYING, distributed as part of this software.
6 //----------------------------------------------------------------------------
6 //----------------------------------------------------------------------------
7
7
8 //============================================================================
8 //============================================================================
9 // Base Widget Model and View classes
9 // Base Widget Model and View classes
10 //============================================================================
10 //============================================================================
11
11
12 /**
12 /**
13 * @module IPython
13 * @module IPython
14 * @namespace IPython
14 * @namespace IPython
15 **/
15 **/
16
16
17 define(["notebook/js/widgetmanager",
17 define(["notebook/js/widgetmanager",
18 "underscore",
18 "underscore",
19 "backbone"],
19 "backbone"],
20 function(WidgetManager, _, Backbone){
20 function(WidgetManager, _, Backbone){
21
21
22 var WidgetModel = Backbone.Model.extend({
22 var WidgetModel = Backbone.Model.extend({
23 constructor: function (widget_manager, model_id, comm) {
23 constructor: function (widget_manager, model_id, comm) {
24 // Constructor
24 // Constructor
25 //
25 //
26 // Creates a WidgetModel instance.
26 // Creates a WidgetModel instance.
27 //
27 //
28 // Parameters
28 // Parameters
29 // ----------
29 // ----------
30 // widget_manager : WidgetManager instance
30 // widget_manager : WidgetManager instance
31 // model_id : string
31 // model_id : string
32 // An ID unique to this model.
32 // An ID unique to this model.
33 // comm : Comm instance (optional)
33 // comm : Comm instance (optional)
34 this.widget_manager = widget_manager;
34 this.widget_manager = widget_manager;
35 this._buffered_state_diff = {};
35 this.pending_msgs = 0;
36 this.pending_msgs = 0;
36 this.msg_throttle = 3;
37 this.msg_throttle = 3;
37 this.msg_buffer = null;
38 this.msg_buffer = null;
38 this.key_value_lock = null;
39 this.key_value_lock = null;
39 this.id = model_id;
40 this.id = model_id;
40 this.views = [];
41 this.views = [];
41
42
42 if (comm !== undefined) {
43 if (comm !== undefined) {
43 // Remember comm associated with the model.
44 // Remember comm associated with the model.
44 this.comm = comm;
45 this.comm = comm;
45 comm.model = this;
46 comm.model = this;
46
47
47 // Hook comm messages up to model.
48 // Hook comm messages up to model.
48 comm.on_close($.proxy(this._handle_comm_closed, this));
49 comm.on_close($.proxy(this._handle_comm_closed, this));
49 comm.on_msg($.proxy(this._handle_comm_msg, this));
50 comm.on_msg($.proxy(this._handle_comm_msg, this));
50 }
51 }
51 return Backbone.Model.apply(this);
52 return Backbone.Model.apply(this);
52 },
53 },
53
54
54 send: function (content, callbacks) {
55 send: function (content, callbacks) {
55 // Send a custom msg over the comm.
56 // Send a custom msg over the comm.
56 if (this.comm !== undefined) {
57 if (this.comm !== undefined) {
57 var data = {method: 'custom', content: content};
58 var data = {method: 'custom', content: content};
58 this.comm.send(data, callbacks);
59 this.comm.send(data, callbacks);
59 this.pending_msgs++;
60 this.pending_msgs++;
60 }
61 }
61 },
62 },
62
63
63 _handle_comm_closed: function (msg) {
64 _handle_comm_closed: function (msg) {
64 // Handle when a widget is closed.
65 // Handle when a widget is closed.
65 this.trigger('comm:close');
66 this.trigger('comm:close');
66 delete this.comm.model; // Delete ref so GC will collect widget model.
67 delete this.comm.model; // Delete ref so GC will collect widget model.
67 delete this.comm;
68 delete this.comm;
68 delete this.model_id; // Delete id from model so widget manager cleans up.
69 delete this.model_id; // Delete id from model so widget manager cleans up.
69 _.each(this.views, function(view, i) {
70 _.each(this.views, function(view, i) {
70 view.remove();
71 view.remove();
71 });
72 });
72 },
73 },
73
74
74 _handle_comm_msg: function (msg) {
75 _handle_comm_msg: function (msg) {
75 // Handle incoming comm msg.
76 // Handle incoming comm msg.
76 var method = msg.content.data.method;
77 var method = msg.content.data.method;
77 switch (method) {
78 switch (method) {
78 case 'update':
79 case 'update':
79 this.apply_update(msg.content.data.state);
80 this.apply_update(msg.content.data.state);
80 break;
81 break;
81 case 'custom':
82 case 'custom':
82 this.trigger('msg:custom', msg.content.data.content);
83 this.trigger('msg:custom', msg.content.data.content);
83 break;
84 break;
84 case 'display':
85 case 'display':
85 this.widget_manager.display_view(msg, this);
86 this.widget_manager.display_view(msg, this);
86 break;
87 break;
87 }
88 }
88 },
89 },
89
90
90 apply_update: function (state) {
91 apply_update: function (state) {
91 // Handle when a widget is updated via the python side.
92 // Handle when a widget is updated via the python side.
92 var that = this;
93 var that = this;
93 _.each(state, function(value, key) {
94 _.each(state, function(value, key) {
94 that.key_value_lock = [key, value];
95 that.key_value_lock = [key, value];
95 try {
96 try {
96 that.set(key, that._unpack_models(value));
97 WidgetModel.__super__.set.apply(that, [key, that._unpack_models(value)]);
97 } finally {
98 } finally {
98 that.key_value_lock = null;
99 that.key_value_lock = null;
99 }
100 }
100 });
101 });
101 },
102 },
102
103
103 _handle_status: function (msg, callbacks) {
104 _handle_status: function (msg, callbacks) {
104 // Handle status msgs.
105 // Handle status msgs.
105
106
106 // execution_state : ('busy', 'idle', 'starting')
107 // execution_state : ('busy', 'idle', 'starting')
107 if (this.comm !== undefined) {
108 if (this.comm !== undefined) {
108 if (msg.content.execution_state ==='idle') {
109 if (msg.content.execution_state ==='idle') {
109 // Send buffer if this message caused another message to be
110 // Send buffer if this message caused another message to be
110 // throttled.
111 // throttled.
111 if (this.msg_buffer !== null &&
112 if (this.msg_buffer !== null &&
112 this.msg_throttle === this.pending_msgs) {
113 this.msg_throttle === this.pending_msgs) {
113 var data = {method: 'backbone', sync_method: 'update', sync_data: this.msg_buffer};
114 var data = {method: 'backbone', sync_method: 'update', sync_data: this.msg_buffer};
114 this.comm.send(data, callbacks);
115 this.comm.send(data, callbacks);
115 this.msg_buffer = null;
116 this.msg_buffer = null;
116 } else {
117 } else {
117 --this.pending_msgs;
118 --this.pending_msgs;
118 }
119 }
119 }
120 }
120 }
121 }
121 },
122 },
122
123
123 callbacks: function(view) {
124 callbacks: function(view) {
124 // Create msg callbacks for a comm msg.
125 // Create msg callbacks for a comm msg.
125 var callbacks = this.widget_manager.callbacks(view);
126 var callbacks = this.widget_manager.callbacks(view);
126
127
127 if (callbacks.iopub === undefined) {
128 if (callbacks.iopub === undefined) {
128 callbacks.iopub = {};
129 callbacks.iopub = {};
129 }
130 }
130
131
131 var that = this;
132 var that = this;
132 callbacks.iopub.status = function (msg) {
133 callbacks.iopub.status = function (msg) {
133 that._handle_status(msg, callbacks);
134 that._handle_status(msg, callbacks);
134 };
135 };
135 return callbacks;
136 return callbacks;
136 },
137 },
137
138
139 set: function(key, val, options) {
140 // Set a value.
141 var return_value = WidgetModel.__super__.set.apply(this, arguments);
142
143 // Backbone only remembers the diff of the most recent set()
144 // operation. Calling set multiple times in a row results in a
145 // loss of diff information. Here we keep our own running diff.
146 this._buffered_state_diff = $.extend(this._buffered_state_diff, this.changedAttributes() || {});
147 return return_value;
148 },
149
138 sync: function (method, model, options) {
150 sync: function (method, model, options) {
139 // Handle sync to the back-end. Called when a model.save() is called.
151 // Handle sync to the back-end. Called when a model.save() is called.
140
152
141 // Make sure a comm exists.
153 // Make sure a comm exists.
142 var error = options.error || function() {
154 var error = options.error || function() {
143 console.error('Backbone sync error:', arguments);
155 console.error('Backbone sync error:', arguments);
144 };
156 };
145 if (this.comm === undefined) {
157 if (this.comm === undefined) {
146 error();
158 error();
147 return false;
159 return false;
148 }
160 }
149
161
150 // Delete any key value pairs that the back-end already knows about.
162 // Delete any key value pairs that the back-end already knows about.
151 var attrs = (method === 'patch') ? options.attrs : model.toJSON(options);
163 var attrs = (method === 'patch') ? options.attrs : model.toJSON(options);
152 if (this.key_value_lock !== null) {
164 if (this.key_value_lock !== null) {
153 var key = this.key_value_lock[0];
165 var key = this.key_value_lock[0];
154 var value = this.key_value_lock[1];
166 var value = this.key_value_lock[1];
155 if (attrs[key] === value) {
167 if (attrs[key] === value) {
156 delete attrs[key];
168 delete attrs[key];
157 }
169 }
158 }
170 }
159
171
160 // Only sync if there are attributes to send to the back-end.
172 // Only sync if there are attributes to send to the back-end.
173 attrs = this._pack_models(attrs);
161 if (_.size(attrs) > 0) {
174 if (_.size(attrs) > 0) {
162
175
163 // If this message was sent via backbone itself, it will not
176 // If this message was sent via backbone itself, it will not
164 // have any callbacks. It's important that we create callbacks
177 // have any callbacks. It's important that we create callbacks
165 // so we can listen for status messages, etc...
178 // so we can listen for status messages, etc...
166 var callbacks = options.callbacks || this.callbacks();
179 var callbacks = options.callbacks || this.callbacks();
167
180
168 // Check throttle.
181 // Check throttle.
169 if (this.pending_msgs >= this.msg_throttle) {
182 if (this.pending_msgs >= this.msg_throttle) {
170 // The throttle has been exceeded, buffer the current msg so
183 // The throttle has been exceeded, buffer the current msg so
171 // it can be sent once the kernel has finished processing
184 // it can be sent once the kernel has finished processing
172 // some of the existing messages.
185 // some of the existing messages.
173
186
174 // Combine updates if it is a 'patch' sync, otherwise replace updates
187 // Combine updates if it is a 'patch' sync, otherwise replace updates
175 switch (method) {
188 switch (method) {
176 case 'patch':
189 case 'patch':
177 this.msg_buffer = $.extend(this.msg_buffer || {}, attrs);
190 this.msg_buffer = $.extend(this.msg_buffer || {}, attrs);
178 break;
191 break;
179 case 'update':
192 case 'update':
180 case 'create':
193 case 'create':
181 this.msg_buffer = attrs;
194 this.msg_buffer = attrs;
182 break;
195 break;
183 default:
196 default:
184 error();
197 error();
185 return false;
198 return false;
186 }
199 }
187 this.msg_buffer_callbacks = callbacks;
200 this.msg_buffer_callbacks = callbacks;
188
201
189 } else {
202 } else {
190 // We haven't exceeded the throttle, send the message like
203 // We haven't exceeded the throttle, send the message like
191 // normal.
204 // normal.
192 var data = {method: 'backbone', sync_data: attrs};
205 var data = {method: 'backbone', sync_data: attrs};
193 this.comm.send(data, callbacks);
206 this.comm.send(data, callbacks);
194 this.pending_msgs++;
207 this.pending_msgs++;
195 }
208 }
196 }
209 }
197 // Since the comm is a one-way communication, assume the message
210 // Since the comm is a one-way communication, assume the message
198 // arrived. Don't call success since we don't have a model back from the server
211 // arrived. Don't call success since we don't have a model back from the server
199 // this means we miss out on the 'sync' event.
212 // this means we miss out on the 'sync' event.
213 this._buffered_state_diff = {};
200 },
214 },
201
215
202 save_changes: function(callbacks) {
216 save_changes: function(callbacks) {
203 // Push this model's state to the back-end
217 // Push this model's state to the back-end
204 //
218 //
205 // This invokes a Backbone.Sync.
219 // This invokes a Backbone.Sync.
206 this.save(this.changedAttributes(), {patch: true, callbacks: callbacks});
220 this.save(this._buffered_state_diff, {patch: true, callbacks: callbacks});
207 },
221 },
208
222
209 _pack_models: function(value) {
223 _pack_models: function(value) {
210 // Replace models with model ids recursively.
224 // Replace models with model ids recursively.
211 if (value instanceof Backbone.Model) {
225 if (value instanceof Backbone.Model) {
212 return value.id;
226 return value.id;
213
227
214 } else if ($.isArray(value)) {
228 } else if ($.isArray(value)) {
215 var packed = [];
229 var packed = [];
216 var that = this;
230 var that = this;
217 _.each(value, function(sub_value, key) {
231 _.each(value, function(sub_value, key) {
218 packed.push(that._pack_models(sub_value));
232 packed.push(that._pack_models(sub_value));
219 });
233 });
220 return packed;
234 return packed;
221
235
222 } else if (value instanceof Object) {
236 } else if (value instanceof Object) {
223 var packed = {};
237 var packed = {};
224 var that = this;
238 var that = this;
225 _.each(value, function(sub_value, key) {
239 _.each(value, function(sub_value, key) {
226 packed[key] = that._pack_models(sub_value);
240 packed[key] = that._pack_models(sub_value);
227 });
241 });
228 return packed;
242 return packed;
229
243
230 } else {
244 } else {
231 return value;
245 return value;
232 }
246 }
233 },
247 },
234
248
235 _unpack_models: function(value) {
249 _unpack_models: function(value) {
236 // Replace model ids with models recursively.
250 // Replace model ids with models recursively.
237 if ($.isArray(value)) {
251 if ($.isArray(value)) {
238 var unpacked = [];
252 var unpacked = [];
239 var that = this;
253 var that = this;
240 _.each(value, function(sub_value, key) {
254 _.each(value, function(sub_value, key) {
241 unpacked.push(that._unpack_models(sub_value));
255 unpacked.push(that._unpack_models(sub_value));
242 });
256 });
243 return unpacked;
257 return unpacked;
244
258
245 } else if (value instanceof Object) {
259 } else if (value instanceof Object) {
246 var unpacked = {};
260 var unpacked = {};
247 var that = this;
261 var that = this;
248 _.each(value, function(sub_value, key) {
262 _.each(value, function(sub_value, key) {
249 unpacked[key] = that._unpack_models(sub_value);
263 unpacked[key] = that._unpack_models(sub_value);
250 });
264 });
251 return unpacked;
265 return unpacked;
252
266
253 } else {
267 } else {
254 var model = this.widget_manager.get_model(value);
268 var model = this.widget_manager.get_model(value);
255 if (model) {
269 if (model) {
256 return model;
270 return model;
257 } else {
271 } else {
258 return value;
272 return value;
259 }
273 }
260 }
274 }
261 },
275 },
262
276
263 });
277 });
264 WidgetManager.register_widget_model('WidgetModel', WidgetModel);
278 WidgetManager.register_widget_model('WidgetModel', WidgetModel);
265
279
266
280
267 var WidgetView = Backbone.View.extend({
281 var WidgetView = Backbone.View.extend({
268 initialize: function(parameters) {
282 initialize: function(parameters) {
269 // Public constructor.
283 // Public constructor.
270 this.model.on('change',this.update,this);
284 this.model.on('change',this.update,this);
271 this.options = parameters.options;
285 this.options = parameters.options;
272 this.child_views = [];
286 this.child_views = [];
273 this.model.views.push(this);
287 this.model.views.push(this);
274 },
288 },
275
289
276 update: function(){
290 update: function(){
277 // Triggered on model change.
291 // Triggered on model change.
278 //
292 //
279 // Update view to be consistent with this.model
293 // Update view to be consistent with this.model
280 },
294 },
281
295
282 create_child_view: function(child_model, options) {
296 create_child_view: function(child_model, options) {
283 // Create and return a child view.
297 // Create and return a child view.
284 //
298 //
285 // -given a model and (optionally) a view name if the view name is
299 // -given a model and (optionally) a view name if the view name is
286 // not given, it defaults to the model's default view attribute.
300 // not given, it defaults to the model's default view attribute.
287
301
288 // TODO: this is hacky, and makes the view depend on this cell attribute and widget manager behavior
302 // TODO: this is hacky, and makes the view depend on this cell attribute and widget manager behavior
289 // it would be great to have the widget manager add the cell metadata
303 // it would be great to have the widget manager add the cell metadata
290 // to the subview without having to add it here.
304 // to the subview without having to add it here.
291 var child_view = this.model.widget_manager.create_view(child_model, options || {}, this);
305 var child_view = this.model.widget_manager.create_view(child_model, options || {}, this);
292 this.child_views[child_model.id] = child_view;
306 this.child_views[child_model.id] = child_view;
293 return child_view;
307 return child_view;
294 },
308 },
295
309
296 delete_child_view: function(child_model, options) {
310 delete_child_view: function(child_model, options) {
297 // Delete a child view that was previously created using create_child_view.
311 // Delete a child view that was previously created using create_child_view.
298 var view = this.child_views[child_model.id];
312 var view = this.child_views[child_model.id];
299 if (view !== undefined) {
313 if (view !== undefined) {
300 delete this.child_views[child_model.id];
314 delete this.child_views[child_model.id];
301 view.remove();
315 view.remove();
302 }
316 }
303 },
317 },
304
318
305 do_diff: function(old_list, new_list, removed_callback, added_callback) {
319 do_diff: function(old_list, new_list, removed_callback, added_callback) {
306 // Difference a changed list and call remove and add callbacks for
320 // Difference a changed list and call remove and add callbacks for
307 // each removed and added item in the new list.
321 // each removed and added item in the new list.
308 //
322 //
309 // Parameters
323 // Parameters
310 // ----------
324 // ----------
311 // old_list : array
325 // old_list : array
312 // new_list : array
326 // new_list : array
313 // removed_callback : Callback(item)
327 // removed_callback : Callback(item)
314 // Callback that is called for each item removed.
328 // Callback that is called for each item removed.
315 // added_callback : Callback(item)
329 // added_callback : Callback(item)
316 // Callback that is called for each item added.
330 // Callback that is called for each item added.
317
331
318
332
319 // removed items
333 // removed items
320 _.each(_.difference(old_list, new_list), function(item, index, list) {
334 _.each(_.difference(old_list, new_list), function(item, index, list) {
321 removed_callback(item);
335 removed_callback(item);
322 }, this);
336 }, this);
323
337
324 // added items
338 // added items
325 _.each(_.difference(new_list, old_list), function(item, index, list) {
339 _.each(_.difference(new_list, old_list), function(item, index, list) {
326 added_callback(item);
340 added_callback(item);
327 }, this);
341 }, this);
328 },
342 },
329
343
330 callbacks: function(){
344 callbacks: function(){
331 // Create msg callbacks for a comm msg.
345 // Create msg callbacks for a comm msg.
332 return this.model.callbacks(this);
346 return this.model.callbacks(this);
333 },
347 },
334
348
335 render: function(){
349 render: function(){
336 // Render the view.
350 // Render the view.
337 //
351 //
338 // By default, this is only called the first time the view is created
352 // By default, this is only called the first time the view is created
339 },
353 },
340
354
341 send: function (content) {
355 send: function (content) {
342 // Send a custom msg associated with this view.
356 // Send a custom msg associated with this view.
343 this.model.send(content, this.callbacks());
357 this.model.send(content, this.callbacks());
344 },
358 },
345
359
346 touch: function () {
360 touch: function () {
347 this.model.save_changes(this.callbacks());
361 this.model.save_changes(this.callbacks());
348 },
362 },
349 });
363 });
350
364
351
365
352 var DOMWidgetView = WidgetView.extend({
366 var DOMWidgetView = WidgetView.extend({
353 initialize: function (options) {
367 initialize: function (options) {
354 // Public constructor
368 // Public constructor
355
369
356 // In the future we may want to make changes more granular
370 // In the future we may want to make changes more granular
357 // (e.g., trigger on visible:change).
371 // (e.g., trigger on visible:change).
358 this.model.on('change', this.update, this);
372 this.model.on('change', this.update, this);
359 this.model.on('msg:custom', this.on_msg, this);
373 this.model.on('msg:custom', this.on_msg, this);
360 DOMWidgetView.__super__.initialize.apply(this, arguments);
374 DOMWidgetView.__super__.initialize.apply(this, arguments);
361 },
375 },
362
376
363 on_msg: function(msg) {
377 on_msg: function(msg) {
364 // Handle DOM specific msgs.
378 // Handle DOM specific msgs.
365 switch(msg.msg_type) {
379 switch(msg.msg_type) {
366 case 'add_class':
380 case 'add_class':
367 this.add_class(msg.selector, msg.class_list);
381 this.add_class(msg.selector, msg.class_list);
368 break;
382 break;
369 case 'remove_class':
383 case 'remove_class':
370 this.remove_class(msg.selector, msg.class_list);
384 this.remove_class(msg.selector, msg.class_list);
371 break;
385 break;
372 }
386 }
373 },
387 },
374
388
375 add_class: function (selector, class_list) {
389 add_class: function (selector, class_list) {
376 // Add a DOM class to an element.
390 // Add a DOM class to an element.
377 this._get_selector_element(selector).addClass(class_list);
391 this._get_selector_element(selector).addClass(class_list);
378 },
392 },
379
393
380 remove_class: function (selector, class_list) {
394 remove_class: function (selector, class_list) {
381 // Remove a DOM class from an element.
395 // Remove a DOM class from an element.
382 this._get_selector_element(selector).removeClass(class_list);
396 this._get_selector_element(selector).removeClass(class_list);
383 },
397 },
384
398
385 update: function () {
399 update: function () {
386 // Update the contents of this view
400 // Update the contents of this view
387 //
401 //
388 // Called when the model is changed. The model may have been
402 // Called when the model is changed. The model may have been
389 // changed by another view or by a state update from the back-end.
403 // changed by another view or by a state update from the back-end.
390 // The very first update seems to happen before the element is
404 // The very first update seems to happen before the element is
391 // finished rendering so we use setTimeout to give the element time
405 // finished rendering so we use setTimeout to give the element time
392 // to render
406 // to render
393 var e = this.$el;
407 var e = this.$el;
394 var visible = this.model.get('visible');
408 var visible = this.model.get('visible');
395 setTimeout(function() {e.toggle(visible);},0);
409 setTimeout(function() {e.toggle(visible);},0);
396
410
397 var css = this.model.get('_css');
411 var css = this.model.get('_css');
398 if (css === undefined) {return;}
412 if (css === undefined) {return;}
399 var that = this;
413 var that = this;
400 _.each(css, function(css_traits, selector){
414 _.each(css, function(css_traits, selector){
401 // Apply the css traits to all elements that match the selector.
415 // Apply the css traits to all elements that match the selector.
402 var elements = that._get_selector_element(selector);
416 var elements = that._get_selector_element(selector);
403 if (elements.length > 0) {
417 if (elements.length > 0) {
404 _.each(css_traits, function(css_value, css_key){
418 _.each(css_traits, function(css_value, css_key){
405 elements.css(css_key, css_value);
419 elements.css(css_key, css_value);
406 });
420 });
407 }
421 }
408 });
422 });
409 },
423 },
410
424
411 _get_selector_element: function (selector) {
425 _get_selector_element: function (selector) {
412 // Get the elements via the css selector.
426 // Get the elements via the css selector.
413
427
414 // If the selector is blank, apply the style to the $el_to_style
428 // If the selector is blank, apply the style to the $el_to_style
415 // element. If the $el_to_style element is not defined, use apply
429 // element. If the $el_to_style element is not defined, use apply
416 // the style to the view's element.
430 // the style to the view's element.
417 var elements;
431 var elements;
418 if (!selector) {
432 if (!selector) {
419 if (this.$el_to_style === undefined) {
433 if (this.$el_to_style === undefined) {
420 elements = this.$el;
434 elements = this.$el;
421 } else {
435 } else {
422 elements = this.$el_to_style;
436 elements = this.$el_to_style;
423 }
437 }
424 } else {
438 } else {
425 elements = this.$el.find(selector);
439 elements = this.$el.find(selector);
426 }
440 }
427 return elements;
441 return elements;
428 },
442 },
429 });
443 });
430
444
431 IPython.WidgetModel = WidgetModel;
445 IPython.WidgetModel = WidgetModel;
432 IPython.WidgetView = WidgetView;
446 IPython.WidgetView = WidgetView;
433 IPython.DOMWidgetView = DOMWidgetView;
447 IPython.DOMWidgetView = DOMWidgetView;
434
448
435 // Pass through WidgetManager namespace.
449 // Pass through WidgetManager namespace.
436 return WidgetManager;
450 return WidgetManager;
437 });
451 });
@@ -1,134 +1,182 b''
1 var xor = function (a, b) {return !a ^ !b;};
1 var xor = function (a, b) {return !a ^ !b;};
2 var isArray = function (a) {return toString.call(a) === "[object Array]" || toString.call(a) === "[object RuntimeArray]";};
2 var isArray = function (a) {return toString.call(a) === "[object Array]" || toString.call(a) === "[object RuntimeArray]";};
3 var recursive_compare = function(a, b) {
3 var recursive_compare = function(a, b) {
4 // Recursively compare two objects.
4 // Recursively compare two objects.
5 var same = true;
5 var same = true;
6 same = same && !xor(a instanceof Object, b instanceof Object);
6 same = same && !xor(a instanceof Object, b instanceof Object);
7 same = same && !xor(isArray(a), isArray(b));
7 same = same && !xor(isArray(a), isArray(b));
8
8
9 if (same) {
9 if (same) {
10 if (a instanceof Object) {
10 if (a instanceof Object) {
11 for (var key in a) {
11 var key;
12 for (key in a) {
12 if (a.hasOwnProperty(key) && !recursive_compare(a[key], b[key])) {
13 if (a.hasOwnProperty(key) && !recursive_compare(a[key], b[key])) {
13 same = false;
14 same = false;
14 break;
15 break;
15 }
16 }
16 }
17 }
17 for (var key in b) {
18 for (key in b) {
18 if (b.hasOwnProperty(key) && !recursive_compare(a[key], b[key])) {
19 if (b.hasOwnProperty(key) && !recursive_compare(a[key], b[key])) {
19 same = false;
20 same = false;
20 break;
21 break;
21 }
22 }
22 }
23 }
23 } else {
24 } else {
24 return a === b;
25 return a === b;
25 }
26 }
26 }
27 }
27
28
28 return same;
29 return same;
29 }
30 };
30
31
31 // Test the widget framework.
32 // Test the widget framework.
32 casper.notebook_test(function () {
33 casper.notebook_test(function () {
33 var index;
34 var index;
34
35
35 this.then(function () {
36 this.then(function () {
36
37
37 // Check if the WidgetManager class is defined.
38 // Check if the WidgetManager class is defined.
38 this.test.assert(this.evaluate(function() {
39 this.test.assert(this.evaluate(function() {
39 return IPython.WidgetManager !== undefined;
40 return IPython.WidgetManager !== undefined;
40 }), 'WidgetManager class is defined');
41 }), 'WidgetManager class is defined');
41 });
42 });
42
43
43 index = this.append_cell(
44 index = this.append_cell(
44 'from IPython.html import widgets\n' +
45 'from IPython.html import widgets\n' +
45 'from IPython.display import display, clear_output\n' +
46 'from IPython.display import display, clear_output\n' +
46 'print("Success")');
47 'print("Success")');
47 this.execute_cell_then(index);
48 this.execute_cell_then(index);
48
49
49 this.then(function () {
50 this.then(function () {
50 // Check if the widget manager has been instantiated.
51 // Check if the widget manager has been instantiated.
51 this.test.assert(this.evaluate(function() {
52 this.test.assert(this.evaluate(function() {
52 return IPython.notebook.kernel.widget_manager !== undefined;
53 return IPython.notebook.kernel.widget_manager !== undefined;
53 }), 'Notebook widget manager instantiated');
54 }), 'Notebook widget manager instantiated');
54
55
55 // Functions that can be used to test the packing and unpacking APIs
56 // Functions that can be used to test the packing and unpacking APIs
56 var that = this;
57 var that = this;
57 var test_pack = function (input) {
58 var test_pack = function (input) {
58 var output = that.evaluate(function(input) {
59 var output = that.evaluate(function(input) {
59 var model = new IPython.WidgetModel(IPython.notebook.kernel.widget_manager, undefined);
60 var model = new IPython.WidgetModel(IPython.notebook.kernel.widget_manager, undefined);
60 var results = model._pack_models(input);
61 var results = model._pack_models(input);
61 delete model;
62 return results;
62 return results;
63 }, {input: input});
63 }, {input: input});
64 that.test.assert(recursive_compare(input, output),
64 that.test.assert(recursive_compare(input, output),
65 JSON.stringify(input) + ' passed through Model._pack_model unchanged');
65 JSON.stringify(input) + ' passed through Model._pack_model unchanged');
66 };
66 };
67 var test_unpack = function (input) {
67 var test_unpack = function (input) {
68 var output = that.evaluate(function(input) {
68 var output = that.evaluate(function(input) {
69 var model = new IPython.WidgetModel(IPython.notebook.kernel.widget_manager, undefined);
69 var model = new IPython.WidgetModel(IPython.notebook.kernel.widget_manager, undefined);
70 var results = model._unpack_models(input);
70 var results = model._unpack_models(input);
71 delete model;
72 return results;
71 return results;
73 }, {input: input});
72 }, {input: input});
74 that.test.assert(recursive_compare(input, output),
73 that.test.assert(recursive_compare(input, output),
75 JSON.stringify(input) + ' passed through Model._unpack_model unchanged');
74 JSON.stringify(input) + ' passed through Model._unpack_model unchanged');
76 };
75 };
77 var test_packing = function(input) {
76 var test_packing = function(input) {
78 test_pack(input);
77 test_pack(input);
79 test_unpack(input);
78 test_unpack(input);
80 };
79 };
81
80
82 test_packing({0: 'hi', 1: 'bye'})
81 test_packing({0: 'hi', 1: 'bye'});
83 test_packing(['hi', 'bye'])
82 test_packing(['hi', 'bye']);
84 test_packing(['hi', 5])
83 test_packing(['hi', 5]);
85 test_packing(['hi', '5'])
84 test_packing(['hi', '5']);
86 test_packing([1.0, 0])
85 test_packing([1.0, 0]);
87 test_packing([1.0, false])
86 test_packing([1.0, false]);
88 test_packing([1, false])
87 test_packing([1, false]);
89 test_packing([1, false, {a: 'hi'}])
88 test_packing([1, false, {a: 'hi'}]);
90 test_packing([1, false, ['hi']])
89 test_packing([1, false, ['hi']]);
90
91 // Test multi-set, single touch code. First create a custom widget.
92 this.evaluate(function() {
93 var MultiSetView = IPython.DOMWidgetView.extend({
94 render: function(){
95 this.model.set('a', 1);
96 this.model.set('b', 2);
97 this.model.set('c', 3);
98 this.touch();
99 },
100 });
101 IPython.WidgetManager.register_widget_view('MultiSetView', MultiSetView);
102 }, {});
103 });
104
105 // Try creating the multiset widget, verify that sets the values correctly.
106 var multiset = {};
107 multiset.index = this.append_cell(
108 'from IPython.utils.traitlets import Unicode, CInt\n' +
109 'class MultiSetWidget(widgets.Widget):\n' +
110 ' _view_name = Unicode("MultiSetView", sync=True)\n' +
111 ' a = CInt(0, sync=True)\n' +
112 ' b = CInt(0, sync=True)\n' +
113 ' c = CInt(0, sync=True)\n' +
114 ' d = CInt(-1, sync=True)\n' + // See if it sends a full state.
115 ' def _handle_receive_state(self, sync_data):\n' +
116 ' widgets.Widget._handle_receive_state(self, sync_data)\n'+
117 ' self.d = len(sync_data)\n' +
118 'multiset = MultiSetWidget()\n' +
119 'display(multiset)\n' +
120 'print(multiset.model_id)');
121 this.execute_cell_then(multiset.index, function(index) {
122 multiset.model_id = this.get_output_cell(index).text.trim();
123 });
124
125 this.wait_for_widget(multiset);
126
127 index = this.append_cell(
128 'print("%d%d%d" % (multiset.a, multiset.b, multiset.c))');
129 this.execute_cell_then(index, function(index) {
130 this.test.assertEquals(this.get_output_cell(index).text.trim(), '123',
131 'Multiple model.set calls and one view.touch update state in back-end.');
132 });
133
134 index = this.append_cell(
135 'print("%d" % (multiset.d))');
136 this.execute_cell_then(index, function(index) {
137 this.test.assertEquals(this.get_output_cell(index).text.trim(), '3',
138 'Multiple model.set calls sent a partial state.');
91 });
139 });
92
140
93 var textbox = {};
141 var textbox = {};
94 throttle_index = this.append_cell(
142 throttle_index = this.append_cell(
95 'import time\n' +
143 'import time\n' +
96 'textbox = widgets.TextWidget()\n' +
144 'textbox = widgets.TextWidget()\n' +
97 'display(textbox)\n' +
145 'display(textbox)\n' +
98 'textbox.add_class("my-throttle-textbox")\n' +
146 'textbox.add_class("my-throttle-textbox")\n' +
99 'def handle_change(name, old, new):\n' +
147 'def handle_change(name, old, new):\n' +
100 ' print(len(new))\n' +
148 ' print(len(new))\n' +
101 ' time.sleep(0.5)\n' +
149 ' time.sleep(0.5)\n' +
102 'textbox.on_trait_change(handle_change, "value")\n' +
150 'textbox.on_trait_change(handle_change, "value")\n' +
103 'print(textbox.model_id)');
151 'print(textbox.model_id)');
104 this.execute_cell_then(throttle_index, function(index){
152 this.execute_cell_then(throttle_index, function(index){
105 textbox.model_id = this.get_output_cell(index).text.trim();
153 textbox.model_id = this.get_output_cell(index).text.trim();
106
154
107 this.test.assert(this.cell_element_exists(index,
155 this.test.assert(this.cell_element_exists(index,
108 '.widget-area .widget-subarea'),
156 '.widget-area .widget-subarea'),
109 'Widget subarea exists.');
157 'Widget subarea exists.');
110
158
111 this.test.assert(this.cell_element_exists(index,
159 this.test.assert(this.cell_element_exists(index,
112 '.my-throttle-textbox'), 'Textbox exists.');
160 '.my-throttle-textbox'), 'Textbox exists.');
113
161
114 // Send 20 characters
162 // Send 20 characters
115 this.sendKeys('.my-throttle-textbox', '....................');
163 this.sendKeys('.my-throttle-textbox', '....................');
116 });
164 });
117
165
118 this.wait_for_widget(textbox);
166 this.wait_for_widget(textbox);
119
167
120 this.then(function () {
168 this.then(function () {
121 var outputs = this.evaluate(function(i) {
169 var outputs = this.evaluate(function(i) {
122 return IPython.notebook.get_cell(i).output_area.outputs;
170 return IPython.notebook.get_cell(i).output_area.outputs;
123 }, {i : throttle_index});
171 }, {i : throttle_index});
124
172
125 // Only 4 outputs should have printed, but because of timing, sometimes
173 // Only 4 outputs should have printed, but because of timing, sometimes
126 // 5 outputs will print. All we need to do is verify num outputs <= 5
174 // 5 outputs will print. All we need to do is verify num outputs <= 5
127 // because that is much less than 20.
175 // because that is much less than 20.
128 this.test.assert(outputs.length <= 5, 'Messages throttled.');
176 this.test.assert(outputs.length <= 5, 'Messages throttled.');
129
177
130 // We also need to verify that the last state sent was correct.
178 // We also need to verify that the last state sent was correct.
131 var last_state = outputs[outputs.length-1].text;
179 var last_state = outputs[outputs.length-1].text;
132 this.test.assertEquals(last_state, "20\n", "Last state sent when throttling.");
180 this.test.assertEquals(last_state, "20\n", "Last state sent when throttling.");
133 });
181 });
134 });
182 });
General Comments 0
You need to be logged in to leave comments. Login now