##// END OF EJS Templates
Fix view rendering order.
Jonathan Frederic -
Show More
@@ -1,246 +1,246 b''
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 cell = this.get_msg_cell(msg.parent_header.msg_id);
52 52 if (cell === null) {
53 53 console.log("Could not determine where the display" +
54 54 " message was from. Widget will not be displayed");
55 55 } else {
56 56 var dummy = null;
57 57 if (cell.widget_subarea) {
58 58 dummy = $('<div />');
59 59 cell.widget_subarea.append(dummy);
60 60 }
61 61
62 62 var that = this;
63 63 this.create_view(model, {cell: cell}).then(function(view) {
64 64 that._handle_display_view(view);
65 65 if (dummy) {
66 66 dummy.replaceWith(view.$el);
67 67 }
68 68 view.trigger('displayed');
69 }, function(error) { console.error(error); });
69 }, console.error);
70 70 }
71 71 };
72 72
73 73 WidgetManager.prototype._handle_display_view = function (view) {
74 74 // Have the IPython keyboard manager disable its event
75 75 // handling so the widget can capture keyboard input.
76 76 // Note, this is only done on the outer most widgets.
77 77 if (this.keyboard_manager) {
78 78 this.keyboard_manager.register_events(view.$el);
79 79
80 80 if (view.additional_elements) {
81 81 for (var i = 0; i < view.additional_elements.length; i++) {
82 82 this.keyboard_manager.register_events(view.additional_elements[i]);
83 83 }
84 84 }
85 85 }
86 86 };
87 87
88 88
89 89 WidgetManager.prototype.create_view = function(model, options) {
90 90 // Creates a view for a particular model.
91 91 return new Promise(function(resolve, reject) {
92 92 var view_name = model.get('_view_name');
93 93 var view_module = model.get('_view_module');
94 94 utils.try_load(view_name, view_module, WidgetManager._view_types).then(function(ViewType){
95 95
96 96 // If a view is passed into the method, use that view's cell as
97 97 // the cell for the view that is created.
98 98 options = options || {};
99 99 if (options.parent !== undefined) {
100 100 options.cell = options.parent.options.cell;
101 101 }
102 102
103 103 // Create and render the view...
104 104 var parameters = {model: model, options: options};
105 105 var view = new ViewType(parameters);
106 106 view.render();
107 107 model.on('destroy', view.remove, view);
108 108 resolve(view);
109 109 }, reject);
110 110 });
111 111 };
112 112
113 113 WidgetManager.prototype.get_msg_cell = function (msg_id) {
114 114 var cell = null;
115 115 // First, check to see if the msg was triggered by cell execution.
116 116 if (this.notebook) {
117 117 cell = this.notebook.get_msg_cell(msg_id);
118 118 }
119 119 if (cell !== null) {
120 120 return cell;
121 121 }
122 122 // Second, check to see if a get_cell callback was defined
123 123 // for the message. get_cell callbacks are registered for
124 124 // widget messages, so this block is actually checking to see if the
125 125 // message was triggered by a widget.
126 126 var kernel = this.comm_manager.kernel;
127 127 if (kernel) {
128 128 var callbacks = kernel.get_callbacks_for_msg(msg_id);
129 129 if (callbacks && callbacks.iopub &&
130 130 callbacks.iopub.get_cell !== undefined) {
131 131 return callbacks.iopub.get_cell();
132 132 }
133 133 }
134 134
135 135 // Not triggered by a cell or widget (no get_cell callback
136 136 // exists).
137 137 return null;
138 138 };
139 139
140 140 WidgetManager.prototype.callbacks = function (view) {
141 141 // callback handlers specific a view
142 142 var callbacks = {};
143 143 if (view && view.options.cell) {
144 144
145 145 // Try to get output handlers
146 146 var cell = view.options.cell;
147 147 var handle_output = null;
148 148 var handle_clear_output = null;
149 149 if (cell.output_area) {
150 150 handle_output = $.proxy(cell.output_area.handle_output, cell.output_area);
151 151 handle_clear_output = $.proxy(cell.output_area.handle_clear_output, cell.output_area);
152 152 }
153 153
154 154 // Create callback dictionary using what is known
155 155 var that = this;
156 156 callbacks = {
157 157 iopub : {
158 158 output : handle_output,
159 159 clear_output : handle_clear_output,
160 160
161 161 // Special function only registered by widget messages.
162 162 // Allows us to get the cell for a message so we know
163 163 // where to add widgets if the code requires it.
164 164 get_cell : function () {
165 165 return cell;
166 166 },
167 167 },
168 168 };
169 169 }
170 170 return callbacks;
171 171 };
172 172
173 173 WidgetManager.prototype.get_model = function (model_id) {
174 174 // Look-up a model instance by its id.
175 175 var model = this._models[model_id];
176 176 if (model !== undefined && model.id == model_id) {
177 177 return model;
178 178 }
179 179 return null;
180 180 };
181 181
182 182 WidgetManager.prototype._handle_comm_open = function (comm, msg) {
183 183 // Handle when a comm is opened.
184 184 this.create_model({
185 185 model_name: msg.content.data.model_name,
186 186 model_module: msg.content.data.model_module,
187 187 comm: comm});
188 188 };
189 189
190 190 WidgetManager.prototype.create_model = function (options) {
191 191 // Create and return a promise to create a new widget model.
192 192 //
193 193 // Minimally, one must provide the model_name and widget_class
194 194 // parameters to create a model from Javascript.
195 195 //
196 196 // Example
197 197 // --------
198 198 // JS:
199 199 // IPython.notebook.kernel.widget_manager.create_model({
200 200 // model_name: 'WidgetModel',
201 201 // widget_class: 'IPython.html.widgets.widget_int.IntSlider'})
202 202 // .then(function(model) { console.log('Create success!', model); },
203 // function(error) { console.error(error); });
203 // console.error);
204 204 //
205 205 // Parameters
206 206 // ----------
207 207 // options: dictionary
208 208 // Dictionary of options with the following contents:
209 209 // model_name: string
210 210 // Target name of the widget model to create.
211 211 // model_module: (optional) string
212 212 // Module name of the widget model to create.
213 213 // widget_class: (optional) string
214 214 // Target name of the widget in the back-end.
215 215 // comm: (optional) Comm
216 216 return new Promise(function(resolve, reject) {
217 217
218 218 // Get the model type using require or through the registry.
219 219 var widget_type_name = options.model_name;
220 220 var widget_module = options.model_module;
221 221 var that = this;
222 222 utils.try_load(widget_type_name, widget_module, WidgetManager._model_types)
223 223 .then(function(ModelType) {
224 224
225 225 // Create a comm if it wasn't provided.
226 226 var comm = options.comm;
227 227 if (!comm) {
228 228 comm = that.comm_manager.new_comm('ipython.widget', {'widget_class': options.widget_class});
229 229 }
230 230
231 231 var model_id = comm.comm_id;
232 232 var widget_model = new ModelType(that, model_id, comm);
233 233 widget_model.on('comm:close', function () {
234 234 delete that._models[model_id];
235 235 });
236 236 that._models[model_id] = widget_model;
237 237 reolve(widget_model);
238 238 }, reject);
239 239 });
240 240 };
241 241
242 242 // Backwards compatibility.
243 243 IPython.WidgetManager = WidgetManager;
244 244
245 245 return {'WidgetManager': WidgetManager};
246 246 });
@@ -1,622 +1,622 b''
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/namespace",
9 9 ], function(widgetmanager, _, Backbone, $, IPython){
10 10
11 11 var WidgetModel = Backbone.Model.extend({
12 12 constructor: function (widget_manager, model_id, comm, init_state_callback) {
13 13 // Constructor
14 14 //
15 15 // Creates a WidgetModel instance.
16 16 //
17 17 // Parameters
18 18 // ----------
19 19 // widget_manager : WidgetManager instance
20 20 // model_id : string
21 21 // An ID unique to this model.
22 22 // comm : Comm instance (optional)
23 23 // init_state_callback : callback (optional)
24 24 // Called once when the first state message is recieved from
25 25 // the back-end.
26 26 this.widget_manager = widget_manager;
27 27 this.init_state_callback = init_state_callback;
28 28 this._buffered_state_diff = {};
29 29 this.pending_msgs = 0;
30 30 this.msg_buffer = null;
31 31 this.state_lock = null;
32 32 this.id = model_id;
33 33 this.views = {};
34 34
35 35 if (comm !== undefined) {
36 36 // Remember comm associated with the model.
37 37 this.comm = comm;
38 38 comm.model = this;
39 39
40 40 // Hook comm messages up to model.
41 41 comm.on_close($.proxy(this._handle_comm_closed, this));
42 42 comm.on_msg($.proxy(this._handle_comm_msg, this));
43 43 }
44 44 return Backbone.Model.apply(this);
45 45 },
46 46
47 47 send: function (content, callbacks) {
48 48 // Send a custom msg over the comm.
49 49 if (this.comm !== undefined) {
50 50 var data = {method: 'custom', content: content};
51 51 this.comm.send(data, callbacks);
52 52 this.pending_msgs++;
53 53 }
54 54 },
55 55
56 56 _handle_comm_closed: function (msg) {
57 57 // Handle when a widget is closed.
58 58 this.trigger('comm:close');
59 59 this.stopListening();
60 60 this.trigger('destroy', this);
61 61 delete this.comm.model; // Delete ref so GC will collect widget model.
62 62 delete this.comm;
63 63 delete this.model_id; // Delete id from model so widget manager cleans up.
64 64 for (var id in this.views) {
65 65 if (this.views.hasOwnProperty(id)) {
66 66 this.views[id].remove();
67 67 }
68 68 }
69 69 },
70 70
71 71 _handle_comm_msg: function (msg) {
72 72 // Handle incoming comm msg.
73 73 var method = msg.content.data.method;
74 74 switch (method) {
75 75 case 'update':
76 76 this.set_state(msg.content.data.state);
77 77 if (this.init_state_callback) {
78 78 this.init_state_callback.apply(this, [this]);
79 79 delete this.init_state_callback;
80 80 }
81 81 break;
82 82 case 'custom':
83 83 this.trigger('msg:custom', msg.content.data.content);
84 84 break;
85 85 case 'display':
86 86 this.widget_manager.display_view(msg, this);
87 87 break;
88 88 }
89 89 },
90 90
91 91 set_state: function (state) {
92 92 // Handle when a widget is updated via the python side.
93 93 this.state_lock = state;
94 94 try {
95 95 var that = this;
96 96 WidgetModel.__super__.set.apply(this, [Object.keys(state).reduce(function(obj, key) {
97 97 obj[key] = that._unpack_models(state[key]);
98 98 return obj;
99 99 }, {})]);
100 100 } finally {
101 101 this.state_lock = null;
102 102 }
103 103 },
104 104
105 105 _handle_status: function (msg, callbacks) {
106 106 // Handle status msgs.
107 107
108 108 // execution_state : ('busy', 'idle', 'starting')
109 109 if (this.comm !== undefined) {
110 110 if (msg.content.execution_state ==='idle') {
111 111 // Send buffer if this message caused another message to be
112 112 // throttled.
113 113 if (this.msg_buffer !== null &&
114 114 (this.get('msg_throttle') || 3) === this.pending_msgs) {
115 115 var data = {method: 'backbone', sync_method: 'update', sync_data: this.msg_buffer};
116 116 this.comm.send(data, callbacks);
117 117 this.msg_buffer = null;
118 118 } else {
119 119 --this.pending_msgs;
120 120 }
121 121 }
122 122 }
123 123 },
124 124
125 125 callbacks: function(view) {
126 126 // Create msg callbacks for a comm msg.
127 127 var callbacks = this.widget_manager.callbacks(view);
128 128
129 129 if (callbacks.iopub === undefined) {
130 130 callbacks.iopub = {};
131 131 }
132 132
133 133 var that = this;
134 134 callbacks.iopub.status = function (msg) {
135 135 that._handle_status(msg, callbacks);
136 136 };
137 137 return callbacks;
138 138 },
139 139
140 140 set: function(key, val, options) {
141 141 // Set a value.
142 142 var return_value = WidgetModel.__super__.set.apply(this, arguments);
143 143
144 144 // Backbone only remembers the diff of the most recent set()
145 145 // operation. Calling set multiple times in a row results in a
146 146 // loss of diff information. Here we keep our own running diff.
147 147 this._buffered_state_diff = $.extend(this._buffered_state_diff, this.changedAttributes() || {});
148 148 return return_value;
149 149 },
150 150
151 151 sync: function (method, model, options) {
152 152 // Handle sync to the back-end. Called when a model.save() is called.
153 153
154 154 // Make sure a comm exists.
155 155 var error = options.error || function() {
156 156 console.error('Backbone sync error:', arguments);
157 157 };
158 158 if (this.comm === undefined) {
159 159 error();
160 160 return false;
161 161 }
162 162
163 163 // Delete any key value pairs that the back-end already knows about.
164 164 var attrs = (method === 'patch') ? options.attrs : model.toJSON(options);
165 165 if (this.state_lock !== null) {
166 166 var keys = Object.keys(this.state_lock);
167 167 for (var i=0; i<keys.length; i++) {
168 168 var key = keys[i];
169 169 if (attrs[key] === this.state_lock[key]) {
170 170 delete attrs[key];
171 171 }
172 172 }
173 173 }
174 174
175 175 // Only sync if there are attributes to send to the back-end.
176 176 attrs = this._pack_models(attrs);
177 177 if (_.size(attrs) > 0) {
178 178
179 179 // If this message was sent via backbone itself, it will not
180 180 // have any callbacks. It's important that we create callbacks
181 181 // so we can listen for status messages, etc...
182 182 var callbacks = options.callbacks || this.callbacks();
183 183
184 184 // Check throttle.
185 185 if (this.pending_msgs >= (this.get('msg_throttle') || 3)) {
186 186 // The throttle has been exceeded, buffer the current msg so
187 187 // it can be sent once the kernel has finished processing
188 188 // some of the existing messages.
189 189
190 190 // Combine updates if it is a 'patch' sync, otherwise replace updates
191 191 switch (method) {
192 192 case 'patch':
193 193 this.msg_buffer = $.extend(this.msg_buffer || {}, attrs);
194 194 break;
195 195 case 'update':
196 196 case 'create':
197 197 this.msg_buffer = attrs;
198 198 break;
199 199 default:
200 200 error();
201 201 return false;
202 202 }
203 203 this.msg_buffer_callbacks = callbacks;
204 204
205 205 } else {
206 206 // We haven't exceeded the throttle, send the message like
207 207 // normal.
208 208 var data = {method: 'backbone', sync_data: attrs};
209 209 this.comm.send(data, callbacks);
210 210 this.pending_msgs++;
211 211 }
212 212 }
213 213 // Since the comm is a one-way communication, assume the message
214 214 // arrived. Don't call success since we don't have a model back from the server
215 215 // this means we miss out on the 'sync' event.
216 216 this._buffered_state_diff = {};
217 217 },
218 218
219 219 save_changes: function(callbacks) {
220 220 // Push this model's state to the back-end
221 221 //
222 222 // This invokes a Backbone.Sync.
223 223 this.save(this._buffered_state_diff, {patch: true, callbacks: callbacks});
224 224 },
225 225
226 226 _pack_models: function(value) {
227 227 // Replace models with model ids recursively.
228 228 var that = this;
229 229 var packed;
230 230 if (value instanceof Backbone.Model) {
231 231 return "IPY_MODEL_" + value.id;
232 232
233 233 } else if ($.isArray(value)) {
234 234 packed = [];
235 235 _.each(value, function(sub_value, key) {
236 236 packed.push(that._pack_models(sub_value));
237 237 });
238 238 return packed;
239 239 } else if (value instanceof Date || value instanceof String) {
240 240 return value;
241 241 } else if (value instanceof Object) {
242 242 packed = {};
243 243 _.each(value, function(sub_value, key) {
244 244 packed[key] = that._pack_models(sub_value);
245 245 });
246 246 return packed;
247 247
248 248 } else {
249 249 return value;
250 250 }
251 251 },
252 252
253 253 _unpack_models: function(value) {
254 254 // Replace model ids with models recursively.
255 255 var that = this;
256 256 var unpacked;
257 257 if ($.isArray(value)) {
258 258 unpacked = [];
259 259 _.each(value, function(sub_value, key) {
260 260 unpacked.push(that._unpack_models(sub_value));
261 261 });
262 262 return unpacked;
263 263
264 264 } else if (value instanceof Object) {
265 265 unpacked = {};
266 266 _.each(value, function(sub_value, key) {
267 267 unpacked[key] = that._unpack_models(sub_value);
268 268 });
269 269 return unpacked;
270 270
271 271 } else if (typeof value === 'string' && value.slice(0,10) === "IPY_MODEL_") {
272 272 var model = this.widget_manager.get_model(value.slice(10, value.length));
273 273 if (model) {
274 274 return model;
275 275 } else {
276 276 return value;
277 277 }
278 278 } else {
279 279 return value;
280 280 }
281 281 },
282 282
283 283 on_some_change: function(keys, callback, context) {
284 284 // on_some_change(["key1", "key2"], foo, context) differs from
285 285 // on("change:key1 change:key2", foo, context).
286 286 // If the widget attributes key1 and key2 are both modified,
287 287 // the second form will result in foo being called twice
288 288 // while the first will call foo only once.
289 289 this.on('change', function() {
290 290 if (keys.some(this.hasChanged, this)) {
291 291 callback.apply(context);
292 292 }
293 293 }, this);
294 294
295 295 },
296 296 });
297 297 widgetmanager.WidgetManager.register_widget_model('WidgetModel', WidgetModel);
298 298
299 299
300 300 var WidgetView = Backbone.View.extend({
301 301 initialize: function(parameters) {
302 302 // Public constructor.
303 303 this.model.on('change',this.update,this);
304 304 this.options = parameters.options;
305 305 this.child_model_views = {};
306 306 this.child_views = {};
307 307 this.id = this.id || IPython.utils.uuid();
308 308 this.model.views[this.id] = this;
309 309 this.on('displayed', function() {
310 310 this.is_displayed = true;
311 311 }, this);
312 312 },
313 313
314 314 update: function(){
315 315 // Triggered on model change.
316 316 //
317 317 // Update view to be consistent with this.model
318 318 },
319 319
320 320 create_child_view: function(child_model, options) {
321 321 // Create and return a child view.
322 322 //
323 323 // -given a model and (optionally) a view name if the view name is
324 324 // not given, it defaults to the model's default view attribute.
325
326 // TODO: this is hacky, and makes the view depend on this cell attribute and widget manager behavior
327 // it would be great to have the widget manager add the cell metadata
328 // to the subview without having to add it here.
329 var that = this;
330 var old_callback = options.callback || function(view) {};
331 options = $.extend({ parent: this }, options || {});
332
333 this.model.widget_manager.create_view(child_model, options).then(function(child_view) {
334 // Associate the view id with the model id.
335 if (that.child_model_views[child_model.id] === undefined) {
336 that.child_model_views[child_model.id] = [];
337 }
338 that.child_model_views[child_model.id].push(child_view.id);
325 return new Promise(function(resolve, reject) {
326 // TODO: this is hacky, and makes the view depend on this cell attribute and widget manager behavior
327 // it would be great to have the widget manager add the cell metadata
328 // to the subview without having to add it here.
329 var that = this;
330 options = $.extend({ parent: this }, options || {});
331
332 this.model.widget_manager.create_view(child_model, options).then(function(child_view) {
333 // Associate the view id with the model id.
334 if (that.child_model_views[child_model.id] === undefined) {
335 that.child_model_views[child_model.id] = [];
336 }
337 that.child_model_views[child_model.id].push(child_view.id);
339 338
340 // Remember the view by id.
341 that.child_views[child_view.id] = child_view;
342 old_callback(child_view);
343 }, function(error) { console.error(error); });
339 // Remember the view by id.
340 that.child_views[child_view.id] = child_view;
341 resolve(child_view);
342 }, reject);
343 });
344 344 },
345 345
346 346 pop_child_view: function(child_model) {
347 347 // Delete a child view that was previously created using create_child_view.
348 348 var view_ids = this.child_model_views[child_model.id];
349 349 if (view_ids !== undefined) {
350 350
351 351 // Only delete the first view in the list.
352 352 var view_id = view_ids[0];
353 353 var view = this.child_views[view_id];
354 354 delete this.child_views[view_id];
355 355 view_ids.splice(0,1);
356 356 delete child_model.views[view_id];
357 357
358 358 // Remove the view list specific to this model if it is empty.
359 359 if (view_ids.length === 0) {
360 360 delete this.child_model_views[child_model.id];
361 361 }
362 362 return view;
363 363 }
364 364 return null;
365 365 },
366 366
367 367 do_diff: function(old_list, new_list, removed_callback, added_callback) {
368 368 // Difference a changed list and call remove and add callbacks for
369 369 // each removed and added item in the new list.
370 370 //
371 371 // Parameters
372 372 // ----------
373 373 // old_list : array
374 374 // new_list : array
375 375 // removed_callback : Callback(item)
376 376 // Callback that is called for each item removed.
377 377 // added_callback : Callback(item)
378 378 // Callback that is called for each item added.
379 379
380 380 // Walk the lists until an unequal entry is found.
381 381 var i;
382 382 for (i = 0; i < new_list.length; i++) {
383 383 if (i >= old_list.length || new_list[i] !== old_list[i]) {
384 384 break;
385 385 }
386 386 }
387 387
388 388 // Remove the non-matching items from the old list.
389 389 for (var j = i; j < old_list.length; j++) {
390 390 removed_callback(old_list[j]);
391 391 }
392 392
393 393 // Add the rest of the new list items.
394 394 for (; i < new_list.length; i++) {
395 395 added_callback(new_list[i]);
396 396 }
397 397 },
398 398
399 399 callbacks: function(){
400 400 // Create msg callbacks for a comm msg.
401 401 return this.model.callbacks(this);
402 402 },
403 403
404 404 render: function(){
405 405 // Render the view.
406 406 //
407 407 // By default, this is only called the first time the view is created
408 408 },
409 409
410 410 show: function(){
411 411 // Show the widget-area
412 412 if (this.options && this.options.cell &&
413 413 this.options.cell.widget_area !== undefined) {
414 414 this.options.cell.widget_area.show();
415 415 }
416 416 },
417 417
418 418 send: function (content) {
419 419 // Send a custom msg associated with this view.
420 420 this.model.send(content, this.callbacks());
421 421 },
422 422
423 423 touch: function () {
424 424 this.model.save_changes(this.callbacks());
425 425 },
426 426
427 427 after_displayed: function (callback, context) {
428 428 // Calls the callback right away is the view is already displayed
429 429 // otherwise, register the callback to the 'displayed' event.
430 430 if (this.is_displayed) {
431 431 callback.apply(context);
432 432 } else {
433 433 this.on('displayed', callback, context);
434 434 }
435 435 },
436 436 });
437 437
438 438
439 439 var DOMWidgetView = WidgetView.extend({
440 440 initialize: function (parameters) {
441 441 // Public constructor
442 442 DOMWidgetView.__super__.initialize.apply(this, [parameters]);
443 443 this.on('displayed', this.show, this);
444 444 this.model.on('change:visible', this.update_visible, this);
445 445 this.model.on('change:_css', this.update_css, this);
446 446
447 447 this.model.on('change:_dom_classes', function(model, new_classes) {
448 448 var old_classes = model.previous('_dom_classes');
449 449 this.update_classes(old_classes, new_classes);
450 450 }, this);
451 451
452 452 this.model.on('change:color', function (model, value) {
453 453 this.update_attr('color', value); }, this);
454 454
455 455 this.model.on('change:background_color', function (model, value) {
456 456 this.update_attr('background', value); }, this);
457 457
458 458 this.model.on('change:width', function (model, value) {
459 459 this.update_attr('width', value); }, this);
460 460
461 461 this.model.on('change:height', function (model, value) {
462 462 this.update_attr('height', value); }, this);
463 463
464 464 this.model.on('change:border_color', function (model, value) {
465 465 this.update_attr('border-color', value); }, this);
466 466
467 467 this.model.on('change:border_width', function (model, value) {
468 468 this.update_attr('border-width', value); }, this);
469 469
470 470 this.model.on('change:border_style', function (model, value) {
471 471 this.update_attr('border-style', value); }, this);
472 472
473 473 this.model.on('change:font_style', function (model, value) {
474 474 this.update_attr('font-style', value); }, this);
475 475
476 476 this.model.on('change:font_weight', function (model, value) {
477 477 this.update_attr('font-weight', value); }, this);
478 478
479 479 this.model.on('change:font_size', function (model, value) {
480 480 this.update_attr('font-size', this._default_px(value)); }, this);
481 481
482 482 this.model.on('change:font_family', function (model, value) {
483 483 this.update_attr('font-family', value); }, this);
484 484
485 485 this.model.on('change:padding', function (model, value) {
486 486 this.update_attr('padding', value); }, this);
487 487
488 488 this.model.on('change:margin', function (model, value) {
489 489 this.update_attr('margin', this._default_px(value)); }, this);
490 490
491 491 this.model.on('change:border_radius', function (model, value) {
492 492 this.update_attr('border-radius', this._default_px(value)); }, this);
493 493
494 494 this.after_displayed(function() {
495 495 this.update_visible(this.model, this.model.get("visible"));
496 496 this.update_classes([], this.model.get('_dom_classes'));
497 497
498 498 this.update_attr('color', this.model.get('color'));
499 499 this.update_attr('background', this.model.get('background_color'));
500 500 this.update_attr('width', this.model.get('width'));
501 501 this.update_attr('height', this.model.get('height'));
502 502 this.update_attr('border-color', this.model.get('border_color'));
503 503 this.update_attr('border-width', this.model.get('border_width'));
504 504 this.update_attr('border-style', this.model.get('border_style'));
505 505 this.update_attr('font-style', this.model.get('font_style'));
506 506 this.update_attr('font-weight', this.model.get('font_weight'));
507 507 this.update_attr('font-size', this.model.get('font_size'));
508 508 this.update_attr('font-family', this.model.get('font_family'));
509 509 this.update_attr('padding', this.model.get('padding'));
510 510 this.update_attr('margin', this.model.get('margin'));
511 511 this.update_attr('border-radius', this.model.get('border_radius'));
512 512
513 513 this.update_css(this.model, this.model.get("_css"));
514 514 }, this);
515 515 },
516 516
517 517 _default_px: function(value) {
518 518 // Makes browser interpret a numerical string as a pixel value.
519 519 if (/^\d+\.?(\d+)?$/.test(value.trim())) {
520 520 return value.trim() + 'px';
521 521 }
522 522 return value;
523 523 },
524 524
525 525 update_attr: function(name, value) {
526 526 // Set a css attr of the widget view.
527 527 this.$el.css(name, value);
528 528 },
529 529
530 530 update_visible: function(model, value) {
531 531 // Update visibility
532 532 this.$el.toggle(value);
533 533 },
534 534
535 535 update_css: function (model, css) {
536 536 // Update the css styling of this view.
537 537 var e = this.$el;
538 538 if (css === undefined) {return;}
539 539 for (var i = 0; i < css.length; i++) {
540 540 // Apply the css traits to all elements that match the selector.
541 541 var selector = css[i][0];
542 542 var elements = this._get_selector_element(selector);
543 543 if (elements.length > 0) {
544 544 var trait_key = css[i][1];
545 545 var trait_value = css[i][2];
546 546 elements.css(trait_key ,trait_value);
547 547 }
548 548 }
549 549 },
550 550
551 551 update_classes: function (old_classes, new_classes, $el) {
552 552 // Update the DOM classes applied to an element, default to this.$el.
553 553 if ($el===undefined) {
554 554 $el = this.$el;
555 555 }
556 556 this.do_diff(old_classes, new_classes, function(removed) {
557 557 $el.removeClass(removed);
558 558 }, function(added) {
559 559 $el.addClass(added);
560 560 });
561 561 },
562 562
563 563 update_mapped_classes: function(class_map, trait_name, previous_trait_value, $el) {
564 564 // Update the DOM classes applied to the widget based on a single
565 565 // trait's value.
566 566 //
567 567 // Given a trait value classes map, this function automatically
568 568 // handles applying the appropriate classes to the widget element
569 569 // and removing classes that are no longer valid.
570 570 //
571 571 // Parameters
572 572 // ----------
573 573 // class_map: dictionary
574 574 // Dictionary of trait values to class lists.
575 575 // Example:
576 576 // {
577 577 // success: ['alert', 'alert-success'],
578 578 // info: ['alert', 'alert-info'],
579 579 // warning: ['alert', 'alert-warning'],
580 580 // danger: ['alert', 'alert-danger']
581 581 // };
582 582 // trait_name: string
583 583 // Name of the trait to check the value of.
584 584 // previous_trait_value: optional string, default ''
585 585 // Last trait value
586 586 // $el: optional jQuery element handle, defaults to this.$el
587 587 // Element that the classes are applied to.
588 588 var key = previous_trait_value;
589 589 if (key === undefined) {
590 590 key = this.model.previous(trait_name);
591 591 }
592 592 var old_classes = class_map[key] ? class_map[key] : [];
593 593 key = this.model.get(trait_name);
594 594 var new_classes = class_map[key] ? class_map[key] : [];
595 595
596 596 this.update_classes(old_classes, new_classes, $el || this.$el);
597 597 },
598 598
599 599 _get_selector_element: function (selector) {
600 600 // Get the elements via the css selector.
601 601 var elements;
602 602 if (!selector) {
603 603 elements = this.$el;
604 604 } else {
605 605 elements = this.$el.find(selector).addBack(selector);
606 606 }
607 607 return elements;
608 608 },
609 609 });
610 610
611 611
612 612 var widget = {
613 613 'WidgetModel': WidgetModel,
614 614 'WidgetView': WidgetView,
615 615 'DOMWidgetView': DOMWidgetView,
616 616 };
617 617
618 618 // For backwards compatability.
619 619 $.extend(IPython, widget);
620 620
621 621 return widget;
622 622 });
@@ -1,346 +1,348 b''
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 "widgets/js/widget",
6 6 "jqueryui",
7 7 "bootstrap",
8 8 ], function(widget, $){
9 9
10 10 var BoxView = widget.DOMWidgetView.extend({
11 11 initialize: function(){
12 12 // Public constructor
13 13 BoxView.__super__.initialize.apply(this, arguments);
14 14 this.model.on('change:children', function(model, value) {
15 15 this.update_children(model.previous('children'), value);
16 16 }, this);
17 17 this.model.on('change:overflow_x', function(model, value) {
18 18 this.update_overflow_x();
19 19 }, this);
20 20 this.model.on('change:overflow_y', function(model, value) {
21 21 this.update_overflow_y();
22 22 }, this);
23 23 this.model.on('change:box_style', function(model, value) {
24 24 this.update_box_style();
25 25 }, this);
26 26 },
27 27
28 28 update_attr: function(name, value) {
29 29 // Set a css attr of the widget view.
30 30 this.$box.css(name, value);
31 31 },
32 32
33 33 render: function(){
34 34 // Called when view is rendered.
35 35 this.$box = this.$el;
36 36 this.$box.addClass('widget-box');
37 37 this.update_children([], this.model.get('children'));
38 38 this.update_overflow_x();
39 39 this.update_overflow_y();
40 40 this.update_box_style('');
41 41 },
42 42
43 43 update_overflow_x: function() {
44 44 // Called when the x-axis overflow setting is changed.
45 45 this.$box.css('overflow-x', this.model.get('overflow_x'));
46 46 },
47 47
48 48 update_overflow_y: function() {
49 49 // Called when the y-axis overflow setting is changed.
50 50 this.$box.css('overflow-y', this.model.get('overflow_y'));
51 51 },
52 52
53 53 update_box_style: function(previous_trait_value) {
54 54 var class_map = {
55 55 success: ['alert', 'alert-success'],
56 56 info: ['alert', 'alert-info'],
57 57 warning: ['alert', 'alert-warning'],
58 58 danger: ['alert', 'alert-danger']
59 59 };
60 60 this.update_mapped_classes(class_map, 'box_style', previous_trait_value, this.$box);
61 61 },
62 62
63 63 update_children: function(old_list, new_list) {
64 64 // Called when the children list changes.
65 65 this.do_diff(old_list, new_list,
66 66 $.proxy(this.remove_child_model, this),
67 67 $.proxy(this.add_child_model, this));
68 68 },
69 69
70 70 remove_child_model: function(model) {
71 71 // Called when a model is removed from the children list.
72 72 this.pop_child_view(model).remove();
73 73 },
74 74
75 75 add_child_model: function(model) {
76 76 // Called when a model is added to the children list.
77 77 var that = this;
78 this.create_child_view(model, {callback: function(view) {
79 that.$box.append(view.$el);
78 var dummy = $('<div/>');
79 that.$box.append(dummy);
80 this.create_child_view(model).then(function(view) {
81 dummy.replaceWith(view.$el);
80 82
81 83 // Trigger the displayed event of the child view.
82 84 that.after_displayed(function() {
83 85 view.trigger('displayed');
84 86 });
85 }});
87 }, console.error);
86 88 },
87 89 });
88 90
89 91
90 92 var FlexBoxView = BoxView.extend({
91 93 render: function(){
92 94 FlexBoxView.__super__.render.apply(this);
93 95 this.model.on('change:orientation', this.update_orientation, this);
94 96 this.model.on('change:flex', this._flex_changed, this);
95 97 this.model.on('change:pack', this._pack_changed, this);
96 98 this.model.on('change:align', this._align_changed, this);
97 99 this._flex_changed();
98 100 this._pack_changed();
99 101 this._align_changed();
100 102 this.update_orientation();
101 103 },
102 104
103 105 update_orientation: function(){
104 106 var orientation = this.model.get("orientation");
105 107 if (orientation == "vertical") {
106 108 this.$box.removeClass("hbox").addClass("vbox");
107 109 } else {
108 110 this.$box.removeClass("vbox").addClass("hbox");
109 111 }
110 112 },
111 113
112 114 _flex_changed: function(){
113 115 if (this.model.previous('flex')) {
114 116 this.$box.removeClass('box-flex' + this.model.previous('flex'));
115 117 }
116 118 this.$box.addClass('box-flex' + this.model.get('flex'));
117 119 },
118 120
119 121 _pack_changed: function(){
120 122 if (this.model.previous('pack')) {
121 123 this.$box.removeClass(this.model.previous('pack'));
122 124 }
123 125 this.$box.addClass(this.model.get('pack'));
124 126 },
125 127
126 128 _align_changed: function(){
127 129 if (this.model.previous('align')) {
128 130 this.$box.removeClass('align-' + this.model.previous('align'));
129 131 }
130 132 this.$box.addClass('align-' + this.model.get('align'));
131 133 },
132 134 });
133 135
134 136 var PopupView = BoxView.extend({
135 137
136 138 render: function(){
137 139 // Called when view is rendered.
138 140 var that = this;
139 141
140 142 this.$el.on("remove", function(){
141 143 that.$backdrop.remove();
142 144 });
143 145 this.$backdrop = $('<div />')
144 146 .appendTo($('#notebook-container'))
145 147 .addClass('modal-dialog')
146 148 .css('position', 'absolute')
147 149 .css('left', '0px')
148 150 .css('top', '0px');
149 151 this.$window = $('<div />')
150 152 .appendTo(this.$backdrop)
151 153 .addClass('modal-content widget-modal')
152 154 .mousedown(function(){
153 155 that.bring_to_front();
154 156 });
155 157
156 158 // Set the elements array since the this.$window element is not child
157 159 // of this.$el and the parent widget manager or other widgets may
158 160 // need to know about all of the top-level widgets. The IPython
159 161 // widget manager uses this to register the elements with the
160 162 // keyboard manager.
161 163 this.additional_elements = [this.$window];
162 164
163 165 this.$title_bar = $('<div />')
164 166 .addClass('popover-title')
165 167 .appendTo(this.$window)
166 168 .mousedown(function(){
167 169 that.bring_to_front();
168 170 });
169 171 this.$close = $('<button />')
170 172 .addClass('close fa fa-remove')
171 173 .css('margin-left', '5px')
172 174 .appendTo(this.$title_bar)
173 175 .click(function(){
174 176 that.hide();
175 177 event.stopPropagation();
176 178 });
177 179 this.$minimize = $('<button />')
178 180 .addClass('close fa fa-arrow-down')
179 181 .appendTo(this.$title_bar)
180 182 .click(function(){
181 183 that.popped_out = !that.popped_out;
182 184 if (!that.popped_out) {
183 185 that.$minimize
184 186 .removeClass('fa-arrow-down')
185 187 .addClass('fa-arrow-up');
186 188
187 189 that.$window
188 190 .draggable('destroy')
189 191 .resizable('destroy')
190 192 .removeClass('widget-modal modal-content')
191 193 .addClass('docked-widget-modal')
192 194 .detach()
193 195 .insertBefore(that.$show_button);
194 196 that.$show_button.hide();
195 197 that.$close.hide();
196 198 } else {
197 199 that.$minimize
198 200 .addClass('fa-arrow-down')
199 201 .removeClass('fa-arrow-up');
200 202
201 203 that.$window
202 204 .removeClass('docked-widget-modal')
203 205 .addClass('widget-modal modal-content')
204 206 .detach()
205 207 .appendTo(that.$backdrop)
206 208 .draggable({handle: '.popover-title', snap: '#notebook, .modal', snapMode: 'both'})
207 209 .resizable()
208 210 .children('.ui-resizable-handle').show();
209 211 that.show();
210 212 that.$show_button.show();
211 213 that.$close.show();
212 214 }
213 215 event.stopPropagation();
214 216 });
215 217 this.$title = $('<div />')
216 218 .addClass('widget-modal-title')
217 219 .html("&nbsp;")
218 220 .appendTo(this.$title_bar);
219 221 this.$box = $('<div />')
220 222 .addClass('modal-body')
221 223 .addClass('widget-modal-body')
222 224 .addClass('widget-box')
223 225 .addClass('vbox')
224 226 .appendTo(this.$window);
225 227
226 228 this.$show_button = $('<button />')
227 229 .html("&nbsp;")
228 230 .addClass('btn btn-info widget-modal-show')
229 231 .appendTo(this.$el)
230 232 .click(function(){
231 233 that.show();
232 234 });
233 235
234 236 this.$window.draggable({handle: '.popover-title', snap: '#notebook, .modal', snapMode: 'both'});
235 237 this.$window.resizable();
236 238 this.$window.on('resize', function(){
237 239 that.$box.outerHeight(that.$window.innerHeight() - that.$title_bar.outerHeight());
238 240 });
239 241
240 242 this._shown_once = false;
241 243 this.popped_out = true;
242 244
243 245 this.update_children([], this.model.get('children'));
244 246 this.model.on('change:children', function(model, value) {
245 247 this.update_children(model.previous('children'), value);
246 248 }, this);
247 249 },
248 250
249 251 hide: function() {
250 252 // Called when the modal hide button is clicked.
251 253 this.$window.hide();
252 254 this.$show_button.removeClass('btn-info');
253 255 },
254 256
255 257 show: function() {
256 258 // Called when the modal show button is clicked.
257 259 this.$show_button.addClass('btn-info');
258 260 this.$window.show();
259 261 if (this.popped_out) {
260 262 this.$window.css("positon", "absolute");
261 263 this.$window.css("top", "0px");
262 264 this.$window.css("left", Math.max(0, (($('body').outerWidth() - this.$window.outerWidth()) / 2) +
263 265 $(window).scrollLeft()) + "px");
264 266 this.bring_to_front();
265 267 }
266 268 },
267 269
268 270 bring_to_front: function() {
269 271 // Make the modal top-most, z-ordered about the other modals.
270 272 var $widget_modals = $(".widget-modal");
271 273 var max_zindex = 0;
272 274 $widget_modals.each(function (index, el){
273 275 var zindex = parseInt($(el).css('z-index'));
274 276 if (!isNaN(zindex)) {
275 277 max_zindex = Math.max(max_zindex, zindex);
276 278 }
277 279 });
278 280
279 281 // Start z-index of widget modals at 2000
280 282 max_zindex = Math.max(max_zindex, 2000);
281 283
282 284 $widget_modals.each(function (index, el){
283 285 $el = $(el);
284 286 if (max_zindex == parseInt($el.css('z-index'))) {
285 287 $el.css('z-index', max_zindex - 1);
286 288 }
287 289 });
288 290 this.$window.css('z-index', max_zindex);
289 291 },
290 292
291 293 update: function(){
292 294 // Update the contents of this view
293 295 //
294 296 // Called when the model is changed. The model may have been
295 297 // changed by another view or by a state update from the back-end.
296 298 var description = this.model.get('description');
297 299 if (description.trim().length === 0) {
298 300 this.$title.html("&nbsp;"); // Preserve title height
299 301 } else {
300 302 this.$title.text(description);
301 303 MathJax.Hub.Queue(["Typeset",MathJax.Hub,this.$title.get(0)]);
302 304 }
303 305
304 306 var button_text = this.model.get('button_text');
305 307 if (button_text.trim().length === 0) {
306 308 this.$show_button.html("&nbsp;"); // Preserve button height
307 309 } else {
308 310 this.$show_button.text(button_text);
309 311 }
310 312
311 313 if (!this._shown_once) {
312 314 this._shown_once = true;
313 315 this.show();
314 316 }
315 317
316 318 return PopupView.__super__.update.apply(this);
317 319 },
318 320
319 321 _get_selector_element: function(selector) {
320 322 // Get an element view a 'special' jquery selector. (see widget.js)
321 323 //
322 324 // Since the modal actually isn't within the $el in the DOM, we need to extend
323 325 // the selector logic to allow the user to set css on the modal if need be.
324 326 // The convention used is:
325 327 // "modal" - select the modal div
326 328 // "modal [selector]" - select element(s) within the modal div.
327 329 // "[selector]" - select elements within $el
328 330 // "" - select the $el
329 331 if (selector.substring(0, 5) == 'modal') {
330 332 if (selector == 'modal') {
331 333 return this.$window;
332 334 } else {
333 335 return this.$window.find(selector.substring(6));
334 336 }
335 337 } else {
336 338 return PopupView.__super__._get_selector_element.apply(this, [selector]);
337 339 }
338 340 },
339 341 });
340 342
341 343 return {
342 344 'BoxView': BoxView,
343 345 'PopupView': PopupView,
344 346 'FlexBoxView': FlexBoxView,
345 347 };
346 348 });
@@ -1,257 +1,261 b''
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 "widgets/js/widget",
6 6 "base/js/utils",
7 7 "jquery",
8 8 "bootstrap",
9 9 ], function(widget, utils, $){
10 10
11 11 var AccordionView = widget.DOMWidgetView.extend({
12 12 render: function(){
13 13 // Called when view is rendered.
14 14 var guid = 'panel-group' + utils.uuid();
15 15 this.$el
16 16 .attr('id', guid)
17 17 .addClass('panel-group');
18 18 this.containers = [];
19 19 this.model_containers = {};
20 20 this.update_children([], this.model.get('children'));
21 21 this.model.on('change:children', function(model, value, options) {
22 22 this.update_children(model.previous('children'), value);
23 23 }, this);
24 24 this.model.on('change:selected_index', function(model, value, options) {
25 25 this.update_selected_index(model.previous('selected_index'), value, options);
26 26 }, this);
27 27 this.model.on('change:_titles', function(model, value, options) {
28 28 this.update_titles(value);
29 29 }, this);
30 30 var that = this;
31 31 this.on('displayed', function() {
32 32 this.update_titles();
33 33 }, this);
34 34 },
35 35
36 36 update_titles: function(titles) {
37 37 // Set tab titles
38 38 if (!titles) {
39 39 titles = this.model.get('_titles');
40 40 }
41 41
42 42 var that = this;
43 43 _.each(titles, function(title, page_index) {
44 44 var accordian = that.containers[page_index];
45 45 if (accordian !== undefined) {
46 46 accordian
47 47 .find('.panel-heading')
48 48 .find('.accordion-toggle')
49 49 .text(title);
50 50 }
51 51 });
52 52 },
53 53
54 54 update_selected_index: function(old_index, new_index, options) {
55 55 // Only update the selection if the selection wasn't triggered
56 56 // by the front-end. It must be triggered by the back-end.
57 57 if (options === undefined || options.updated_view != this) {
58 58 this.containers[old_index].find('.panel-collapse').collapse('hide');
59 59 if (0 <= new_index && new_index < this.containers.length) {
60 60 this.containers[new_index].find('.panel-collapse').collapse('show');
61 61 }
62 62 }
63 63 },
64 64
65 65 update_children: function(old_list, new_list) {
66 66 // Called when the children list is modified.
67 67 this.do_diff(old_list,
68 68 new_list,
69 69 $.proxy(this.remove_child_model, this),
70 70 $.proxy(this.add_child_model, this));
71 71 },
72 72
73 73 remove_child_model: function(model) {
74 74 // Called when a child is removed from children list.
75 75 var accordion_group = this.model_containers[model.id];
76 76 this.containers.splice(accordion_group.container_index, 1);
77 77 delete this.model_containers[model.id];
78 78 accordion_group.remove();
79 79 this.pop_child_view(model);
80 80 },
81 81
82 82 add_child_model: function(model) {
83 83 // Called when a child is added to children list.
84 84 var index = this.containers.length;
85 85 var uuid = utils.uuid();
86 86 var accordion_group = $('<div />')
87 87 .addClass('panel panel-default')
88 88 .appendTo(this.$el);
89 89 var accordion_heading = $('<div />')
90 90 .addClass('panel-heading')
91 91 .appendTo(accordion_group);
92 92 var that = this;
93 93 var accordion_toggle = $('<a />')
94 94 .addClass('accordion-toggle')
95 95 .attr('data-toggle', 'collapse')
96 96 .attr('data-parent', '#' + this.$el.attr('id'))
97 97 .attr('href', '#' + uuid)
98 98 .click(function(evt){
99 99
100 100 // Calling model.set will trigger all of the other views of the
101 101 // model to update.
102 102 that.model.set("selected_index", index, {updated_view: that});
103 103 that.touch();
104 104 })
105 105 .text('Page ' + index)
106 106 .appendTo(accordion_heading);
107 107 var accordion_body = $('<div />', {id: uuid})
108 108 .addClass('panel-collapse collapse')
109 109 .appendTo(accordion_group);
110 110 var accordion_inner = $('<div />')
111 111 .addClass('panel-body')
112 112 .appendTo(accordion_body);
113 113 var container_index = this.containers.push(accordion_group) - 1;
114 114 accordion_group.container_index = container_index;
115 115 this.model_containers[model.id] = accordion_group;
116 116
117 this.create_child_view(model, {callback: function(view) {
118 accordion_inner.append(view.$el);
119
117 var dummy = $('<div/>');
118 accordion_inner.append(dummy);
119 this.create_child_view(model).then(function(view) {
120 dummy.replaceWith(view.$el);
120 121 that.update();
121 122 that.update_titles();
122 123
123 124 // Trigger the displayed event of the child view.
124 125 that.after_displayed(function() {
125 126 view.trigger('displayed');
126 127 });
127 }});
128 }, console.error);
128 129 },
129 130 });
130 131
131 132
132 133 var TabView = widget.DOMWidgetView.extend({
133 134 initialize: function() {
134 135 // Public constructor.
135 136 this.containers = [];
136 137 TabView.__super__.initialize.apply(this, arguments);
137 138 },
138 139
139 140 render: function(){
140 141 // Called when view is rendered.
141 142 var uuid = 'tabs'+utils.uuid();
142 143 var that = this;
143 144 this.$tabs = $('<div />', {id: uuid})
144 145 .addClass('nav')
145 146 .addClass('nav-tabs')
146 147 .appendTo(this.$el);
147 148 this.$tab_contents = $('<div />', {id: uuid + 'Content'})
148 149 .addClass('tab-content')
149 150 .appendTo(this.$el);
150 151 this.containers = [];
151 152 this.update_children([], this.model.get('children'));
152 153 this.model.on('change:children', function(model, value, options) {
153 154 this.update_children(model.previous('children'), value);
154 155 }, this);
155 156 },
156 157
157 158 update_attr: function(name, value) {
158 159 // Set a css attr of the widget view.
159 160 this.$tabs.css(name, value);
160 161 },
161 162
162 163 update_children: function(old_list, new_list) {
163 164 // Called when the children list is modified.
164 165 this.do_diff(old_list,
165 166 new_list,
166 167 $.proxy(this.remove_child_model, this),
167 168 $.proxy(this.add_child_model, this));
168 169 },
169 170
170 171 remove_child_model: function(model) {
171 172 // Called when a child is removed from children list.
172 173 var view = this.pop_child_view(model);
173 174 this.containers.splice(view.parent_tab.tab_text_index, 1);
174 175 view.parent_tab.remove();
175 176 view.parent_container.remove();
176 177 view.remove();
177 178 },
178 179
179 180 add_child_model: function(model) {
180 181 // Called when a child is added to children list.
181 182 var index = this.containers.length;
182 183 var uuid = utils.uuid();
183 184
184 185 var that = this;
185 186 var tab = $('<li />')
186 187 .css('list-style-type', 'none')
187 188 .appendTo(this.$tabs);
188 189
189 this.create_child_view(model, {callback: function(view) {
190 view.parent_tab = tab;
191 190
192 var tab_text = $('<a />')
193 .attr('href', '#' + uuid)
194 .attr('data-toggle', 'tab')
195 .text('Page ' + index)
196 .appendTo(tab)
197 .click(function (e) {
198
199 // Calling model.set will trigger all of the other views of the
200 // model to update.
201 that.model.set("selected_index", index, {updated_view: that});
202 that.touch();
203 that.select_page(index);
204 });
205 tab.tab_text_index = that.containers.push(tab_text) - 1;
191 var tab_text = $('<a />')
192 .attr('href', '#' + uuid)
193 .attr('data-toggle', 'tab')
194 .text('Page ' + index)
195 .appendTo(tab)
196 .click(function (e) {
197
198 // Calling model.set will trigger all of the other views of the
199 // model to update.
200 that.model.set("selected_index", index, {updated_view: that});
201 that.touch();
202 that.select_page(index);
203 });
204 tab.tab_text_index = that.containers.push(tab_text) - 1;
205
206 var dummy = $('<div />');
207 var contents_div = $('<div />', {id: uuid})
208 .addClass('tab-pane')
209 .addClass('fade')
210 .append(dummy)
211 .appendTo(that.$tab_contents);
206 212
207 var contents_div = $('<div />', {id: uuid})
208 .addClass('tab-pane')
209 .addClass('fade')
210 .append(view.$el)
211 .appendTo(that.$tab_contents);
213 this.create_child_view(model).then(function(view) {
214 dummy.replaceWith(view.$el);
215 view.parent_tab = tab;
212 216 view.parent_container = contents_div;
213 217
214 218 // Trigger the displayed event of the child view.
215 219 that.after_displayed(function() {
216 220 view.trigger('displayed');
217 221 });
218 }});
222 }, console.error);
219 223 },
220 224
221 225 update: function(options) {
222 226 // Update the contents of this view
223 227 //
224 228 // Called when the model is changed. The model may have been
225 229 // changed by another view or by a state update from the back-end.
226 230 if (options === undefined || options.updated_view != this) {
227 231 // Set tab titles
228 232 var titles = this.model.get('_titles');
229 233 var that = this;
230 234 _.each(titles, function(title, page_index) {
231 235 var tab_text = that.containers[page_index];
232 236 if (tab_text !== undefined) {
233 237 tab_text.text(title);
234 238 }
235 239 });
236 240
237 241 var selected_index = this.model.get('selected_index');
238 242 if (0 <= selected_index && selected_index < this.containers.length) {
239 243 this.select_page(selected_index);
240 244 }
241 245 }
242 246 return TabView.__super__.update.apply(this);
243 247 },
244 248
245 249 select_page: function(index) {
246 250 // Select a page.
247 251 this.$tabs.find('li')
248 252 .removeClass('active');
249 253 this.containers[index].tab('show');
250 254 },
251 255 });
252 256
253 257 return {
254 258 'AccordionView': AccordionView,
255 259 'TabView': TabView,
256 260 };
257 261 });
General Comments 0
You need to be logged in to leave comments. Login now