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