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