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