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