##// END OF EJS Templates
Adding a comment and renaming on_bulk_change to on_change
Sylvain Corlay -
Show More
@@ -1,496 +1,501 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) {
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 this.widget_manager = widget_manager;
24 24 this._buffered_state_diff = {};
25 25 this.pending_msgs = 0;
26 26 this.msg_buffer = null;
27 27 this.state_lock = null;
28 28 this.id = model_id;
29 29 this.views = [];
30 30
31 31 if (comm !== undefined) {
32 32 // Remember comm associated with the model.
33 33 this.comm = comm;
34 34 comm.model = this;
35 35
36 36 // Hook comm messages up to model.
37 37 comm.on_close($.proxy(this._handle_comm_closed, this));
38 38 comm.on_msg($.proxy(this._handle_comm_msg, this));
39 39 }
40 40 return Backbone.Model.apply(this);
41 41 },
42 42
43 43 send: function (content, callbacks) {
44 44 // Send a custom msg over the comm.
45 45 if (this.comm !== undefined) {
46 46 var data = {method: 'custom', content: content};
47 47 this.comm.send(data, callbacks);
48 48 this.pending_msgs++;
49 49 }
50 50 },
51 51
52 52 _handle_comm_closed: function (msg) {
53 53 // Handle when a widget is closed.
54 54 this.trigger('comm:close');
55 55 delete this.comm.model; // Delete ref so GC will collect widget model.
56 56 delete this.comm;
57 57 delete this.model_id; // Delete id from model so widget manager cleans up.
58 58 _.each(this.views, function(view, i) {
59 59 view.remove();
60 60 });
61 61 },
62 62
63 63 _handle_comm_msg: function (msg) {
64 64 // Handle incoming comm msg.
65 65 var method = msg.content.data.method;
66 66 switch (method) {
67 67 case 'update':
68 68 this.apply_update(msg.content.data.state);
69 69 break;
70 70 case 'custom':
71 71 this.trigger('msg:custom', msg.content.data.content);
72 72 break;
73 73 case 'display':
74 74 this.widget_manager.display_view(msg, this);
75 75 break;
76 76 }
77 77 },
78 78
79 79 apply_update: function (state) {
80 80 // Handle when a widget is updated via the python side.
81 81 this.state_lock = state;
82 82 try {
83 83 var that = this;
84 84 WidgetModel.__super__.set.apply(this, [Object.keys(state).reduce(function(obj, key) {
85 85 obj[key] = that._unpack_models(state[key]);
86 86 return obj;
87 87 }, {})]);
88 88 } finally {
89 89 this.state_lock = null;
90 90 }
91 91 },
92 92
93 93 _handle_status: function (msg, callbacks) {
94 94 // Handle status msgs.
95 95
96 96 // execution_state : ('busy', 'idle', 'starting')
97 97 if (this.comm !== undefined) {
98 98 if (msg.content.execution_state ==='idle') {
99 99 // Send buffer if this message caused another message to be
100 100 // throttled.
101 101 if (this.msg_buffer !== null &&
102 102 (this.get('msg_throttle') || 3) === this.pending_msgs) {
103 103 var data = {method: 'backbone', sync_method: 'update', sync_data: this.msg_buffer};
104 104 this.comm.send(data, callbacks);
105 105 this.msg_buffer = null;
106 106 } else {
107 107 --this.pending_msgs;
108 108 }
109 109 }
110 110 }
111 111 },
112 112
113 113 callbacks: function(view) {
114 114 // Create msg callbacks for a comm msg.
115 115 var callbacks = this.widget_manager.callbacks(view);
116 116
117 117 if (callbacks.iopub === undefined) {
118 118 callbacks.iopub = {};
119 119 }
120 120
121 121 var that = this;
122 122 callbacks.iopub.status = function (msg) {
123 123 that._handle_status(msg, callbacks);
124 124 };
125 125 return callbacks;
126 126 },
127 127
128 128 set: function(key, val, options) {
129 129 // Set a value.
130 130 var return_value = WidgetModel.__super__.set.apply(this, arguments);
131 131
132 132 // Backbone only remembers the diff of the most recent set()
133 133 // operation. Calling set multiple times in a row results in a
134 134 // loss of diff information. Here we keep our own running diff.
135 135 this._buffered_state_diff = $.extend(this._buffered_state_diff, this.changedAttributes() || {});
136 136 return return_value;
137 137 },
138 138
139 139 sync: function (method, model, options) {
140 140 // Handle sync to the back-end. Called when a model.save() is called.
141 141
142 142 // Make sure a comm exists.
143 143 var error = options.error || function() {
144 144 console.error('Backbone sync error:', arguments);
145 145 };
146 146 if (this.comm === undefined) {
147 147 error();
148 148 return false;
149 149 }
150 150
151 151 // Delete any key value pairs that the back-end already knows about.
152 152 var attrs = (method === 'patch') ? options.attrs : model.toJSON(options);
153 153 if (this.state_lock !== null) {
154 154 var keys = Object.keys(this.state_lock);
155 155 for (var i=0; i<keys.length; i++)
156 156 var key = keys[i];
157 157 if (attrs[key] === this.state_lock[key]) {
158 158 delete attrs[key];
159 159 }
160 160 }
161 161
162 162 // Only sync if there are attributes to send to the back-end.
163 163 attrs = this._pack_models(attrs);
164 164 if (_.size(attrs) > 0) {
165 165
166 166 // If this message was sent via backbone itself, it will not
167 167 // have any callbacks. It's important that we create callbacks
168 168 // so we can listen for status messages, etc...
169 169 var callbacks = options.callbacks || this.callbacks();
170 170
171 171 // Check throttle.
172 172 if (this.pending_msgs >= (this.get('msg_throttle') || 3)) {
173 173 // The throttle has been exceeded, buffer the current msg so
174 174 // it can be sent once the kernel has finished processing
175 175 // some of the existing messages.
176 176
177 177 // Combine updates if it is a 'patch' sync, otherwise replace updates
178 178 switch (method) {
179 179 case 'patch':
180 180 this.msg_buffer = $.extend(this.msg_buffer || {}, attrs);
181 181 break;
182 182 case 'update':
183 183 case 'create':
184 184 this.msg_buffer = attrs;
185 185 break;
186 186 default:
187 187 error();
188 188 return false;
189 189 }
190 190 this.msg_buffer_callbacks = callbacks;
191 191
192 192 } else {
193 193 // We haven't exceeded the throttle, send the message like
194 194 // normal.
195 195 var data = {method: 'backbone', sync_data: attrs};
196 196 this.comm.send(data, callbacks);
197 197 this.pending_msgs++;
198 198 }
199 199 }
200 200 // Since the comm is a one-way communication, assume the message
201 201 // arrived. Don't call success since we don't have a model back from the server
202 202 // this means we miss out on the 'sync' event.
203 203 this._buffered_state_diff = {};
204 204 },
205 205
206 206 save_changes: function(callbacks) {
207 207 // Push this model's state to the back-end
208 208 //
209 209 // This invokes a Backbone.Sync.
210 210 this.save(this._buffered_state_diff, {patch: true, callbacks: callbacks});
211 211 },
212 212
213 213 _pack_models: function(value) {
214 214 // Replace models with model ids recursively.
215 215 var that = this;
216 216 var packed;
217 217 if (value instanceof Backbone.Model) {
218 218 return "IPY_MODEL_" + value.id;
219 219
220 220 } else if ($.isArray(value)) {
221 221 packed = [];
222 222 _.each(value, function(sub_value, key) {
223 223 packed.push(that._pack_models(sub_value));
224 224 });
225 225 return packed;
226 226
227 227 } else if (value instanceof Object) {
228 228 packed = {};
229 229 _.each(value, function(sub_value, key) {
230 230 packed[key] = that._pack_models(sub_value);
231 231 });
232 232 return packed;
233 233
234 234 } else {
235 235 return value;
236 236 }
237 237 },
238 238
239 239 _unpack_models: function(value) {
240 240 // Replace model ids with models recursively.
241 241 var that = this;
242 242 var unpacked;
243 243 if ($.isArray(value)) {
244 244 unpacked = [];
245 245 _.each(value, function(sub_value, key) {
246 246 unpacked.push(that._unpack_models(sub_value));
247 247 });
248 248 return unpacked;
249 249
250 250 } else if (value instanceof Object) {
251 251 unpacked = {};
252 252 _.each(value, function(sub_value, key) {
253 253 unpacked[key] = that._unpack_models(sub_value);
254 254 });
255 255 return unpacked;
256 256
257 257 } else if (typeof value === 'string' && value.slice(0,10) === "IPY_MODEL_") {
258 258 var model = this.widget_manager.get_model(value.slice(10, value.length));
259 259 if (model) {
260 260 return model;
261 261 } else {
262 262 return value;
263 263 }
264 264 } else {
265 265 return value;
266 266 }
267 267 },
268 268
269 on_bulk_change: function(keys, callback, context) {
269 on_change: function(keys, callback, context) {
270 // on_change(["key1", "key2"], foo, context) differs from
271 // on("change:key1 change:key2", foo, context).
272 // If the widget attributes key1 and key2 are both modified,
273 // the second form will result in foo being called twice
274 // while the first will call foo only once.
270 275 this.on('change', function() {
271 276 if (keys.some(this.hasChanged, this)) {
272 277 callback.apply(context);
273 278 }
274 279 }, this);
275 280
276 281 },
277 282 });
278 283 widgetmanager.WidgetManager.register_widget_model('WidgetModel', WidgetModel);
279 284
280 285
281 286 var WidgetView = Backbone.View.extend({
282 287 initialize: function(parameters) {
283 288 // Public constructor.
284 289 this.model.on('change',this.update,this);
285 290 this.options = parameters.options;
286 291 this.child_model_views = {};
287 292 this.child_views = {};
288 293 this.model.views.push(this);
289 294 this.id = this.id || IPython.utils.uuid();
290 295 this.on('displayed', function() {
291 296 this.is_displayed = true;
292 297 }, this);
293 298 },
294 299
295 300 update: function(){
296 301 // Triggered on model change.
297 302 //
298 303 // Update view to be consistent with this.model
299 304 },
300 305
301 306 create_child_view: function(child_model, options) {
302 307 // Create and return a child view.
303 308 //
304 309 // -given a model and (optionally) a view name if the view name is
305 310 // not given, it defaults to the model's default view attribute.
306 311
307 312 // TODO: this is hacky, and makes the view depend on this cell attribute and widget manager behavior
308 313 // it would be great to have the widget manager add the cell metadata
309 314 // to the subview without having to add it here.
310 315 options = $.extend({ parent: this }, options || {});
311 316 var child_view = this.model.widget_manager.create_view(child_model, options, this);
312 317
313 318 // Associate the view id with the model id.
314 319 if (this.child_model_views[child_model.id] === undefined) {
315 320 this.child_model_views[child_model.id] = [];
316 321 }
317 322 this.child_model_views[child_model.id].push(child_view.id);
318 323
319 324 // Remember the view by id.
320 325 this.child_views[child_view.id] = child_view;
321 326 return child_view;
322 327 },
323 328
324 329 pop_child_view: function(child_model) {
325 330 // Delete a child view that was previously created using create_child_view.
326 331 var view_ids = this.child_model_views[child_model.id];
327 332 if (view_ids !== undefined) {
328 333
329 334 // Only delete the first view in the list.
330 335 var view_id = view_ids[0];
331 336 var view = this.child_views[view_id];
332 337 delete this.child_views[view_id];
333 338 view_ids.splice(0,1);
334 339 child_model.views.pop(view);
335 340
336 341 // Remove the view list specific to this model if it is empty.
337 342 if (view_ids.length === 0) {
338 343 delete this.child_model_views[child_model.id];
339 344 }
340 345 return view;
341 346 }
342 347 return null;
343 348 },
344 349
345 350 do_diff: function(old_list, new_list, removed_callback, added_callback) {
346 351 // Difference a changed list and call remove and add callbacks for
347 352 // each removed and added item in the new list.
348 353 //
349 354 // Parameters
350 355 // ----------
351 356 // old_list : array
352 357 // new_list : array
353 358 // removed_callback : Callback(item)
354 359 // Callback that is called for each item removed.
355 360 // added_callback : Callback(item)
356 361 // Callback that is called for each item added.
357 362
358 363 // Walk the lists until an unequal entry is found.
359 364 var i;
360 365 for (i = 0; i < new_list.length; i++) {
361 366 if (i >= old_list.length || new_list[i] !== old_list[i]) {
362 367 break;
363 368 }
364 369 }
365 370
366 371 // Remove the non-matching items from the old list.
367 372 for (var j = i; j < old_list.length; j++) {
368 373 removed_callback(old_list[j]);
369 374 }
370 375
371 376 // Add the rest of the new list items.
372 377 for (; i < new_list.length; i++) {
373 378 added_callback(new_list[i]);
374 379 }
375 380 },
376 381
377 382 callbacks: function(){
378 383 // Create msg callbacks for a comm msg.
379 384 return this.model.callbacks(this);
380 385 },
381 386
382 387 render: function(){
383 388 // Render the view.
384 389 //
385 390 // By default, this is only called the first time the view is created
386 391 },
387 392
388 393 show: function(){
389 394 // Show the widget-area
390 395 if (this.options && this.options.cell &&
391 396 this.options.cell.widget_area !== undefined) {
392 397 this.options.cell.widget_area.show();
393 398 }
394 399 },
395 400
396 401 send: function (content) {
397 402 // Send a custom msg associated with this view.
398 403 this.model.send(content, this.callbacks());
399 404 },
400 405
401 406 touch: function () {
402 407 this.model.save_changes(this.callbacks());
403 408 },
404 409
405 410 after_displayed: function (callback, context) {
406 411 // Calls the callback right away is the view is already displayed
407 412 // otherwise, register the callback to the 'displayed' event.
408 413 if (this.is_displayed) {
409 414 callback.apply(context);
410 415 } else {
411 416 this.on('displayed', callback, context);
412 417 }
413 418 },
414 419 });
415 420
416 421
417 422 var DOMWidgetView = WidgetView.extend({
418 423 initialize: function (parameters) {
419 424 // Public constructor
420 425 DOMWidgetView.__super__.initialize.apply(this, [parameters]);
421 426 this.on('displayed', this.show, this);
422 427 this.after_displayed(function() {
423 428 this.update_visible(this.model, this.model.get("visible"));
424 429 this.update_css(this.model, this.model.get("_css"));
425 430 }, this);
426 431 this.model.on('msg:custom', this.on_msg, this);
427 432 this.model.on('change:visible', this.update_visible, this);
428 433 this.model.on('change:_css', this.update_css, this);
429 434 },
430 435
431 436 on_msg: function(msg) {
432 437 // Handle DOM specific msgs.
433 438 switch(msg.msg_type) {
434 439 case 'add_class':
435 440 this.add_class(msg.selector, msg.class_list);
436 441 break;
437 442 case 'remove_class':
438 443 this.remove_class(msg.selector, msg.class_list);
439 444 break;
440 445 }
441 446 },
442 447
443 448 add_class: function (selector, class_list) {
444 449 // Add a DOM class to an element.
445 450 this._get_selector_element(selector).addClass(class_list);
446 451 },
447 452
448 453 remove_class: function (selector, class_list) {
449 454 // Remove a DOM class from an element.
450 455 this._get_selector_element(selector).removeClass(class_list);
451 456 },
452 457
453 458 update_visible: function(model, value) {
454 459 // Update visibility
455 460 this.$el.toggle(value);
456 461 },
457 462
458 463 update_css: function (model, css) {
459 464 // Update the css styling of this view.
460 465 var e = this.$el;
461 466 if (css === undefined) {return;}
462 467 for (var i = 0; i < css.length; i++) {
463 468 // Apply the css traits to all elements that match the selector.
464 469 var selector = css[i][0];
465 470 var elements = this._get_selector_element(selector);
466 471 if (elements.length > 0) {
467 472 var trait_key = css[i][1];
468 473 var trait_value = css[i][2];
469 474 elements.css(trait_key ,trait_value);
470 475 }
471 476 }
472 477 },
473 478
474 479 _get_selector_element: function (selector) {
475 480 // Get the elements via the css selector.
476 481 var elements;
477 482 if (!selector) {
478 483 elements = this.$el;
479 484 } else {
480 485 elements = this.$el.find(selector).addBack(selector);
481 486 }
482 487 return elements;
483 488 },
484 489 });
485 490
486 491 var widget = {
487 492 'WidgetModel': WidgetModel,
488 493 'WidgetView': WidgetView,
489 494 'DOMWidgetView': DOMWidgetView,
490 495 };
491 496
492 497 // For backwards compatability.
493 498 $.extend(IPython, widget);
494 499
495 500 return widget;
496 501 });
General Comments 0
You need to be logged in to leave comments. Login now