##// END OF EJS Templates
Implement view logic in selection containers.
Jonathan Frederic -
Show More
@@ -1,683 +1,681
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 }, utils.reject("Couldn't set model state", true));
98 }, 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.child_model_views = {};
295 this.child_model_views = {};
296 this.child_views = {};
296 this.child_views = {};
297 this.id = this.id || utils.uuid();
297 this.id = this.id || utils.uuid();
298 this.model.views[this.id] = this;
298 this.model.views[this.id] = this;
299 this.on('displayed', function() {
299 this.on('displayed', function() {
300 this.is_displayed = true;
300 this.is_displayed = true;
301 }, this);
301 }, this);
302 },
302 },
303
303
304 update: function(){
304 update: function(){
305 // Triggered on model change.
305 // Triggered on model change.
306 //
306 //
307 // Update view to be consistent with this.model
307 // Update view to be consistent with this.model
308 },
308 },
309
309
310 create_child_view: function(child_model, options) {
310 create_child_view: function(child_model, options) {
311 // Create and promise that resolves to a child view of a given model
311 // Create and promise that resolves to a child view of a given model
312 var that = this;
312 var that = this;
313 options = $.extend({ parent: this }, options || {});
313 options = $.extend({ parent: this }, options || {});
314 return this.model.widget_manager.create_view(child_model, options).then(function(child_view) {
314 return this.model.widget_manager.create_view(child_model, options).then(function(child_view) {
315 // Associate the view id with the model id.
315 // Associate the view id with the model id.
316 if (that.child_model_views[child_model.id] === undefined) {
316 if (that.child_model_views[child_model.id] === undefined) {
317 that.child_model_views[child_model.id] = [];
317 that.child_model_views[child_model.id] = [];
318 }
318 }
319 that.child_model_views[child_model.id].push(child_view.id);
319 that.child_model_views[child_model.id].push(child_view.id);
320 // Remember the view by id.
320 // Remember the view by id.
321 that.child_views[child_view.id] = child_view;
321 that.child_views[child_view.id] = child_view;
322 return child_view;
322 return child_view;
323 }, utils.reject("Couldn't create child view"));
323 }, utils.reject("Couldn't create child view"));
324 },
324 },
325
325
326 pop_child_view: function(child_model) {
326 pop_child_view: function(child_model) {
327 // Delete a child view that was previously created using create_child_view.
327 // Delete a child view that was previously created using create_child_view.
328 console.error("Deprecated pop_child_view; use a ViewList or similar class instead");
328 console.error("Deprecated pop_child_view; use a ViewList or similar class instead");
329 var view_ids = this.child_model_views[child_model.id];
329 var view_ids = this.child_model_views[child_model.id];
330 if (view_ids !== undefined) {
330 if (view_ids !== undefined) {
331
331
332 // Only delete the first view in the list.
332 // Only delete the first view in the list.
333 var view_id = view_ids[0];
333 var view_id = view_ids[0];
334 var view = this.child_views[view_id];
334 var view = this.child_views[view_id];
335 delete this.child_views[view_id];
335 delete this.child_views[view_id];
336 view_ids.splice(0,1);
336 view_ids.splice(0,1);
337 delete child_model.views[view_id];
337 delete child_model.views[view_id];
338
338
339 // Remove the view list specific to this model if it is empty.
339 // Remove the view list specific to this model if it is empty.
340 if (view_ids.length === 0) {
340 if (view_ids.length === 0) {
341 delete this.child_model_views[child_model.id];
341 delete this.child_model_views[child_model.id];
342 }
342 }
343 return view;
343 return view;
344 }
344 }
345 return null;
345 return null;
346 },
346 },
347
347
348 do_diff: function(old_list, new_list, removed_callback, added_callback) {
348 do_diff: function(old_list, new_list, removed_callback, added_callback) {
349 // Difference a changed list and call remove and add callbacks for
349 // Difference a changed list and call remove and add callbacks for
350 // each removed and added item in the new list.
350 // each removed and added item in the new list.
351 //
351 //
352 // Parameters
352 // Parameters
353 // ----------
353 // ----------
354 // old_list : array
354 // old_list : array
355 // new_list : array
355 // new_list : array
356 // removed_callback : Callback(item)
356 // removed_callback : Callback(item)
357 // Callback that is called for each item removed.
357 // Callback that is called for each item removed.
358 // added_callback : Callback(item)
358 // added_callback : Callback(item)
359 // Callback that is called for each item added.
359 // Callback that is called for each item added.
360
360
361 // Walk the lists until an unequal entry is found.
361 // Walk the lists until an unequal entry is found.
362 console.error("Deprecated _do_diff; use a ViewList or similar class instead");
363
364 var i;
362 var i;
365 for (i = 0; i < new_list.length; i++) {
363 for (i = 0; i < new_list.length; i++) {
366 if (i >= old_list.length || new_list[i] !== old_list[i]) {
364 if (i >= old_list.length || new_list[i] !== old_list[i]) {
367 break;
365 break;
368 }
366 }
369 }
367 }
370
368
371 // Remove the non-matching items from the old list.
369 // Remove the non-matching items from the old list.
372 for (var j = i; j < old_list.length; j++) {
370 for (var j = i; j < old_list.length; j++) {
373 removed_callback(old_list[j]);
371 removed_callback(old_list[j]);
374 }
372 }
375
373
376 // Add the rest of the new list items.
374 // Add the rest of the new list items.
377 for (; i < new_list.length; i++) {
375 for (; i < new_list.length; i++) {
378 added_callback(new_list[i]);
376 added_callback(new_list[i]);
379 }
377 }
380 },
378 },
381
379
382 callbacks: function(){
380 callbacks: function(){
383 // Create msg callbacks for a comm msg.
381 // Create msg callbacks for a comm msg.
384 return this.model.callbacks(this);
382 return this.model.callbacks(this);
385 },
383 },
386
384
387 render: function(){
385 render: function(){
388 // Render the view.
386 // Render the view.
389 //
387 //
390 // By default, this is only called the first time the view is created
388 // By default, this is only called the first time the view is created
391 },
389 },
392
390
393 show: function(){
391 show: function(){
394 // Show the widget-area
392 // Show the widget-area
395 if (this.options && this.options.cell &&
393 if (this.options && this.options.cell &&
396 this.options.cell.widget_area !== undefined) {
394 this.options.cell.widget_area !== undefined) {
397 this.options.cell.widget_area.show();
395 this.options.cell.widget_area.show();
398 }
396 }
399 },
397 },
400
398
401 send: function (content) {
399 send: function (content) {
402 // Send a custom msg associated with this view.
400 // Send a custom msg associated with this view.
403 this.model.send(content, this.callbacks());
401 this.model.send(content, this.callbacks());
404 },
402 },
405
403
406 touch: function () {
404 touch: function () {
407 this.model.save_changes(this.callbacks());
405 this.model.save_changes(this.callbacks());
408 },
406 },
409
407
410 after_displayed: function (callback, context) {
408 after_displayed: function (callback, context) {
411 // Calls the callback right away is the view is already displayed
409 // Calls the callback right away is the view is already displayed
412 // otherwise, register the callback to the 'displayed' event.
410 // otherwise, register the callback to the 'displayed' event.
413 if (this.is_displayed) {
411 if (this.is_displayed) {
414 callback.apply(context);
412 callback.apply(context);
415 } else {
413 } else {
416 this.on('displayed', callback, context);
414 this.on('displayed', callback, context);
417 }
415 }
418 },
416 },
419 });
417 });
420
418
421
419
422 var DOMWidgetView = WidgetView.extend({
420 var DOMWidgetView = WidgetView.extend({
423 initialize: function (parameters) {
421 initialize: function (parameters) {
424 // Public constructor
422 // Public constructor
425 DOMWidgetView.__super__.initialize.apply(this, [parameters]);
423 DOMWidgetView.__super__.initialize.apply(this, [parameters]);
426 this.on('displayed', this.show, this);
424 this.on('displayed', this.show, this);
427 this.model.on('change:visible', this.update_visible, this);
425 this.model.on('change:visible', this.update_visible, this);
428 this.model.on('change:_css', this.update_css, this);
426 this.model.on('change:_css', this.update_css, this);
429
427
430 this.model.on('change:_dom_classes', function(model, new_classes) {
428 this.model.on('change:_dom_classes', function(model, new_classes) {
431 var old_classes = model.previous('_dom_classes');
429 var old_classes = model.previous('_dom_classes');
432 this.update_classes(old_classes, new_classes);
430 this.update_classes(old_classes, new_classes);
433 }, this);
431 }, this);
434
432
435 this.model.on('change:color', function (model, value) {
433 this.model.on('change:color', function (model, value) {
436 this.update_attr('color', value); }, this);
434 this.update_attr('color', value); }, this);
437
435
438 this.model.on('change:background_color', function (model, value) {
436 this.model.on('change:background_color', function (model, value) {
439 this.update_attr('background', value); }, this);
437 this.update_attr('background', value); }, this);
440
438
441 this.model.on('change:width', function (model, value) {
439 this.model.on('change:width', function (model, value) {
442 this.update_attr('width', value); }, this);
440 this.update_attr('width', value); }, this);
443
441
444 this.model.on('change:height', function (model, value) {
442 this.model.on('change:height', function (model, value) {
445 this.update_attr('height', value); }, this);
443 this.update_attr('height', value); }, this);
446
444
447 this.model.on('change:border_color', function (model, value) {
445 this.model.on('change:border_color', function (model, value) {
448 this.update_attr('border-color', value); }, this);
446 this.update_attr('border-color', value); }, this);
449
447
450 this.model.on('change:border_width', function (model, value) {
448 this.model.on('change:border_width', function (model, value) {
451 this.update_attr('border-width', value); }, this);
449 this.update_attr('border-width', value); }, this);
452
450
453 this.model.on('change:border_style', function (model, value) {
451 this.model.on('change:border_style', function (model, value) {
454 this.update_attr('border-style', value); }, this);
452 this.update_attr('border-style', value); }, this);
455
453
456 this.model.on('change:font_style', function (model, value) {
454 this.model.on('change:font_style', function (model, value) {
457 this.update_attr('font-style', value); }, this);
455 this.update_attr('font-style', value); }, this);
458
456
459 this.model.on('change:font_weight', function (model, value) {
457 this.model.on('change:font_weight', function (model, value) {
460 this.update_attr('font-weight', value); }, this);
458 this.update_attr('font-weight', value); }, this);
461
459
462 this.model.on('change:font_size', function (model, value) {
460 this.model.on('change:font_size', function (model, value) {
463 this.update_attr('font-size', this._default_px(value)); }, this);
461 this.update_attr('font-size', this._default_px(value)); }, this);
464
462
465 this.model.on('change:font_family', function (model, value) {
463 this.model.on('change:font_family', function (model, value) {
466 this.update_attr('font-family', value); }, this);
464 this.update_attr('font-family', value); }, this);
467
465
468 this.model.on('change:padding', function (model, value) {
466 this.model.on('change:padding', function (model, value) {
469 this.update_attr('padding', value); }, this);
467 this.update_attr('padding', value); }, this);
470
468
471 this.model.on('change:margin', function (model, value) {
469 this.model.on('change:margin', function (model, value) {
472 this.update_attr('margin', this._default_px(value)); }, this);
470 this.update_attr('margin', this._default_px(value)); }, this);
473
471
474 this.model.on('change:border_radius', function (model, value) {
472 this.model.on('change:border_radius', function (model, value) {
475 this.update_attr('border-radius', this._default_px(value)); }, this);
473 this.update_attr('border-radius', this._default_px(value)); }, this);
476
474
477 this.after_displayed(function() {
475 this.after_displayed(function() {
478 this.update_visible(this.model, this.model.get("visible"));
476 this.update_visible(this.model, this.model.get("visible"));
479 this.update_classes([], this.model.get('_dom_classes'));
477 this.update_classes([], this.model.get('_dom_classes'));
480
478
481 this.update_attr('color', this.model.get('color'));
479 this.update_attr('color', this.model.get('color'));
482 this.update_attr('background', this.model.get('background_color'));
480 this.update_attr('background', this.model.get('background_color'));
483 this.update_attr('width', this.model.get('width'));
481 this.update_attr('width', this.model.get('width'));
484 this.update_attr('height', this.model.get('height'));
482 this.update_attr('height', this.model.get('height'));
485 this.update_attr('border-color', this.model.get('border_color'));
483 this.update_attr('border-color', this.model.get('border_color'));
486 this.update_attr('border-width', this.model.get('border_width'));
484 this.update_attr('border-width', this.model.get('border_width'));
487 this.update_attr('border-style', this.model.get('border_style'));
485 this.update_attr('border-style', this.model.get('border_style'));
488 this.update_attr('font-style', this.model.get('font_style'));
486 this.update_attr('font-style', this.model.get('font_style'));
489 this.update_attr('font-weight', this.model.get('font_weight'));
487 this.update_attr('font-weight', this.model.get('font_weight'));
490 this.update_attr('font-size', this.model.get('font_size'));
488 this.update_attr('font-size', this.model.get('font_size'));
491 this.update_attr('font-family', this.model.get('font_family'));
489 this.update_attr('font-family', this.model.get('font_family'));
492 this.update_attr('padding', this.model.get('padding'));
490 this.update_attr('padding', this.model.get('padding'));
493 this.update_attr('margin', this.model.get('margin'));
491 this.update_attr('margin', this.model.get('margin'));
494 this.update_attr('border-radius', this.model.get('border_radius'));
492 this.update_attr('border-radius', this.model.get('border_radius'));
495
493
496 this.update_css(this.model, this.model.get("_css"));
494 this.update_css(this.model, this.model.get("_css"));
497 }, this);
495 }, this);
498 },
496 },
499
497
500 _default_px: function(value) {
498 _default_px: function(value) {
501 // Makes browser interpret a numerical string as a pixel value.
499 // Makes browser interpret a numerical string as a pixel value.
502 if (/^\d+\.?(\d+)?$/.test(value.trim())) {
500 if (/^\d+\.?(\d+)?$/.test(value.trim())) {
503 return value.trim() + 'px';
501 return value.trim() + 'px';
504 }
502 }
505 return value;
503 return value;
506 },
504 },
507
505
508 update_attr: function(name, value) {
506 update_attr: function(name, value) {
509 // Set a css attr of the widget view.
507 // Set a css attr of the widget view.
510 this.$el.css(name, value);
508 this.$el.css(name, value);
511 },
509 },
512
510
513 update_visible: function(model, value) {
511 update_visible: function(model, value) {
514 // Update visibility
512 // Update visibility
515 this.$el.toggle(value);
513 this.$el.toggle(value);
516 },
514 },
517
515
518 update_css: function (model, css) {
516 update_css: function (model, css) {
519 // Update the css styling of this view.
517 // Update the css styling of this view.
520 var e = this.$el;
518 var e = this.$el;
521 if (css === undefined) {return;}
519 if (css === undefined) {return;}
522 for (var i = 0; i < css.length; i++) {
520 for (var i = 0; i < css.length; i++) {
523 // Apply the css traits to all elements that match the selector.
521 // Apply the css traits to all elements that match the selector.
524 var selector = css[i][0];
522 var selector = css[i][0];
525 var elements = this._get_selector_element(selector);
523 var elements = this._get_selector_element(selector);
526 if (elements.length > 0) {
524 if (elements.length > 0) {
527 var trait_key = css[i][1];
525 var trait_key = css[i][1];
528 var trait_value = css[i][2];
526 var trait_value = css[i][2];
529 elements.css(trait_key ,trait_value);
527 elements.css(trait_key ,trait_value);
530 }
528 }
531 }
529 }
532 },
530 },
533
531
534 update_classes: function (old_classes, new_classes, $el) {
532 update_classes: function (old_classes, new_classes, $el) {
535 // Update the DOM classes applied to an element, default to this.$el.
533 // Update the DOM classes applied to an element, default to this.$el.
536 if ($el===undefined) {
534 if ($el===undefined) {
537 $el = this.$el;
535 $el = this.$el;
538 }
536 }
539 this.do_diff(old_classes, new_classes, function(removed) {
537 this.do_diff(old_classes, new_classes, function(removed) {
540 $el.removeClass(removed);
538 $el.removeClass(removed);
541 }, function(added) {
539 }, function(added) {
542 $el.addClass(added);
540 $el.addClass(added);
543 });
541 });
544 },
542 },
545
543
546 update_mapped_classes: function(class_map, trait_name, previous_trait_value, $el) {
544 update_mapped_classes: function(class_map, trait_name, previous_trait_value, $el) {
547 // Update the DOM classes applied to the widget based on a single
545 // Update the DOM classes applied to the widget based on a single
548 // trait's value.
546 // trait's value.
549 //
547 //
550 // Given a trait value classes map, this function automatically
548 // Given a trait value classes map, this function automatically
551 // handles applying the appropriate classes to the widget element
549 // handles applying the appropriate classes to the widget element
552 // and removing classes that are no longer valid.
550 // and removing classes that are no longer valid.
553 //
551 //
554 // Parameters
552 // Parameters
555 // ----------
553 // ----------
556 // class_map: dictionary
554 // class_map: dictionary
557 // Dictionary of trait values to class lists.
555 // Dictionary of trait values to class lists.
558 // Example:
556 // Example:
559 // {
557 // {
560 // success: ['alert', 'alert-success'],
558 // success: ['alert', 'alert-success'],
561 // info: ['alert', 'alert-info'],
559 // info: ['alert', 'alert-info'],
562 // warning: ['alert', 'alert-warning'],
560 // warning: ['alert', 'alert-warning'],
563 // danger: ['alert', 'alert-danger']
561 // danger: ['alert', 'alert-danger']
564 // };
562 // };
565 // trait_name: string
563 // trait_name: string
566 // Name of the trait to check the value of.
564 // Name of the trait to check the value of.
567 // previous_trait_value: optional string, default ''
565 // previous_trait_value: optional string, default ''
568 // Last trait value
566 // Last trait value
569 // $el: optional jQuery element handle, defaults to this.$el
567 // $el: optional jQuery element handle, defaults to this.$el
570 // Element that the classes are applied to.
568 // Element that the classes are applied to.
571 var key = previous_trait_value;
569 var key = previous_trait_value;
572 if (key === undefined) {
570 if (key === undefined) {
573 key = this.model.previous(trait_name);
571 key = this.model.previous(trait_name);
574 }
572 }
575 var old_classes = class_map[key] ? class_map[key] : [];
573 var old_classes = class_map[key] ? class_map[key] : [];
576 key = this.model.get(trait_name);
574 key = this.model.get(trait_name);
577 var new_classes = class_map[key] ? class_map[key] : [];
575 var new_classes = class_map[key] ? class_map[key] : [];
578
576
579 this.update_classes(old_classes, new_classes, $el || this.$el);
577 this.update_classes(old_classes, new_classes, $el || this.$el);
580 },
578 },
581
579
582 _get_selector_element: function (selector) {
580 _get_selector_element: function (selector) {
583 // Get the elements via the css selector.
581 // Get the elements via the css selector.
584 var elements;
582 var elements;
585 if (!selector) {
583 if (!selector) {
586 elements = this.$el;
584 elements = this.$el;
587 } else {
585 } else {
588 elements = this.$el.find(selector).addBack(selector);
586 elements = this.$el.find(selector).addBack(selector);
589 }
587 }
590 return elements;
588 return elements;
591 },
589 },
592 });
590 });
593
591
594
592
595 var ViewList = function(create_view, remove_view, context) {
593 var ViewList = function(create_view, remove_view, context) {
596 // * create_view and remove_view are default functions called when adding or removing views
594 // * create_view and remove_view are default functions called when adding or removing views
597 // * create_view takes a model and returns a view or a promise for a view for that model
595 // * create_view takes a model and returns a view or a promise for a view for that model
598 // * remove_view takes a view and destroys it (including calling `view.remove()`)
596 // * remove_view takes a view and destroys it (including calling `view.remove()`)
599 // * each time the update() function is called with a new list, the create and remove
597 // * each time the update() function is called with a new list, the create and remove
600 // callbacks will be called in an order so that if you append the views created in the
598 // callbacks will be called in an order so that if you append the views created in the
601 // create callback and remove the views in the remove callback, you will duplicate
599 // create callback and remove the views in the remove callback, you will duplicate
602 // the order of the list.
600 // the order of the list.
603 // * the remove callback defaults to just removing the view (e.g., pass in null for the second parameter)
601 // * the remove callback defaults to just removing the view (e.g., pass in null for the second parameter)
604 // * the context defaults to the created ViewList. If you pass another context, the create and remove
602 // * the context defaults to the created ViewList. If you pass another context, the create and remove
605 // will be called in that context.
603 // will be called in that context.
606
604
607 this.initialize.apply(this, arguments);
605 this.initialize.apply(this, arguments);
608 }
606 };
609
607
610 _.extend(ViewList.prototype, {
608 _.extend(ViewList.prototype, {
611 initialize: function(create_view, remove_view, context) {
609 initialize: function(create_view, remove_view, context) {
612 this.state_change = Promise.resolve();
610 this.state_change = Promise.resolve();
613 this._handler_context = context || this;
611 this._handler_context = context || this;
614 this._models = [];
612 this._models = [];
615 this.views = [];
613 this.views = [];
616 this._create_view = create_view;
614 this._create_view = create_view;
617 this._remove_view = remove_view || function(view) {view.remove();};
615 this._remove_view = remove_view || function(view) {view.remove();};
618 },
616 },
619
617
620 update: function(new_models, create_view, remove_view, context) {
618 update: function(new_models, create_view, remove_view, context) {
621 // the create_view, remove_view, and context arguments override the defaults
619 // the create_view, remove_view, and context arguments override the defaults
622 // specified when the list is created.
620 // specified when the list is created.
623 // returns a promise that resolves after this update is done
621 // returns a promise that resolves after this update is done
624 var remove = remove_view || this._remove_view;
622 var remove = remove_view || this._remove_view;
625 var create = create_view || this._create_view;
623 var create = create_view || this._create_view;
626 var context = context || this._handler_context;
624 var context = context || this._handler_context;
627 var added_views = [];
625 var added_views = [];
628 var that = this;
626 var that = this;
629 this.state_change = this.state_change.then(function() {
627 this.state_change = this.state_change.then(function() {
630 var i;
628 var i;
631 // first, skip past the beginning of the lists if they are identical
629 // first, skip past the beginning of the lists if they are identical
632 for (i = 0; i < new_models.length; i++) {
630 for (i = 0; i < new_models.length; i++) {
633 if (i >= that._models.length || new_models[i] !== that._models[i]) {
631 if (i >= that._models.length || new_models[i] !== that._models[i]) {
634 break;
632 break;
635 }
633 }
636 }
634 }
637 var first_removed = i;
635 var first_removed = i;
638 // Remove the non-matching items from the old list.
636 // Remove the non-matching items from the old list.
639 for (var j = first_removed; j < that._models.length; j++) {
637 for (var j = first_removed; j < that._models.length; j++) {
640 remove.call(context, that.views[j]);
638 remove.call(context, that.views[j]);
641 }
639 }
642
640
643 // Add the rest of the new list items.
641 // Add the rest of the new list items.
644 for (; i < new_models.length; i++) {
642 for (; i < new_models.length; i++) {
645 added_views.push(create.call(context, new_models[i]));
643 added_views.push(create.call(context, new_models[i]));
646 }
644 }
647 // make a copy of the input array
645 // make a copy of the input array
648 that._models = new_models.slice();
646 that._models = new_models.slice();
649 return Promise.all(added_views, function(added) {
647 return Promise.all(added_views, function(added) {
650 that.views = that.views.slice(0,first_removed).concat(added);
648 that.views = that.views.slice(0,first_removed).concat(added);
651 });
649 });
652 });
650 });
653 return this.state_change;
651 return this.state_change;
654 },
652 },
655
653
656 remove: function() {
654 remove: function() {
657 // removes every view in the list; convenience function for `.update([])`
655 // removes every view in the list; convenience function for `.update([])`
658 // that should be faster
656 // that should be faster
659 // returns a promise that resolves after this removal is done
657 // returns a promise that resolves after this removal is done
660 var that = this;
658 var that = this;
661 this.state_change = this.state_change.then(function() {
659 this.state_change = this.state_change.then(function() {
662 for (var i = 0, len=that.views.length; i <len; i++) {
660 for (var i = 0, len=that.views.length; i <len; i++) {
663 that._remove_view.call(that._handler_context, that.views[i]);
661 that._remove_view.call(that._handler_context, that.views[i]);
664 };
662 }
665 that._models = [];
663 that._models = [];
666 that.views = [];
664 that.views = [];
667 });
665 });
668 return this.state_change;
666 return this.state_change;
669 },
667 },
670 });
668 });
671
669
672 var widget = {
670 var widget = {
673 'WidgetModel': WidgetModel,
671 'WidgetModel': WidgetModel,
674 'WidgetView': WidgetView,
672 'WidgetView': WidgetView,
675 'DOMWidgetView': DOMWidgetView,
673 'DOMWidgetView': DOMWidgetView,
676 'ViewList': ViewList,
674 'ViewList': ViewList,
677 };
675 };
678
676
679 // For backwards compatability.
677 // For backwards compatability.
680 $.extend(IPython, widget);
678 $.extend(IPython, widget);
681
679
682 return widget;
680 return widget;
683 });
681 });
@@ -1,263 +1,264
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([
4 define([
5 "widgets/js/widget",
5 "widgets/js/widget",
6 "base/js/utils",
6 "base/js/utils",
7 "jquery",
7 "jquery",
8 "bootstrap",
8 "bootstrap",
9 ], function(widget, utils, $){
9 ], function(widget, utils, $){
10
10
11 var AccordionView = widget.DOMWidgetView.extend({
11 var AccordionView = widget.DOMWidgetView.extend({
12 initialize: function(){
13 AccordionView.__super__.initialize.apply(this, arguments);
14
15 this.containers = [];
16 this.model_containers = {};
17 this.children_views = new widget.ViewList(this.add_child_model, this.remove_child_model, this);
18 this.listenTo(this.model, 'change:children', function(model, value) {
19 this.children_views.update(value);
20 }, this);
21 },
22
12 render: function(){
23 render: function(){
13 // Called when view is rendered.
24 // Called when view is rendered.
14 var guid = 'panel-group' + utils.uuid();
25 var guid = 'panel-group' + utils.uuid();
15 this.$el
26 this.$el
16 .attr('id', guid)
27 .attr('id', guid)
17 .addClass('panel-group');
28 .addClass('panel-group');
18 this.containers = [];
19 this.model_containers = {};
20 this.update_children([], this.model.get('children'));
21 this.model.on('change:children', function(model, value, options) {
22 this.update_children(model.previous('children'), value);
23 }, this);
24 this.model.on('change:selected_index', function(model, value, options) {
29 this.model.on('change:selected_index', function(model, value, options) {
25 this.update_selected_index(model.previous('selected_index'), value, options);
30 this.update_selected_index(model.previous('selected_index'), value, options);
26 }, this);
31 }, this);
27 this.model.on('change:_titles', function(model, value, options) {
32 this.model.on('change:_titles', function(model, value, options) {
28 this.update_titles(value);
33 this.update_titles(value);
29 }, this);
34 }, this);
30 var that = this;
35 var that = this;
31 this.on('displayed', function() {
36 this.on('displayed', function() {
32 this.update_titles();
37 this.update_titles();
33 }, this);
38 }, this);
39 this.children_views.update(this.model.get('children'));
34 },
40 },
35
41
36 update_titles: function(titles) {
42 update_titles: function(titles) {
37 // Set tab titles
43 // Set tab titles
38 if (!titles) {
44 if (!titles) {
39 titles = this.model.get('_titles');
45 titles = this.model.get('_titles');
40 }
46 }
41
47
42 var that = this;
48 var that = this;
43 _.each(titles, function(title, page_index) {
49 _.each(titles, function(title, page_index) {
44 var accordian = that.containers[page_index];
50 var accordian = that.containers[page_index];
45 if (accordian !== undefined) {
51 if (accordian !== undefined) {
46 accordian
52 accordian
47 .find('.panel-heading')
53 .find('.panel-heading')
48 .find('.accordion-toggle')
54 .find('.accordion-toggle')
49 .text(title);
55 .text(title);
50 }
56 }
51 });
57 });
52 },
58 },
53
59
54 update_selected_index: function(old_index, new_index, options) {
60 update_selected_index: function(old_index, new_index, options) {
55 // Only update the selection if the selection wasn't triggered
61 // Only update the selection if the selection wasn't triggered
56 // by the front-end. It must be triggered by the back-end.
62 // by the front-end. It must be triggered by the back-end.
57 if (options === undefined || options.updated_view != this) {
63 if (options === undefined || options.updated_view != this) {
58 this.containers[old_index].find('.panel-collapse').collapse('hide');
64 this.containers[old_index].find('.panel-collapse').collapse('hide');
59 if (0 <= new_index && new_index < this.containers.length) {
65 if (0 <= new_index && new_index < this.containers.length) {
60 this.containers[new_index].find('.panel-collapse').collapse('show');
66 this.containers[new_index].find('.panel-collapse').collapse('show');
61 }
67 }
62 }
68 }
63 },
69 },
64
70
65 update_children: function(old_list, new_list) {
66 // Called when the children list is modified.
67 this.do_diff(old_list,
68 new_list,
69 $.proxy(this.remove_child_model, this),
70 $.proxy(this.add_child_model, this));
71 },
72
73 remove_child_model: function(model) {
71 remove_child_model: function(model) {
74 // Called when a child is removed from children list.
72 // Called when a child is removed from children list.
75 var accordion_group = this.model_containers[model.id];
73 var accordion_group = this.model_containers[model.id];
76 this.containers.splice(accordion_group.container_index, 1);
74 this.containers.splice(accordion_group.container_index, 1);
77 delete this.model_containers[model.id];
75 delete this.model_containers[model.id];
78 accordion_group.remove();
76 accordion_group.remove();
79 this.pop_child_view(model);
77 this.pop_child_view(model);
80 },
78 },
81
79
82 add_child_model: function(model) {
80 add_child_model: function(model) {
83 // Called when a child is added to children list.
81 // Called when a child is added to children list.
84 var index = this.containers.length;
82 var index = this.containers.length;
85 var uuid = utils.uuid();
83 var uuid = utils.uuid();
86 var accordion_group = $('<div />')
84 var accordion_group = $('<div />')
87 .addClass('panel panel-default')
85 .addClass('panel panel-default')
88 .appendTo(this.$el);
86 .appendTo(this.$el);
89 var accordion_heading = $('<div />')
87 var accordion_heading = $('<div />')
90 .addClass('panel-heading')
88 .addClass('panel-heading')
91 .appendTo(accordion_group);
89 .appendTo(accordion_group);
92 var that = this;
90 var that = this;
93 var accordion_toggle = $('<a />')
91 var accordion_toggle = $('<a />')
94 .addClass('accordion-toggle')
92 .addClass('accordion-toggle')
95 .attr('data-toggle', 'collapse')
93 .attr('data-toggle', 'collapse')
96 .attr('data-parent', '#' + this.$el.attr('id'))
94 .attr('data-parent', '#' + this.$el.attr('id'))
97 .attr('href', '#' + uuid)
95 .attr('href', '#' + uuid)
98 .click(function(evt){
96 .click(function(evt){
99
97
100 // Calling model.set will trigger all of the other views of the
98 // Calling model.set will trigger all of the other views of the
101 // model to update.
99 // model to update.
102 that.model.set("selected_index", index, {updated_view: that});
100 that.model.set("selected_index", index, {updated_view: that});
103 that.touch();
101 that.touch();
104 })
102 })
105 .text('Page ' + index)
103 .text('Page ' + index)
106 .appendTo(accordion_heading);
104 .appendTo(accordion_heading);
107 var accordion_body = $('<div />', {id: uuid})
105 var accordion_body = $('<div />', {id: uuid})
108 .addClass('panel-collapse collapse')
106 .addClass('panel-collapse collapse')
109 .appendTo(accordion_group);
107 .appendTo(accordion_group);
110 var accordion_inner = $('<div />')
108 var accordion_inner = $('<div />')
111 .addClass('panel-body')
109 .addClass('panel-body')
112 .appendTo(accordion_body);
110 .appendTo(accordion_body);
113 var container_index = this.containers.push(accordion_group) - 1;
111 var container_index = this.containers.push(accordion_group) - 1;
114 accordion_group.container_index = container_index;
112 accordion_group.container_index = container_index;
115 this.model_containers[model.id] = accordion_group;
113 this.model_containers[model.id] = accordion_group;
116
114
117 var dummy = $('<div/>');
115 var dummy = $('<div/>');
118 accordion_inner.append(dummy);
116 accordion_inner.append(dummy);
119 return this.create_child_view(model).then(function(view) {
117 return this.create_child_view(model).then(function(view) {
120 dummy.replaceWith(view.$el);
118 dummy.replaceWith(view.$el);
121 that.update();
119 that.update();
122 that.update_titles();
120 that.update_titles();
123
121
124 // Trigger the displayed event of the child view.
122 // Trigger the displayed event of the child view.
125 that.after_displayed(function() {
123 that.after_displayed(function() {
126 view.trigger('displayed');
124 view.trigger('displayed');
127 });
125 });
128 return view;
126 return view;
129 }, utils.reject("Couldn't add child view to box", true));
127 }, utils.reject("Couldn't add child view to box", true));
130 },
128 },
129
130 remove: function() {
131 AccordionView.__super__.remove.apply(this, arguments);
132 this.children_views.remove();
133 },
131 });
134 });
132
135
133
136
134 var TabView = widget.DOMWidgetView.extend({
137 var TabView = widget.DOMWidgetView.extend({
135 initialize: function() {
138 initialize: function() {
136 // Public constructor.
139 // Public constructor.
137 this.containers = [];
138 TabView.__super__.initialize.apply(this, arguments);
140 TabView.__super__.initialize.apply(this, arguments);
141
142 this.containers = [];
143 this.children_views = new widget.ViewList(this.add_child_model, this.remove_child_model, this);
144 this.listenTo(this.model, 'change:children', function(model, value) {
145 this.children_views.update(value);
146 }, this);
139 },
147 },
140
148
141 render: function(){
149 render: function(){
142 // Called when view is rendered.
150 // Called when view is rendered.
143 var uuid = 'tabs'+utils.uuid();
151 var uuid = 'tabs'+utils.uuid();
144 var that = this;
152 var that = this;
145 this.$tabs = $('<div />', {id: uuid})
153 this.$tabs = $('<div />', {id: uuid})
146 .addClass('nav')
154 .addClass('nav')
147 .addClass('nav-tabs')
155 .addClass('nav-tabs')
148 .appendTo(this.$el);
156 .appendTo(this.$el);
149 this.$tab_contents = $('<div />', {id: uuid + 'Content'})
157 this.$tab_contents = $('<div />', {id: uuid + 'Content'})
150 .addClass('tab-content')
158 .addClass('tab-content')
151 .appendTo(this.$el);
159 .appendTo(this.$el);
152 this.containers = [];
160 this.children_views.update(this.model.get('children'));
153 this.update_children([], this.model.get('children'));
154 this.model.on('change:children', function(model, value, options) {
155 this.update_children(model.previous('children'), value);
156 }, this);
157 },
161 },
158
162
159 update_attr: function(name, value) {
163 update_attr: function(name, value) {
160 // Set a css attr of the widget view.
164 // Set a css attr of the widget view.
161 this.$tabs.css(name, value);
165 this.$tabs.css(name, value);
162 },
166 },
163
167
164 update_children: function(old_list, new_list) {
165 // Called when the children list is modified.
166 this.do_diff(old_list,
167 new_list,
168 $.proxy(this.remove_child_model, this),
169 $.proxy(this.add_child_model, this));
170 },
171
172 remove_child_model: function(model) {
168 remove_child_model: function(model) {
173 // Called when a child is removed from children list.
169 // Called when a child is removed from children list.
174 var view = this.pop_child_view(model);
170 var view = this.pop_child_view(model);
175 this.containers.splice(view.parent_tab.tab_text_index, 1);
171 this.containers.splice(view.parent_tab.tab_text_index, 1);
176 view.parent_tab.remove();
172 view.parent_tab.remove();
177 view.parent_container.remove();
173 view.parent_container.remove();
178 view.remove();
174 view.remove();
179 },
175 },
180
176
181 add_child_model: function(model) {
177 add_child_model: function(model) {
182 // Called when a child is added to children list.
178 // Called when a child is added to children list.
183 var index = this.containers.length;
179 var index = this.containers.length;
184 var uuid = utils.uuid();
180 var uuid = utils.uuid();
185
181
186 var that = this;
182 var that = this;
187 var tab = $('<li />')
183 var tab = $('<li />')
188 .css('list-style-type', 'none')
184 .css('list-style-type', 'none')
189 .appendTo(this.$tabs);
185 .appendTo(this.$tabs);
190
186
191
187
192 var tab_text = $('<a />')
188 var tab_text = $('<a />')
193 .attr('href', '#' + uuid)
189 .attr('href', '#' + uuid)
194 .attr('data-toggle', 'tab')
190 .attr('data-toggle', 'tab')
195 .text('Page ' + index)
191 .text('Page ' + index)
196 .appendTo(tab)
192 .appendTo(tab)
197 .click(function (e) {
193 .click(function (e) {
198
194
199 // Calling model.set will trigger all of the other views of the
195 // Calling model.set will trigger all of the other views of the
200 // model to update.
196 // model to update.
201 that.model.set("selected_index", index, {updated_view: that});
197 that.model.set("selected_index", index, {updated_view: that});
202 that.touch();
198 that.touch();
203 that.select_page(index);
199 that.select_page(index);
204 });
200 });
205 tab.tab_text_index = that.containers.push(tab_text) - 1;
201 tab.tab_text_index = that.containers.push(tab_text) - 1;
206
202
207 var dummy = $('<div />');
203 var dummy = $('<div />');
208 var contents_div = $('<div />', {id: uuid})
204 var contents_div = $('<div />', {id: uuid})
209 .addClass('tab-pane')
205 .addClass('tab-pane')
210 .addClass('fade')
206 .addClass('fade')
211 .append(dummy)
207 .append(dummy)
212 .appendTo(that.$tab_contents);
208 .appendTo(that.$tab_contents);
213
209
214 return this.create_child_view(model).then(function(view) {
210 return this.create_child_view(model).then(function(view) {
215 dummy.replaceWith(view.$el);
211 dummy.replaceWith(view.$el);
216 view.parent_tab = tab;
212 view.parent_tab = tab;
217 view.parent_container = contents_div;
213 view.parent_container = contents_div;
218
214
219 // Trigger the displayed event of the child view.
215 // Trigger the displayed event of the child view.
220 that.after_displayed(function() {
216 that.after_displayed(function() {
221 view.trigger('displayed');
217 view.trigger('displayed');
222 });
218 });
223 return view;
219 return view;
224 }, utils.reject("Couldn't add child view to box", true));
220 }, utils.reject("Couldn't add child view to box", true));
225 },
221 },
226
222
227 update: function(options) {
223 update: function(options) {
228 // Update the contents of this view
224 // Update the contents of this view
229 //
225 //
230 // Called when the model is changed. The model may have been
226 // Called when the model is changed. The model may have been
231 // changed by another view or by a state update from the back-end.
227 // changed by another view or by a state update from the back-end.
232 if (options === undefined || options.updated_view != this) {
228 if (options === undefined || options.updated_view != this) {
233 // Set tab titles
229 // Set tab titles
234 var titles = this.model.get('_titles');
230 var titles = this.model.get('_titles');
235 var that = this;
231 var that = this;
236 _.each(titles, function(title, page_index) {
232 _.each(titles, function(title, page_index) {
237 var tab_text = that.containers[page_index];
233 var tab_text = that.containers[page_index];
238 if (tab_text !== undefined) {
234 if (tab_text !== undefined) {
239 tab_text.text(title);
235 tab_text.text(title);
240 }
236 }
241 });
237 });
242
238
243 var selected_index = this.model.get('selected_index');
239 var selected_index = this.model.get('selected_index');
244 if (0 <= selected_index && selected_index < this.containers.length) {
240 if (0 <= selected_index && selected_index < this.containers.length) {
245 this.select_page(selected_index);
241 this.select_page(selected_index);
246 }
242 }
247 }
243 }
248 return TabView.__super__.update.apply(this);
244 return TabView.__super__.update.apply(this);
249 },
245 },
250
246
251 select_page: function(index) {
247 select_page: function(index) {
252 // Select a page.
248 // Select a page.
253 this.$tabs.find('li')
249 this.$tabs.find('li')
254 .removeClass('active');
250 .removeClass('active');
255 this.containers[index].tab('show');
251 this.containers[index].tab('show');
256 },
252 },
253
254 remove: function() {
255 TabView.__super__.remove.apply(this, arguments);
256 this.children_views.remove();
257 },
257 });
258 });
258
259
259 return {
260 return {
260 'AccordionView': AccordionView,
261 'AccordionView': AccordionView,
261 'TabView': TabView,
262 'TabView': TabView,
262 };
263 };
263 });
264 });
General Comments 0
You need to be logged in to leave comments. Login now