##// END OF EJS Templates
Merge pull request #7801 from jasongrout/display-state-change...
Jonathan Frederic -
r20469:92333e10 merge
parent child Browse files
Show More
@@ -1,762 +1,763 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/utils",
8 "base/js/utils",
9 "base/js/namespace",
9 "base/js/namespace",
10 ], function(widgetmanager, _, Backbone, $, utils, IPython){
10 ], function(widgetmanager, _, Backbone, $, utils, IPython){
11 "use strict";
11 "use strict";
12
12
13 var WidgetModel = Backbone.Model.extend({
13 var WidgetModel = Backbone.Model.extend({
14 constructor: function (widget_manager, model_id, comm) {
14 constructor: function (widget_manager, model_id, comm) {
15 /**
15 /**
16 * Constructor
16 * Constructor
17 *
17 *
18 * Creates a WidgetModel instance.
18 * Creates a WidgetModel instance.
19 *
19 *
20 * Parameters
20 * Parameters
21 * ----------
21 * ----------
22 * widget_manager : WidgetManager instance
22 * widget_manager : WidgetManager instance
23 * model_id : string
23 * model_id : string
24 * An ID unique to this model.
24 * An ID unique to this model.
25 * comm : Comm instance (optional)
25 * comm : Comm instance (optional)
26 */
26 */
27 this.widget_manager = widget_manager;
27 this.widget_manager = widget_manager;
28 this.state_change = Promise.resolve();
28 this.state_change = Promise.resolve();
29 this._buffered_state_diff = {};
29 this._buffered_state_diff = {};
30 this.pending_msgs = 0;
30 this.pending_msgs = 0;
31 this.msg_buffer = null;
31 this.msg_buffer = null;
32 this.state_lock = null;
32 this.state_lock = null;
33 this.id = model_id;
33 this.id = model_id;
34 this.views = {};
34 this.views = {};
35 this._resolve_received_state = {};
35 this._resolve_received_state = {};
36
36
37 if (comm !== undefined) {
37 if (comm !== undefined) {
38 // Remember comm associated with the model.
38 // Remember comm associated with the model.
39 this.comm = comm;
39 this.comm = comm;
40 comm.model = this;
40 comm.model = this;
41
41
42 // Hook comm messages up to model.
42 // Hook comm messages up to model.
43 comm.on_close($.proxy(this._handle_comm_closed, this));
43 comm.on_close($.proxy(this._handle_comm_closed, this));
44 comm.on_msg($.proxy(this._handle_comm_msg, this));
44 comm.on_msg($.proxy(this._handle_comm_msg, this));
45
45
46 // Assume the comm is alive.
46 // Assume the comm is alive.
47 this.set_comm_live(true);
47 this.set_comm_live(true);
48 } else {
48 } else {
49 this.set_comm_live(false);
49 this.set_comm_live(false);
50 }
50 }
51
51
52 // Listen for the events that lead to the websocket being terminated.
52 // Listen for the events that lead to the websocket being terminated.
53 var that = this;
53 var that = this;
54 var died = function() {
54 var died = function() {
55 that.set_comm_live(false);
55 that.set_comm_live(false);
56 };
56 };
57 widget_manager.notebook.events.on('kernel_disconnected.Kernel', died);
57 widget_manager.notebook.events.on('kernel_disconnected.Kernel', died);
58 widget_manager.notebook.events.on('kernel_killed.Kernel', died);
58 widget_manager.notebook.events.on('kernel_killed.Kernel', died);
59 widget_manager.notebook.events.on('kernel_restarting.Kernel', died);
59 widget_manager.notebook.events.on('kernel_restarting.Kernel', died);
60 widget_manager.notebook.events.on('kernel_dead.Kernel', died);
60 widget_manager.notebook.events.on('kernel_dead.Kernel', died);
61
61
62 return Backbone.Model.apply(this);
62 return Backbone.Model.apply(this);
63 },
63 },
64
64
65 send: function (content, callbacks) {
65 send: function (content, callbacks) {
66 /**
66 /**
67 * Send a custom msg over the comm.
67 * Send a custom msg over the comm.
68 */
68 */
69 if (this.comm !== undefined) {
69 if (this.comm !== undefined) {
70 var data = {method: 'custom', content: content};
70 var data = {method: 'custom', content: content};
71 this.comm.send(data, callbacks);
71 this.comm.send(data, callbacks);
72 this.pending_msgs++;
72 this.pending_msgs++;
73 }
73 }
74 },
74 },
75
75
76 request_state: function(callbacks) {
76 request_state: function(callbacks) {
77 /**
77 /**
78 * Request a state push from the back-end.
78 * Request a state push from the back-end.
79 */
79 */
80 if (!this.comm) {
80 if (!this.comm) {
81 console.error("Could not request_state because comm doesn't exist!");
81 console.error("Could not request_state because comm doesn't exist!");
82 return;
82 return;
83 }
83 }
84
84
85 var msg_id = this.comm.send({method: 'request_state'}, callbacks || this.widget_manager.callbacks());
85 var msg_id = this.comm.send({method: 'request_state'}, callbacks || this.widget_manager.callbacks());
86
86
87 // Promise that is resolved when a state is received
87 // Promise that is resolved when a state is received
88 // from the back-end.
88 // from the back-end.
89 var that = this;
89 var that = this;
90 var received_state = new Promise(function(resolve) {
90 var received_state = new Promise(function(resolve) {
91 that._resolve_received_state[msg_id] = resolve;
91 that._resolve_received_state[msg_id] = resolve;
92 });
92 });
93 return received_state;
93 return received_state;
94 },
94 },
95
95
96 set_comm_live: function(live) {
96 set_comm_live: function(live) {
97 /**
97 /**
98 * Change the comm_live state of the model.
98 * Change the comm_live state of the model.
99 */
99 */
100 if (this.comm_live === undefined || this.comm_live != live) {
100 if (this.comm_live === undefined || this.comm_live != live) {
101 this.comm_live = live;
101 this.comm_live = live;
102 this.trigger(live ? 'comm:live' : 'comm:dead', {model: this});
102 this.trigger(live ? 'comm:live' : 'comm:dead', {model: this});
103 }
103 }
104 },
104 },
105
105
106 close: function(comm_closed) {
106 close: function(comm_closed) {
107 /**
107 /**
108 * Close model
108 * Close model
109 */
109 */
110 if (this.comm && !comm_closed) {
110 if (this.comm && !comm_closed) {
111 this.comm.close();
111 this.comm.close();
112 }
112 }
113 this.stopListening();
113 this.stopListening();
114 this.trigger('destroy', this);
114 this.trigger('destroy', this);
115 delete this.comm.model; // Delete ref so GC will collect widget model.
115 delete this.comm.model; // Delete ref so GC will collect widget model.
116 delete this.comm;
116 delete this.comm;
117 delete this.model_id; // Delete id from model so widget manager cleans up.
117 delete this.model_id; // Delete id from model so widget manager cleans up.
118 _.each(this.views, function(v, id, views) {
118 _.each(this.views, function(v, id, views) {
119 v.then(function(view) {
119 v.then(function(view) {
120 view.remove();
120 view.remove();
121 delete views[id];
121 delete views[id];
122 });
122 });
123 });
123 });
124 },
124 },
125
125
126 _handle_comm_closed: function (msg) {
126 _handle_comm_closed: function (msg) {
127 /**
127 /**
128 * Handle when a widget is closed.
128 * Handle when a widget is closed.
129 */
129 */
130 this.trigger('comm:close');
130 this.trigger('comm:close');
131 this.close(true);
131 this.close(true);
132 },
132 },
133
133
134 _handle_comm_msg: function (msg) {
134 _handle_comm_msg: function (msg) {
135 /**
135 /**
136 * Handle incoming comm msg.
136 * Handle incoming comm msg.
137 */
137 */
138 var method = msg.content.data.method;
138 var method = msg.content.data.method;
139 var that = this;
139 var that = this;
140 switch (method) {
140 switch (method) {
141 case 'update':
141 case 'update':
142 this.state_change = this.state_change
142 this.state_change = this.state_change
143 .then(function() {
143 .then(function() {
144 return that.set_state(msg.content.data.state);
144 return that.set_state(msg.content.data.state);
145 }).catch(utils.reject("Couldn't process update msg for model id '" + String(that.id) + "'", true))
145 }).catch(utils.reject("Couldn't process update msg for model id '" + String(that.id) + "'", true))
146 .then(function() {
146 .then(function() {
147 var parent_id = msg.parent_header.msg_id;
147 var parent_id = msg.parent_header.msg_id;
148 if (that._resolve_received_state[parent_id] !== undefined) {
148 if (that._resolve_received_state[parent_id] !== undefined) {
149 that._resolve_received_state[parent_id].call();
149 that._resolve_received_state[parent_id].call();
150 delete that._resolve_received_state[parent_id];
150 delete that._resolve_received_state[parent_id];
151 }
151 }
152 }).catch(utils.reject("Couldn't resolve state request promise", true));
152 }).catch(utils.reject("Couldn't resolve state request promise", true));
153 break;
153 break;
154 case 'custom':
154 case 'custom':
155 this.trigger('msg:custom', msg.content.data.content);
155 this.trigger('msg:custom', msg.content.data.content);
156 break;
156 break;
157 case 'display':
157 case 'display':
158 this.widget_manager.display_view(msg, this)
158 this.state_change = this.state_change.then(function() {
159 .catch(utils.reject('Could not process display view msg', true));
159 that.widget_manager.display_view(msg, that);
160 }).catch(utils.reject('Could not process display view msg', true));
160 break;
161 break;
161 }
162 }
162 },
163 },
163
164
164 set_state: function (state) {
165 set_state: function (state) {
165 var that = this;
166 var that = this;
166 // Handle when a widget is updated via the python side.
167 // Handle when a widget is updated via the python side.
167 return this._unpack_models(state).then(function(state) {
168 return this._unpack_models(state).then(function(state) {
168 that.state_lock = state;
169 that.state_lock = state;
169 try {
170 try {
170 WidgetModel.__super__.set.call(that, state);
171 WidgetModel.__super__.set.call(that, state);
171 } finally {
172 } finally {
172 that.state_lock = null;
173 that.state_lock = null;
173 }
174 }
174 }).catch(utils.reject("Couldn't set model state", true));
175 }).catch(utils.reject("Couldn't set model state", true));
175 },
176 },
176
177
177 get_state: function() {
178 get_state: function() {
178 // Get the serializable state of the model.
179 // Get the serializable state of the model.
179 var state = this.toJSON();
180 var state = this.toJSON();
180 for (var key in state) {
181 for (var key in state) {
181 if (state.hasOwnProperty(key)) {
182 if (state.hasOwnProperty(key)) {
182 state[key] = this._pack_models(state[key]);
183 state[key] = this._pack_models(state[key]);
183 }
184 }
184 }
185 }
185 return state;
186 return state;
186 },
187 },
187
188
188 _handle_status: function (msg, callbacks) {
189 _handle_status: function (msg, callbacks) {
189 /**
190 /**
190 * Handle status msgs.
191 * Handle status msgs.
191 *
192 *
192 * execution_state : ('busy', 'idle', 'starting')
193 * execution_state : ('busy', 'idle', 'starting')
193 */
194 */
194 if (this.comm !== undefined) {
195 if (this.comm !== undefined) {
195 if (msg.content.execution_state ==='idle') {
196 if (msg.content.execution_state ==='idle') {
196 // Send buffer if this message caused another message to be
197 // Send buffer if this message caused another message to be
197 // throttled.
198 // throttled.
198 if (this.msg_buffer !== null &&
199 if (this.msg_buffer !== null &&
199 (this.get('msg_throttle') || 3) === this.pending_msgs) {
200 (this.get('msg_throttle') || 3) === this.pending_msgs) {
200 var data = {method: 'backbone', sync_method: 'update', sync_data: this.msg_buffer};
201 var data = {method: 'backbone', sync_method: 'update', sync_data: this.msg_buffer};
201 this.comm.send(data, callbacks);
202 this.comm.send(data, callbacks);
202 this.msg_buffer = null;
203 this.msg_buffer = null;
203 } else {
204 } else {
204 --this.pending_msgs;
205 --this.pending_msgs;
205 }
206 }
206 }
207 }
207 }
208 }
208 },
209 },
209
210
210 callbacks: function(view) {
211 callbacks: function(view) {
211 /**
212 /**
212 * Create msg callbacks for a comm msg.
213 * Create msg callbacks for a comm msg.
213 */
214 */
214 var callbacks = this.widget_manager.callbacks(view);
215 var callbacks = this.widget_manager.callbacks(view);
215
216
216 if (callbacks.iopub === undefined) {
217 if (callbacks.iopub === undefined) {
217 callbacks.iopub = {};
218 callbacks.iopub = {};
218 }
219 }
219
220
220 var that = this;
221 var that = this;
221 callbacks.iopub.status = function (msg) {
222 callbacks.iopub.status = function (msg) {
222 that._handle_status(msg, callbacks);
223 that._handle_status(msg, callbacks);
223 };
224 };
224 return callbacks;
225 return callbacks;
225 },
226 },
226
227
227 set: function(key, val, options) {
228 set: function(key, val, options) {
228 /**
229 /**
229 * Set a value.
230 * Set a value.
230 */
231 */
231 var return_value = WidgetModel.__super__.set.apply(this, arguments);
232 var return_value = WidgetModel.__super__.set.apply(this, arguments);
232
233
233 // Backbone only remembers the diff of the most recent set()
234 // Backbone only remembers the diff of the most recent set()
234 // operation. Calling set multiple times in a row results in a
235 // operation. Calling set multiple times in a row results in a
235 // loss of diff information. Here we keep our own running diff.
236 // loss of diff information. Here we keep our own running diff.
236 this._buffered_state_diff = $.extend(this._buffered_state_diff, this.changedAttributes() || {});
237 this._buffered_state_diff = $.extend(this._buffered_state_diff, this.changedAttributes() || {});
237 return return_value;
238 return return_value;
238 },
239 },
239
240
240 sync: function (method, model, options) {
241 sync: function (method, model, options) {
241 /**
242 /**
242 * Handle sync to the back-end. Called when a model.save() is called.
243 * Handle sync to the back-end. Called when a model.save() is called.
243 *
244 *
244 * Make sure a comm exists.
245 * Make sure a comm exists.
245 */
246 */
246 var error = options.error || function() {
247 var error = options.error || function() {
247 console.error('Backbone sync error:', arguments);
248 console.error('Backbone sync error:', arguments);
248 };
249 };
249 if (this.comm === undefined) {
250 if (this.comm === undefined) {
250 error();
251 error();
251 return false;
252 return false;
252 }
253 }
253
254
254 // Delete any key value pairs that the back-end already knows about.
255 // Delete any key value pairs that the back-end already knows about.
255 var attrs = (method === 'patch') ? options.attrs : model.toJSON(options);
256 var attrs = (method === 'patch') ? options.attrs : model.toJSON(options);
256 if (this.state_lock !== null) {
257 if (this.state_lock !== null) {
257 var keys = Object.keys(this.state_lock);
258 var keys = Object.keys(this.state_lock);
258 for (var i=0; i<keys.length; i++) {
259 for (var i=0; i<keys.length; i++) {
259 var key = keys[i];
260 var key = keys[i];
260 if (attrs[key] === this.state_lock[key]) {
261 if (attrs[key] === this.state_lock[key]) {
261 delete attrs[key];
262 delete attrs[key];
262 }
263 }
263 }
264 }
264 }
265 }
265
266
266 // Only sync if there are attributes to send to the back-end.
267 // Only sync if there are attributes to send to the back-end.
267 attrs = this._pack_models(attrs);
268 attrs = this._pack_models(attrs);
268 if (_.size(attrs) > 0) {
269 if (_.size(attrs) > 0) {
269
270
270 // If this message was sent via backbone itself, it will not
271 // If this message was sent via backbone itself, it will not
271 // have any callbacks. It's important that we create callbacks
272 // have any callbacks. It's important that we create callbacks
272 // so we can listen for status messages, etc...
273 // so we can listen for status messages, etc...
273 var callbacks = options.callbacks || this.callbacks();
274 var callbacks = options.callbacks || this.callbacks();
274
275
275 // Check throttle.
276 // Check throttle.
276 if (this.pending_msgs >= (this.get('msg_throttle') || 3)) {
277 if (this.pending_msgs >= (this.get('msg_throttle') || 3)) {
277 // The throttle has been exceeded, buffer the current msg so
278 // The throttle has been exceeded, buffer the current msg so
278 // it can be sent once the kernel has finished processing
279 // it can be sent once the kernel has finished processing
279 // some of the existing messages.
280 // some of the existing messages.
280
281
281 // Combine updates if it is a 'patch' sync, otherwise replace updates
282 // Combine updates if it is a 'patch' sync, otherwise replace updates
282 switch (method) {
283 switch (method) {
283 case 'patch':
284 case 'patch':
284 this.msg_buffer = $.extend(this.msg_buffer || {}, attrs);
285 this.msg_buffer = $.extend(this.msg_buffer || {}, attrs);
285 break;
286 break;
286 case 'update':
287 case 'update':
287 case 'create':
288 case 'create':
288 this.msg_buffer = attrs;
289 this.msg_buffer = attrs;
289 break;
290 break;
290 default:
291 default:
291 error();
292 error();
292 return false;
293 return false;
293 }
294 }
294 this.msg_buffer_callbacks = callbacks;
295 this.msg_buffer_callbacks = callbacks;
295
296
296 } else {
297 } else {
297 // We haven't exceeded the throttle, send the message like
298 // We haven't exceeded the throttle, send the message like
298 // normal.
299 // normal.
299 var data = {method: 'backbone', sync_data: attrs};
300 var data = {method: 'backbone', sync_data: attrs};
300 this.comm.send(data, callbacks);
301 this.comm.send(data, callbacks);
301 this.pending_msgs++;
302 this.pending_msgs++;
302 }
303 }
303 }
304 }
304 // Since the comm is a one-way communication, assume the message
305 // Since the comm is a one-way communication, assume the message
305 // arrived. Don't call success since we don't have a model back from the server
306 // arrived. Don't call success since we don't have a model back from the server
306 // this means we miss out on the 'sync' event.
307 // this means we miss out on the 'sync' event.
307 this._buffered_state_diff = {};
308 this._buffered_state_diff = {};
308 },
309 },
309
310
310 save_changes: function(callbacks) {
311 save_changes: function(callbacks) {
311 /**
312 /**
312 * Push this model's state to the back-end
313 * Push this model's state to the back-end
313 *
314 *
314 * This invokes a Backbone.Sync.
315 * This invokes a Backbone.Sync.
315 */
316 */
316 this.save(this._buffered_state_diff, {patch: true, callbacks: callbacks});
317 this.save(this._buffered_state_diff, {patch: true, callbacks: callbacks});
317 },
318 },
318
319
319 _pack_models: function(value) {
320 _pack_models: function(value) {
320 /**
321 /**
321 * Replace models with model ids recursively.
322 * Replace models with model ids recursively.
322 */
323 */
323 var that = this;
324 var that = this;
324 var packed;
325 var packed;
325 if (value instanceof Backbone.Model) {
326 if (value instanceof Backbone.Model) {
326 return "IPY_MODEL_" + value.id;
327 return "IPY_MODEL_" + value.id;
327
328
328 } else if ($.isArray(value)) {
329 } else if ($.isArray(value)) {
329 packed = [];
330 packed = [];
330 _.each(value, function(sub_value, key) {
331 _.each(value, function(sub_value, key) {
331 packed.push(that._pack_models(sub_value));
332 packed.push(that._pack_models(sub_value));
332 });
333 });
333 return packed;
334 return packed;
334 } else if (value instanceof Date || value instanceof String) {
335 } else if (value instanceof Date || value instanceof String) {
335 return value;
336 return value;
336 } else if (value instanceof Object) {
337 } else if (value instanceof Object) {
337 packed = {};
338 packed = {};
338 _.each(value, function(sub_value, key) {
339 _.each(value, function(sub_value, key) {
339 packed[key] = that._pack_models(sub_value);
340 packed[key] = that._pack_models(sub_value);
340 });
341 });
341 return packed;
342 return packed;
342
343
343 } else {
344 } else {
344 return value;
345 return value;
345 }
346 }
346 },
347 },
347
348
348 _unpack_models: function(value) {
349 _unpack_models: function(value) {
349 /**
350 /**
350 * Replace model ids with models recursively.
351 * Replace model ids with models recursively.
351 */
352 */
352 var that = this;
353 var that = this;
353 var unpacked;
354 var unpacked;
354 if ($.isArray(value)) {
355 if ($.isArray(value)) {
355 unpacked = [];
356 unpacked = [];
356 _.each(value, function(sub_value, key) {
357 _.each(value, function(sub_value, key) {
357 unpacked.push(that._unpack_models(sub_value));
358 unpacked.push(that._unpack_models(sub_value));
358 });
359 });
359 return Promise.all(unpacked);
360 return Promise.all(unpacked);
360 } else if (value instanceof Object) {
361 } else if (value instanceof Object) {
361 unpacked = {};
362 unpacked = {};
362 _.each(value, function(sub_value, key) {
363 _.each(value, function(sub_value, key) {
363 unpacked[key] = that._unpack_models(sub_value);
364 unpacked[key] = that._unpack_models(sub_value);
364 });
365 });
365 return utils.resolve_promises_dict(unpacked);
366 return utils.resolve_promises_dict(unpacked);
366 } else if (typeof value === 'string' && value.slice(0,10) === "IPY_MODEL_") {
367 } else if (typeof value === 'string' && value.slice(0,10) === "IPY_MODEL_") {
367 // get_model returns a promise already
368 // get_model returns a promise already
368 return this.widget_manager.get_model(value.slice(10, value.length));
369 return this.widget_manager.get_model(value.slice(10, value.length));
369 } else {
370 } else {
370 return Promise.resolve(value);
371 return Promise.resolve(value);
371 }
372 }
372 },
373 },
373
374
374 on_some_change: function(keys, callback, context) {
375 on_some_change: function(keys, callback, context) {
375 /**
376 /**
376 * on_some_change(["key1", "key2"], foo, context) differs from
377 * on_some_change(["key1", "key2"], foo, context) differs from
377 * on("change:key1 change:key2", foo, context).
378 * on("change:key1 change:key2", foo, context).
378 * If the widget attributes key1 and key2 are both modified,
379 * If the widget attributes key1 and key2 are both modified,
379 * the second form will result in foo being called twice
380 * the second form will result in foo being called twice
380 * while the first will call foo only once.
381 * while the first will call foo only once.
381 */
382 */
382 this.on('change', function() {
383 this.on('change', function() {
383 if (keys.some(this.hasChanged, this)) {
384 if (keys.some(this.hasChanged, this)) {
384 callback.apply(context);
385 callback.apply(context);
385 }
386 }
386 }, this);
387 }, this);
387
388
388 },
389 },
389 });
390 });
390 widgetmanager.WidgetManager.register_widget_model('WidgetModel', WidgetModel);
391 widgetmanager.WidgetManager.register_widget_model('WidgetModel', WidgetModel);
391
392
392
393
393 var WidgetView = Backbone.View.extend({
394 var WidgetView = Backbone.View.extend({
394 initialize: function(parameters) {
395 initialize: function(parameters) {
395 /**
396 /**
396 * Public constructor.
397 * Public constructor.
397 */
398 */
398 this.model.on('change',this.update,this);
399 this.model.on('change',this.update,this);
399
400
400 // Bubble the comm live events.
401 // Bubble the comm live events.
401 this.model.on('comm:live', function() {
402 this.model.on('comm:live', function() {
402 this.trigger('comm:live', this);
403 this.trigger('comm:live', this);
403 }, this);
404 }, this);
404 this.model.on('comm:dead', function() {
405 this.model.on('comm:dead', function() {
405 this.trigger('comm:dead', this);
406 this.trigger('comm:dead', this);
406 }, this);
407 }, this);
407
408
408 this.options = parameters.options;
409 this.options = parameters.options;
409 this.on('displayed', function() {
410 this.on('displayed', function() {
410 this.is_displayed = true;
411 this.is_displayed = true;
411 }, this);
412 }, this);
412 },
413 },
413
414
414 update: function(){
415 update: function(){
415 /**
416 /**
416 * Triggered on model change.
417 * Triggered on model change.
417 *
418 *
418 * Update view to be consistent with this.model
419 * Update view to be consistent with this.model
419 */
420 */
420 },
421 },
421
422
422 create_child_view: function(child_model, options) {
423 create_child_view: function(child_model, options) {
423 /**
424 /**
424 * Create and promise that resolves to a child view of a given model
425 * Create and promise that resolves to a child view of a given model
425 */
426 */
426 var that = this;
427 var that = this;
427 options = $.extend({ parent: this }, options || {});
428 options = $.extend({ parent: this }, options || {});
428 return this.model.widget_manager.create_view(child_model, options).catch(utils.reject("Couldn't create child view"), true);
429 return this.model.widget_manager.create_view(child_model, options).catch(utils.reject("Couldn't create child view"), true);
429 },
430 },
430
431
431 callbacks: function(){
432 callbacks: function(){
432 /**
433 /**
433 * Create msg callbacks for a comm msg.
434 * Create msg callbacks for a comm msg.
434 */
435 */
435 return this.model.callbacks(this);
436 return this.model.callbacks(this);
436 },
437 },
437
438
438 render: function(){
439 render: function(){
439 /**
440 /**
440 * Render the view.
441 * Render the view.
441 *
442 *
442 * By default, this is only called the first time the view is created
443 * By default, this is only called the first time the view is created
443 */
444 */
444 },
445 },
445
446
446 send: function (content) {
447 send: function (content) {
447 /**
448 /**
448 * Send a custom msg associated with this view.
449 * Send a custom msg associated with this view.
449 */
450 */
450 this.model.send(content, this.callbacks());
451 this.model.send(content, this.callbacks());
451 },
452 },
452
453
453 touch: function () {
454 touch: function () {
454 this.model.save_changes(this.callbacks());
455 this.model.save_changes(this.callbacks());
455 },
456 },
456
457
457 after_displayed: function (callback, context) {
458 after_displayed: function (callback, context) {
458 /**
459 /**
459 * Calls the callback right away is the view is already displayed
460 * Calls the callback right away is the view is already displayed
460 * otherwise, register the callback to the 'displayed' event.
461 * otherwise, register the callback to the 'displayed' event.
461 */
462 */
462 if (this.is_displayed) {
463 if (this.is_displayed) {
463 callback.apply(context);
464 callback.apply(context);
464 } else {
465 } else {
465 this.on('displayed', callback, context);
466 this.on('displayed', callback, context);
466 }
467 }
467 },
468 },
468
469
469 remove: function () {
470 remove: function () {
470 // Raise a remove event when the view is removed.
471 // Raise a remove event when the view is removed.
471 WidgetView.__super__.remove.apply(this, arguments);
472 WidgetView.__super__.remove.apply(this, arguments);
472 this.trigger('remove');
473 this.trigger('remove');
473 }
474 }
474 });
475 });
475
476
476
477
477 var DOMWidgetView = WidgetView.extend({
478 var DOMWidgetView = WidgetView.extend({
478 initialize: function (parameters) {
479 initialize: function (parameters) {
479 /**
480 /**
480 * Public constructor
481 * Public constructor
481 */
482 */
482 DOMWidgetView.__super__.initialize.apply(this, [parameters]);
483 DOMWidgetView.__super__.initialize.apply(this, [parameters]);
483 this.model.on('change:visible', this.update_visible, this);
484 this.model.on('change:visible', this.update_visible, this);
484 this.model.on('change:_css', this.update_css, this);
485 this.model.on('change:_css', this.update_css, this);
485
486
486 this.model.on('change:_dom_classes', function(model, new_classes) {
487 this.model.on('change:_dom_classes', function(model, new_classes) {
487 var old_classes = model.previous('_dom_classes');
488 var old_classes = model.previous('_dom_classes');
488 this.update_classes(old_classes, new_classes);
489 this.update_classes(old_classes, new_classes);
489 }, this);
490 }, this);
490
491
491 this.model.on('change:color', function (model, value) {
492 this.model.on('change:color', function (model, value) {
492 this.update_attr('color', value); }, this);
493 this.update_attr('color', value); }, this);
493
494
494 this.model.on('change:background_color', function (model, value) {
495 this.model.on('change:background_color', function (model, value) {
495 this.update_attr('background', value); }, this);
496 this.update_attr('background', value); }, this);
496
497
497 this.model.on('change:width', function (model, value) {
498 this.model.on('change:width', function (model, value) {
498 this.update_attr('width', value); }, this);
499 this.update_attr('width', value); }, this);
499
500
500 this.model.on('change:height', function (model, value) {
501 this.model.on('change:height', function (model, value) {
501 this.update_attr('height', value); }, this);
502 this.update_attr('height', value); }, this);
502
503
503 this.model.on('change:border_color', function (model, value) {
504 this.model.on('change:border_color', function (model, value) {
504 this.update_attr('border-color', value); }, this);
505 this.update_attr('border-color', value); }, this);
505
506
506 this.model.on('change:border_width', function (model, value) {
507 this.model.on('change:border_width', function (model, value) {
507 this.update_attr('border-width', value); }, this);
508 this.update_attr('border-width', value); }, this);
508
509
509 this.model.on('change:border_style', function (model, value) {
510 this.model.on('change:border_style', function (model, value) {
510 this.update_attr('border-style', value); }, this);
511 this.update_attr('border-style', value); }, this);
511
512
512 this.model.on('change:font_style', function (model, value) {
513 this.model.on('change:font_style', function (model, value) {
513 this.update_attr('font-style', value); }, this);
514 this.update_attr('font-style', value); }, this);
514
515
515 this.model.on('change:font_weight', function (model, value) {
516 this.model.on('change:font_weight', function (model, value) {
516 this.update_attr('font-weight', value); }, this);
517 this.update_attr('font-weight', value); }, this);
517
518
518 this.model.on('change:font_size', function (model, value) {
519 this.model.on('change:font_size', function (model, value) {
519 this.update_attr('font-size', this._default_px(value)); }, this);
520 this.update_attr('font-size', this._default_px(value)); }, this);
520
521
521 this.model.on('change:font_family', function (model, value) {
522 this.model.on('change:font_family', function (model, value) {
522 this.update_attr('font-family', value); }, this);
523 this.update_attr('font-family', value); }, this);
523
524
524 this.model.on('change:padding', function (model, value) {
525 this.model.on('change:padding', function (model, value) {
525 this.update_attr('padding', value); }, this);
526 this.update_attr('padding', value); }, this);
526
527
527 this.model.on('change:margin', function (model, value) {
528 this.model.on('change:margin', function (model, value) {
528 this.update_attr('margin', this._default_px(value)); }, this);
529 this.update_attr('margin', this._default_px(value)); }, this);
529
530
530 this.model.on('change:border_radius', function (model, value) {
531 this.model.on('change:border_radius', function (model, value) {
531 this.update_attr('border-radius', this._default_px(value)); }, this);
532 this.update_attr('border-radius', this._default_px(value)); }, this);
532
533
533 this.after_displayed(function() {
534 this.after_displayed(function() {
534 this.update_visible(this.model, this.model.get("visible"));
535 this.update_visible(this.model, this.model.get("visible"));
535 this.update_classes([], this.model.get('_dom_classes'));
536 this.update_classes([], this.model.get('_dom_classes'));
536
537
537 this.update_attr('color', this.model.get('color'));
538 this.update_attr('color', this.model.get('color'));
538 this.update_attr('background', this.model.get('background_color'));
539 this.update_attr('background', this.model.get('background_color'));
539 this.update_attr('width', this.model.get('width'));
540 this.update_attr('width', this.model.get('width'));
540 this.update_attr('height', this.model.get('height'));
541 this.update_attr('height', this.model.get('height'));
541 this.update_attr('border-color', this.model.get('border_color'));
542 this.update_attr('border-color', this.model.get('border_color'));
542 this.update_attr('border-width', this.model.get('border_width'));
543 this.update_attr('border-width', this.model.get('border_width'));
543 this.update_attr('border-style', this.model.get('border_style'));
544 this.update_attr('border-style', this.model.get('border_style'));
544 this.update_attr('font-style', this.model.get('font_style'));
545 this.update_attr('font-style', this.model.get('font_style'));
545 this.update_attr('font-weight', this.model.get('font_weight'));
546 this.update_attr('font-weight', this.model.get('font_weight'));
546 this.update_attr('font-size', this._default_px(this.model.get('font_size')));
547 this.update_attr('font-size', this._default_px(this.model.get('font_size')));
547 this.update_attr('font-family', this.model.get('font_family'));
548 this.update_attr('font-family', this.model.get('font_family'));
548 this.update_attr('padding', this.model.get('padding'));
549 this.update_attr('padding', this.model.get('padding'));
549 this.update_attr('margin', this._default_px(this.model.get('margin')));
550 this.update_attr('margin', this._default_px(this.model.get('margin')));
550 this.update_attr('border-radius', this._default_px(this.model.get('border_radius')));
551 this.update_attr('border-radius', this._default_px(this.model.get('border_radius')));
551
552
552 this.update_css(this.model, this.model.get("_css"));
553 this.update_css(this.model, this.model.get("_css"));
553 }, this);
554 }, this);
554 },
555 },
555
556
556 _default_px: function(value) {
557 _default_px: function(value) {
557 /**
558 /**
558 * Makes browser interpret a numerical string as a pixel value.
559 * Makes browser interpret a numerical string as a pixel value.
559 */
560 */
560 if (/^\d+\.?(\d+)?$/.test(value.trim())) {
561 if (/^\d+\.?(\d+)?$/.test(value.trim())) {
561 return value.trim() + 'px';
562 return value.trim() + 'px';
562 }
563 }
563 return value;
564 return value;
564 },
565 },
565
566
566 update_attr: function(name, value) {
567 update_attr: function(name, value) {
567 /**
568 /**
568 * Set a css attr of the widget view.
569 * Set a css attr of the widget view.
569 */
570 */
570 this.$el.css(name, value);
571 this.$el.css(name, value);
571 },
572 },
572
573
573 update_visible: function(model, value) {
574 update_visible: function(model, value) {
574 /**
575 /**
575 * Update visibility
576 * Update visibility
576 */
577 */
577 switch(value) {
578 switch(value) {
578 case null: // python None
579 case null: // python None
579 this.$el.show().css('visibility', 'hidden'); break;
580 this.$el.show().css('visibility', 'hidden'); break;
580 case false:
581 case false:
581 this.$el.hide(); break;
582 this.$el.hide(); break;
582 case true:
583 case true:
583 this.$el.show().css('visibility', ''); break;
584 this.$el.show().css('visibility', ''); break;
584 }
585 }
585 },
586 },
586
587
587 update_css: function (model, css) {
588 update_css: function (model, css) {
588 /**
589 /**
589 * Update the css styling of this view.
590 * Update the css styling of this view.
590 */
591 */
591 if (css === undefined) {return;}
592 if (css === undefined) {return;}
592 for (var i = 0; i < css.length; i++) {
593 for (var i = 0; i < css.length; i++) {
593 // Apply the css traits to all elements that match the selector.
594 // Apply the css traits to all elements that match the selector.
594 var selector = css[i][0];
595 var selector = css[i][0];
595 var elements = this._get_selector_element(selector);
596 var elements = this._get_selector_element(selector);
596 if (elements.length > 0) {
597 if (elements.length > 0) {
597 var trait_key = css[i][1];
598 var trait_key = css[i][1];
598 var trait_value = css[i][2];
599 var trait_value = css[i][2];
599 elements.css(trait_key ,trait_value);
600 elements.css(trait_key ,trait_value);
600 }
601 }
601 }
602 }
602 },
603 },
603
604
604 update_classes: function (old_classes, new_classes, $el) {
605 update_classes: function (old_classes, new_classes, $el) {
605 /**
606 /**
606 * Update the DOM classes applied to an element, default to this.$el.
607 * Update the DOM classes applied to an element, default to this.$el.
607 */
608 */
608 if ($el===undefined) {
609 if ($el===undefined) {
609 $el = this.$el;
610 $el = this.$el;
610 }
611 }
611 _.difference(old_classes, new_classes).map(function(c) {$el.removeClass(c);})
612 _.difference(old_classes, new_classes).map(function(c) {$el.removeClass(c);})
612 _.difference(new_classes, old_classes).map(function(c) {$el.addClass(c);})
613 _.difference(new_classes, old_classes).map(function(c) {$el.addClass(c);})
613 },
614 },
614
615
615 update_mapped_classes: function(class_map, trait_name, previous_trait_value, $el) {
616 update_mapped_classes: function(class_map, trait_name, previous_trait_value, $el) {
616 /**
617 /**
617 * Update the DOM classes applied to the widget based on a single
618 * Update the DOM classes applied to the widget based on a single
618 * trait's value.
619 * trait's value.
619 *
620 *
620 * Given a trait value classes map, this function automatically
621 * Given a trait value classes map, this function automatically
621 * handles applying the appropriate classes to the widget element
622 * handles applying the appropriate classes to the widget element
622 * and removing classes that are no longer valid.
623 * and removing classes that are no longer valid.
623 *
624 *
624 * Parameters
625 * Parameters
625 * ----------
626 * ----------
626 * class_map: dictionary
627 * class_map: dictionary
627 * Dictionary of trait values to class lists.
628 * Dictionary of trait values to class lists.
628 * Example:
629 * Example:
629 * {
630 * {
630 * success: ['alert', 'alert-success'],
631 * success: ['alert', 'alert-success'],
631 * info: ['alert', 'alert-info'],
632 * info: ['alert', 'alert-info'],
632 * warning: ['alert', 'alert-warning'],
633 * warning: ['alert', 'alert-warning'],
633 * danger: ['alert', 'alert-danger']
634 * danger: ['alert', 'alert-danger']
634 * };
635 * };
635 * trait_name: string
636 * trait_name: string
636 * Name of the trait to check the value of.
637 * Name of the trait to check the value of.
637 * previous_trait_value: optional string, default ''
638 * previous_trait_value: optional string, default ''
638 * Last trait value
639 * Last trait value
639 * $el: optional jQuery element handle, defaults to this.$el
640 * $el: optional jQuery element handle, defaults to this.$el
640 * Element that the classes are applied to.
641 * Element that the classes are applied to.
641 */
642 */
642 var key = previous_trait_value;
643 var key = previous_trait_value;
643 if (key === undefined) {
644 if (key === undefined) {
644 key = this.model.previous(trait_name);
645 key = this.model.previous(trait_name);
645 }
646 }
646 var old_classes = class_map[key] ? class_map[key] : [];
647 var old_classes = class_map[key] ? class_map[key] : [];
647 key = this.model.get(trait_name);
648 key = this.model.get(trait_name);
648 var new_classes = class_map[key] ? class_map[key] : [];
649 var new_classes = class_map[key] ? class_map[key] : [];
649
650
650 this.update_classes(old_classes, new_classes, $el || this.$el);
651 this.update_classes(old_classes, new_classes, $el || this.$el);
651 },
652 },
652
653
653 _get_selector_element: function (selector) {
654 _get_selector_element: function (selector) {
654 /**
655 /**
655 * Get the elements via the css selector.
656 * Get the elements via the css selector.
656 */
657 */
657 var elements;
658 var elements;
658 if (!selector) {
659 if (!selector) {
659 elements = this.$el;
660 elements = this.$el;
660 } else {
661 } else {
661 elements = this.$el.find(selector).addBack(selector);
662 elements = this.$el.find(selector).addBack(selector);
662 }
663 }
663 return elements;
664 return elements;
664 },
665 },
665
666
666 typeset: function(element, text){
667 typeset: function(element, text){
667 utils.typeset.apply(null, arguments);
668 utils.typeset.apply(null, arguments);
668 },
669 },
669 });
670 });
670
671
671
672
672 var ViewList = function(create_view, remove_view, context) {
673 var ViewList = function(create_view, remove_view, context) {
673 /**
674 /**
674 * - create_view and remove_view are default functions called when adding or removing views
675 * - create_view and remove_view are default functions called when adding or removing views
675 * - create_view takes a model and returns a view or a promise for a view for that model
676 * - create_view takes a model and returns a view or a promise for a view for that model
676 * - remove_view takes a view and destroys it (including calling `view.remove()`)
677 * - remove_view takes a view and destroys it (including calling `view.remove()`)
677 * - each time the update() function is called with a new list, the create and remove
678 * - each time the update() function is called with a new list, the create and remove
678 * callbacks will be called in an order so that if you append the views created in the
679 * callbacks will be called in an order so that if you append the views created in the
679 * create callback and remove the views in the remove callback, you will duplicate
680 * create callback and remove the views in the remove callback, you will duplicate
680 * the order of the list.
681 * the order of the list.
681 * - the remove callback defaults to just removing the view (e.g., pass in null for the second parameter)
682 * - the remove callback defaults to just removing the view (e.g., pass in null for the second parameter)
682 * - the context defaults to the created ViewList. If you pass another context, the create and remove
683 * - the context defaults to the created ViewList. If you pass another context, the create and remove
683 * will be called in that context.
684 * will be called in that context.
684 */
685 */
685
686
686 this.initialize.apply(this, arguments);
687 this.initialize.apply(this, arguments);
687 };
688 };
688
689
689 _.extend(ViewList.prototype, {
690 _.extend(ViewList.prototype, {
690 initialize: function(create_view, remove_view, context) {
691 initialize: function(create_view, remove_view, context) {
691 this._handler_context = context || this;
692 this._handler_context = context || this;
692 this._models = [];
693 this._models = [];
693 this.views = []; // list of promises for views
694 this.views = []; // list of promises for views
694 this._create_view = create_view;
695 this._create_view = create_view;
695 this._remove_view = remove_view || function(view) {view.remove();};
696 this._remove_view = remove_view || function(view) {view.remove();};
696 },
697 },
697
698
698 update: function(new_models, create_view, remove_view, context) {
699 update: function(new_models, create_view, remove_view, context) {
699 /**
700 /**
700 * the create_view, remove_view, and context arguments override the defaults
701 * the create_view, remove_view, and context arguments override the defaults
701 * specified when the list is created.
702 * specified when the list is created.
702 * after this function, the .views attribute is a list of promises for views
703 * after this function, the .views attribute is a list of promises for views
703 * if you want to perform some action on the list of views, do something like
704 * if you want to perform some action on the list of views, do something like
704 * `Promise.all(myviewlist.views).then(function(views) {...});`
705 * `Promise.all(myviewlist.views).then(function(views) {...});`
705 */
706 */
706 var remove = remove_view || this._remove_view;
707 var remove = remove_view || this._remove_view;
707 var create = create_view || this._create_view;
708 var create = create_view || this._create_view;
708 context = context || this._handler_context;
709 context = context || this._handler_context;
709 var i = 0;
710 var i = 0;
710 // first, skip past the beginning of the lists if they are identical
711 // first, skip past the beginning of the lists if they are identical
711 for (; i < new_models.length; i++) {
712 for (; i < new_models.length; i++) {
712 if (i >= this._models.length || new_models[i] !== this._models[i]) {
713 if (i >= this._models.length || new_models[i] !== this._models[i]) {
713 break;
714 break;
714 }
715 }
715 }
716 }
716
717
717 var first_removed = i;
718 var first_removed = i;
718 // Remove the non-matching items from the old list.
719 // Remove the non-matching items from the old list.
719 var removed = this.views.splice(first_removed, this.views.length-first_removed);
720 var removed = this.views.splice(first_removed, this.views.length-first_removed);
720 for (var j = 0; j < removed.length; j++) {
721 for (var j = 0; j < removed.length; j++) {
721 removed[j].then(function(view) {
722 removed[j].then(function(view) {
722 remove.call(context, view)
723 remove.call(context, view)
723 });
724 });
724 }
725 }
725
726
726 // Add the rest of the new list items.
727 // Add the rest of the new list items.
727 for (; i < new_models.length; i++) {
728 for (; i < new_models.length; i++) {
728 this.views.push(Promise.resolve(create.call(context, new_models[i])));
729 this.views.push(Promise.resolve(create.call(context, new_models[i])));
729 }
730 }
730 // make a copy of the input array
731 // make a copy of the input array
731 this._models = new_models.slice();
732 this._models = new_models.slice();
732 },
733 },
733
734
734 remove: function() {
735 remove: function() {
735 /**
736 /**
736 * removes every view in the list; convenience function for `.update([])`
737 * removes every view in the list; convenience function for `.update([])`
737 * that should be faster
738 * that should be faster
738 * returns a promise that resolves after this removal is done
739 * returns a promise that resolves after this removal is done
739 */
740 */
740 var that = this;
741 var that = this;
741 return Promise.all(this.views).then(function(views) {
742 return Promise.all(this.views).then(function(views) {
742 for (var i = 0; i < that.views.length; i++) {
743 for (var i = 0; i < that.views.length; i++) {
743 that._remove_view.call(that._handler_context, views[i]);
744 that._remove_view.call(that._handler_context, views[i]);
744 }
745 }
745 that.views = [];
746 that.views = [];
746 that._models = [];
747 that._models = [];
747 });
748 });
748 },
749 },
749 });
750 });
750
751
751 var widget = {
752 var widget = {
752 'WidgetModel': WidgetModel,
753 'WidgetModel': WidgetModel,
753 'WidgetView': WidgetView,
754 'WidgetView': WidgetView,
754 'DOMWidgetView': DOMWidgetView,
755 'DOMWidgetView': DOMWidgetView,
755 'ViewList': ViewList,
756 'ViewList': ViewList,
756 };
757 };
757
758
758 // For backwards compatability.
759 // For backwards compatability.
759 $.extend(IPython, widget);
760 $.extend(IPython, widget);
760
761
761 return widget;
762 return widget;
762 });
763 });
General Comments 0
You need to be logged in to leave comments. Login now