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