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