##// END OF EJS Templates
Added some small comments to widget code
Jonathan Frederic -
Show More
@@ -1,186 +1,188 b''
1 //----------------------------------------------------------------------------
1 //----------------------------------------------------------------------------
2 // Copyright (C) 2013 The IPython Development Team
2 // Copyright (C) 2013 The IPython Development Team
3 //
3 //
4 // Distributed under the terms of the BSD License. The full license is in
4 // Distributed under the terms of the BSD License. The full license is in
5 // the file COPYING, distributed as part of this software.
5 // the file COPYING, distributed as part of this software.
6 //----------------------------------------------------------------------------
6 //----------------------------------------------------------------------------
7
7
8 //============================================================================
8 //============================================================================
9 // WidgetModel, WidgetView, and WidgetManager
9 // WidgetModel, WidgetView, and WidgetManager
10 //============================================================================
10 //============================================================================
11 /**
11 /**
12 * Base Widget classes
12 * Base Widget classes
13 * @module IPython
13 * @module IPython
14 * @namespace IPython
14 * @namespace IPython
15 * @submodule widget
15 * @submodule widget
16 */
16 */
17
17
18 (function () {
18 (function () {
19 "use strict";
19 "use strict";
20
20
21 // Use require.js 'define' method so that require.js is intelligent enough to
21 // Use require.js 'define' method so that require.js is intelligent enough to
22 // syncronously load everything within this file when it is being 'required'
22 // syncronously load everything within this file when it is being 'required'
23 // elsewhere.
23 // elsewhere.
24 define(["underscore",
24 define(["underscore",
25 "backbone",
25 "backbone",
26 ], function (Underscore, Backbone) {
26 ], function (Underscore, Backbone) {
27
27
28 //--------------------------------------------------------------------
28 //--------------------------------------------------------------------
29 // WidgetManager class
29 // WidgetManager class
30 //--------------------------------------------------------------------
30 //--------------------------------------------------------------------
31 var WidgetManager = function (comm_manager) {
31 var WidgetManager = function (comm_manager) {
32 // Public constructor
32 // Public constructor
33 WidgetManager._managers.push(this);
33 WidgetManager._managers.push(this);
34
34
35 // Attach a comm manager to the
35 // Attach a comm manager to the
36 this.comm_manager = comm_manager;
36 this.comm_manager = comm_manager;
37 this._models = {}; /* Dictionary of model ids and model instances */
37 this._models = {}; /* Dictionary of model ids and model instances */
38
38
39 // Register already-registered widget model types with the comm manager.
39 // Register already-registered widget model types with the comm manager.
40 _.each(WidgetManager._model_types, function(value, key) {
40 _.each(WidgetManager._model_types, function(value, key) {
41 this.comm_manager.register_target(value, $.proxy(this._handle_comm_open, this));
41 this.comm_manager.register_target(value, $.proxy(this._handle_comm_open, this));
42 });
42 });
43 };
43 };
44
44
45 //--------------------------------------------------------------------
45 //--------------------------------------------------------------------
46 // Class level
46 // Class level
47 //--------------------------------------------------------------------
47 //--------------------------------------------------------------------
48 WidgetManager._model_types = {}; /* Dictionary of model type names (target_name) and model types. */
48 WidgetManager._model_types = {}; /* Dictionary of model type names (target_name) and model types. */
49 WidgetManager._view_types = {}; /* Dictionary of view names and view types. */
49 WidgetManager._view_types = {}; /* Dictionary of view names and view types. */
50 WidgetManager._managers = []; /* List of widget managers */
50 WidgetManager._managers = []; /* List of widget managers */
51
51
52 WidgetManager.register_widget_model = function (model_name, model_type) {
52 WidgetManager.register_widget_model = function (model_name, model_type) {
53 // Registers a widget model by name.
53 // Registers a widget model by name.
54 WidgetManager._model_types[model_name] = model_type;
54 WidgetManager._model_types[model_name] = model_type;
55
55
56 // Register the widget with the comm manager. Make sure to pass this object's context
56 // Register the widget with the comm manager. Make sure to pass this object's context
57 // in so `this` works in the call back.
57 // in so `this` works in the call back.
58 _.each(WidgetManager._managers, function(instance, i) {
58 _.each(WidgetManager._managers, function(instance, i) {
59 if (instance.comm_manager !== null) {
59 if (instance.comm_manager !== null) {
60 instance.comm_manager.register_target(model_name, $.proxy(instance._handle_comm_open, instance));
60 instance.comm_manager.register_target(model_name, $.proxy(instance._handle_comm_open, instance));
61 }
61 }
62 });
62 });
63 };
63 };
64
64
65 WidgetManager.register_widget_view = function (view_name, view_type) {
65 WidgetManager.register_widget_view = function (view_name, view_type) {
66 // Registers a widget view by name.
66 // Registers a widget view by name.
67 WidgetManager._view_types[view_name] = view_type;
67 WidgetManager._view_types[view_name] = view_type;
68 };
68 };
69
69
70 //--------------------------------------------------------------------
70 //--------------------------------------------------------------------
71 // Instance level
71 // Instance level
72 //--------------------------------------------------------------------
72 //--------------------------------------------------------------------
73 WidgetManager.prototype.display_view = function(msg, model) {
73 WidgetManager.prototype.display_view = function(msg, model) {
74 var cell = this.get_msg_cell(msg.parent_header.msg_id);
74 var cell = this.get_msg_cell(msg.parent_header.msg_id);
75 if (cell === null) {
75 if (cell === null) {
76 console.log("Could not determine where the display" +
76 console.log("Could not determine where the display" +
77 " message was from. Widget will not be displayed");
77 " message was from. Widget will not be displayed");
78 } else {
78 } else {
79 var view = this.create_view(model, {cell: cell});
79 var view = this.create_view(model, {cell: cell});
80 if (view === null) {
80 if (view === null) {
81 console.error("View creation failed", model);
81 console.error("View creation failed", model);
82 }
82 }
83 if (cell.widget_subarea !== undefined
83 if (cell.widget_subarea !== undefined
84 && cell.widget_subarea !== null) {
84 && cell.widget_subarea !== null) {
85
85
86 cell.widget_area.show();
86 cell.widget_area.show();
87 cell.widget_subarea.append(view.$el);
87 cell.widget_subarea.append(view.$el);
88 }
88 }
89 }
89 }
90 },
90 },
91
91
92 WidgetManager.prototype.create_view = function(model, options) {
92 WidgetManager.prototype.create_view = function(model, options) {
93 var view_name = model.get('view_name');
93 var view_name = model.get('view_name');
94 var ViewType = WidgetManager._view_types[view_name];
94 var ViewType = WidgetManager._view_types[view_name];
95 if (ViewType !== undefined && ViewType !== null) {
95 if (ViewType !== undefined && ViewType !== null) {
96 var parameters = {model: model, options: options};
96 var parameters = {model: model, options: options};
97 var view = new ViewType(parameters);
97 var view = new ViewType(parameters);
98 view.render();
98 view.render();
99 IPython.keyboard_manager.register_events(view.$el);
99 IPython.keyboard_manager.register_events(view.$el);
100 model.views.push(view);
100 model.views.push(view);
101 model.on('destroy', view.remove, view);
101 model.on('destroy', view.remove, view);
102 return view;
102 return view;
103 }
103 }
104 return null;
104 return null;
105 },
105 },
106
106
107 WidgetManager.prototype.get_msg_cell = function (msg_id) {
107 WidgetManager.prototype.get_msg_cell = function (msg_id) {
108 var cell = null;
108 var cell = null;
109 // First, check to see if the msg was triggered by cell execution.
109 // First, check to see if the msg was triggered by cell execution.
110 if (IPython.notebook !== undefined && IPython.notebook !== null) {
110 if (IPython.notebook !== undefined && IPython.notebook !== null) {
111 cell = IPython.notebook.get_msg_cell(msg_id);
111 cell = IPython.notebook.get_msg_cell(msg_id);
112 }
112 }
113 if (cell !== null) {
113 if (cell !== null) {
114 return cell
114 return cell
115 }
115 }
116 // Second, check to see if a get_cell callback was defined
116 // Second, check to see if a get_cell callback was defined
117 // for the message. get_cell callbacks are registered for
117 // for the message. get_cell callbacks are registered for
118 // widget messages, so this block is actually checking to see if the
118 // widget messages, so this block is actually checking to see if the
119 // message was triggered by a widget.
119 // message was triggered by a widget.
120 var kernel = this.comm_manager.kernel;
120 var kernel = this.comm_manager.kernel;
121 if (kernel !== undefined && kernel !== null) {
121 if (kernel !== undefined && kernel !== null) {
122 var callbacks = kernel.get_callbacks_for_msg(msg_id);
122 var callbacks = kernel.get_callbacks_for_msg(msg_id);
123 if (callbacks !== undefined &&
123 if (callbacks !== undefined &&
124 callbacks.iopub !== undefined &&
124 callbacks.iopub !== undefined &&
125 callbacks.iopub.get_cell !== undefined) {
125 callbacks.iopub.get_cell !== undefined) {
126
126
127 return callbacks.iopub.get_cell();
127 return callbacks.iopub.get_cell();
128 }
128 }
129 }
129 }
130
130
131 // Not triggered by a cell or widget (no get_cell callback
131 // Not triggered by a cell or widget (no get_cell callback
132 // exists).
132 // exists).
133 return null;
133 return null;
134 };
134 };
135
135
136 WidgetManager.prototype.callbacks = function (view) {
136 WidgetManager.prototype.callbacks = function (view) {
137 // callback handlers specific a view
137 // callback handlers specific a view
138 var callbacks = {};
138 var callbacks = {};
139 var cell = view.options.cell;
139 var cell = view.options.cell;
140 if (cell !== null) {
140 if (cell !== null) {
141 // Try to get output handlers
141 // Try to get output handlers
142 var handle_output = null;
142 var handle_output = null;
143 var handle_clear_output = null;
143 var handle_clear_output = null;
144 if (cell.output_area !== undefined && cell.output_area !== null) {
144 if (cell.output_area !== undefined && cell.output_area !== null) {
145 handle_output = $.proxy(cell.output_area.handle_output, cell.output_area);
145 handle_output = $.proxy(cell.output_area.handle_output, cell.output_area);
146 handle_clear_output = $.proxy(cell.output_area.handle_clear_output, cell.output_area);
146 handle_clear_output = $.proxy(cell.output_area.handle_clear_output, cell.output_area);
147 }
147 }
148
148
149 // Create callback dict using what is known
149 // Create callback dict using what is known
150 var that = this;
150 var that = this;
151 callbacks = {
151 callbacks = {
152 iopub : {
152 iopub : {
153 output : handle_output,
153 output : handle_output,
154 clear_output : handle_clear_output,
154 clear_output : handle_clear_output,
155
155
156 // Special function only registered by widget messages.
156 // Special function only registered by widget messages.
157 // Allows us to get the cell for a message so we know
157 // Allows us to get the cell for a message so we know
158 // where to add widgets if the code requires it.
158 // where to add widgets if the code requires it.
159 get_cell : function () {
159 get_cell : function () {
160 return cell;
160 return cell;
161 },
161 },
162 },
162 },
163 };
163 };
164 }
164 }
165 return callbacks;
165 return callbacks;
166 };
166 };
167
167
168 WidgetManager.prototype.get_model = function (model_id) {
168 WidgetManager.prototype.get_model = function (model_id) {
169 // Look-up a model instance by its id.
169 var model = this._models[model_id];
170 var model = this._models[model_id];
170 if (model !== undefined && model.id == model_id) {
171 if (model !== undefined && model.id == model_id) {
171 return model;
172 return model;
172 }
173 }
173 return null;
174 return null;
174 };
175 };
175
176
176 WidgetManager.prototype._handle_comm_open = function (comm, msg) {
177 WidgetManager.prototype._handle_comm_open = function (comm, msg) {
178 // Handle when a comm is opened.
177 var model_id = comm.comm_id;
179 var model_id = comm.comm_id;
178 var widget_type_name = msg.content.target_name;
180 var widget_type_name = msg.content.target_name;
179 var widget_model = new WidgetManager._model_types[widget_type_name](this, model_id, comm);
181 var widget_model = new WidgetManager._model_types[widget_type_name](this, model_id, comm);
180 this._models[model_id] = widget_model;
182 this._models[model_id] = widget_model;
181 };
183 };
182
184
183 IPython.WidgetManager = WidgetManager;
185 IPython.WidgetManager = WidgetManager;
184 return IPython.WidgetManager;
186 return IPython.WidgetManager;
185 });
187 });
186 }());
188 }());
@@ -1,407 +1,407 b''
1 //----------------------------------------------------------------------------
1 //----------------------------------------------------------------------------
2 // Copyright (C) 2013 The IPython Development Team
2 // Copyright (C) 2013 The IPython Development Team
3 //
3 //
4 // Distributed under the terms of the BSD License. The full license is in
4 // Distributed under the terms of the BSD License. The full license is in
5 // the file COPYING, distributed as part of this software.
5 // the file COPYING, distributed as part of this software.
6 //----------------------------------------------------------------------------
6 //----------------------------------------------------------------------------
7
7
8 //============================================================================
8 //============================================================================
9 // Base Widget Model and View classes
9 // Base Widget Model and View classes
10 //============================================================================
10 //============================================================================
11
11
12 /**
12 /**
13 * @module IPython
13 * @module IPython
14 * @namespace IPython
14 * @namespace IPython
15 **/
15 **/
16
16
17 define(["notebook/js/widgetmanager",
17 define(["notebook/js/widgetmanager",
18 "underscore",
18 "underscore",
19 "backbone"],
19 "backbone"],
20 function(WidgetManager, Underscore, Backbone){
20 function(WidgetManager, Underscore, Backbone){
21
21
22 var WidgetModel = Backbone.Model.extend({
22 var WidgetModel = Backbone.Model.extend({
23 constructor: function (widget_manager, model_id, comm) {
23 constructor: function (widget_manager, model_id, comm) {
24 // Construcctor
24 // Construcctor
25 //
25 //
26 // Creates a WidgetModel instance.
26 // Creates a WidgetModel instance.
27 //
27 //
28 // Parameters
28 // Parameters
29 // ----------
29 // ----------
30 // widget_manager : WidgetManager instance
30 // widget_manager : WidgetManager instance
31 // model_id : string
31 // model_id : string
32 // An ID unique to this model.
32 // An ID unique to this model.
33 // comm : Comm instance (optional)
33 // comm : Comm instance (optional)
34 this.widget_manager = widget_manager;
34 this.widget_manager = widget_manager;
35 this.pending_msgs = 0;
35 this.pending_msgs = 0;
36 this.msg_throttle = 2;
36 this.msg_throttle = 2;
37 this.msg_buffer = null;
37 this.msg_buffer = null;
38 this.key_value_lock = null;
38 this.key_value_lock = null;
39 this.id = model_id;
39 this.id = model_id;
40 this.views = [];
40 this.views = [];
41
41
42 if (comm !== undefined) {
42 if (comm !== undefined) {
43 // Remember comm associated with the model.
43 // Remember comm associated with the model.
44 this.comm = comm;
44 this.comm = comm;
45 comm.model = this;
45 comm.model = this;
46
46
47 // Hook comm messages up to model.
47 // Hook comm messages up to model.
48 comm.on_close($.proxy(this._handle_comm_closed, this));
48 comm.on_close($.proxy(this._handle_comm_closed, this));
49 comm.on_msg($.proxy(this._handle_comm_msg, this));
49 comm.on_msg($.proxy(this._handle_comm_msg, this));
50 }
50 }
51 return Backbone.Model.apply(this);
51 return Backbone.Model.apply(this);
52 },
52 },
53
53
54 send: function (content, callbacks) {
54 send: function (content, callbacks) {
55 // Send a custom msg over the comm.
55 // Send a custom msg over the comm.
56 if (this.comm !== undefined) {
56 if (this.comm !== undefined) {
57 var data = {method: 'custom', content: content};
57 var data = {method: 'custom', content: content};
58 this.comm.send(data, callbacks);
58 this.comm.send(data, callbacks);
59 }
59 }
60 },
60 },
61
61
62 _handle_comm_closed: function (msg) {
62 _handle_comm_closed: function (msg) {
63 // Handle when a widget is closed.
63 // Handle when a widget is closed.
64 this.trigger('comm:close');
64 this.trigger('comm:close');
65 delete this.comm.model; // Delete ref so GC will collect widget model.
65 delete this.comm.model; // Delete ref so GC will collect widget model.
66 delete this.comm;
66 delete this.comm;
67 delete this.model_id; // Delete id from model so widget manager cleans up.
67 delete this.model_id; // Delete id from model so widget manager cleans up.
68 // TODO: Handle deletion, like this.destroy(), and delete views, etc.
68 // TODO: Handle deletion, like this.destroy(), and delete views, etc.
69 },
69 },
70
70
71 _handle_comm_msg: function (msg) {
71 _handle_comm_msg: function (msg) {
72 // Handle incoming comm msg.
72 // Handle incoming comm msg.
73 var method = msg.content.data.method;
73 var method = msg.content.data.method;
74 switch (method) {
74 switch (method) {
75 case 'update':
75 case 'update':
76 this.apply_update(msg.content.data.state);
76 this.apply_update(msg.content.data.state);
77 break;
77 break;
78 case 'custom':
78 case 'custom':
79 this.trigger('msg:custom', msg.content.data.content);
79 this.trigger('msg:custom', msg.content.data.content);
80 break;
80 break;
81 case 'display':
81 case 'display':
82 this.widget_manager.display_view(msg, this);
82 this.widget_manager.display_view(msg, this);
83 break;
83 break;
84 }
84 }
85 },
85 },
86
86
87 apply_update: function (state) {
87 apply_update: function (state) {
88 // Handle when a widget is updated via the python side.
88 // Handle when a widget is updated via the python side.
89 _.each(state, function(value, key) {
89 _.each(state, function(value, key) {
90 this.key_value_lock = [key, value];
90 this.key_value_lock = [key, value];
91 try {
91 try {
92 this.set(key, this._unpack_models(value));
92 this.set(key, this._unpack_models(value));
93 } finally {
93 } finally {
94 this.key_value_lock = null;
94 this.key_value_lock = null;
95 }
95 }
96 });
96 });
97 },
97 },
98
98
99 _handle_status: function (msg, callbacks) {
99 _handle_status: function (msg, callbacks) {
100 // Handle status msgs.
100 // Handle status msgs.
101
101
102 // execution_state : ('busy', 'idle', 'starting')
102 // execution_state : ('busy', 'idle', 'starting')
103 if (this.comm !== undefined) {
103 if (this.comm !== undefined) {
104 if (msg.content.execution_state ==='idle') {
104 if (msg.content.execution_state ==='idle') {
105 // Send buffer if this message caused another message to be
105 // Send buffer if this message caused another message to be
106 // throttled.
106 // throttled.
107 if (this.msg_buffer !== null &&
107 if (this.msg_buffer !== null &&
108 this.msg_throttle === this.pending_msgs) {
108 this.msg_throttle === this.pending_msgs) {
109 var data = {method: 'backbone', sync_method: 'update', sync_data: this.msg_buffer};
109 var data = {method: 'backbone', sync_method: 'update', sync_data: this.msg_buffer};
110 this.comm.send(data, callbacks);
110 this.comm.send(data, callbacks);
111 this.msg_buffer = null;
111 this.msg_buffer = null;
112 } else {
112 } else {
113 --this.pending_msgs;
113 --this.pending_msgs;
114 }
114 }
115 }
115 }
116 }
116 }
117 },
117 },
118
118
119 callbacks: function(view) {
119 callbacks: function(view) {
120 // Create msg callbacks for a comm msg.
120 // Create msg callbacks for a comm msg.
121 var callbacks = this.widget_manager.callbacks(view);
121 var callbacks = this.widget_manager.callbacks(view);
122
122
123 if (callbacks.iopub === undefined) {
123 if (callbacks.iopub === undefined) {
124 callbacks.iopub = {};
124 callbacks.iopub = {};
125 }
125 }
126
126
127 var that = this;
127 var that = this;
128 callbacks.iopub.status = function (msg) {
128 callbacks.iopub.status = function (msg) {
129 that._handle_status(msg, callbacks);
129 that._handle_status(msg, callbacks);
130 }
130 }
131 return callbacks;
131 return callbacks;
132 },
132 },
133
133
134 sync: function (method, model, options) {
134 sync: function (method, model, options) {
135 // Handle sync to the back-end. Called when a model.save() is called.
135
136
136 // Make sure a comm exists.
137 // Make sure a comm exists.
137 var error = options.error || function() {
138 var error = options.error || function() {
138 console.error('Backbone sync error:', arguments);
139 console.error('Backbone sync error:', arguments);
139 }
140 }
140 if (this.comm === undefined) {
141 if (this.comm === undefined) {
141 error();
142 error();
142 return false;
143 return false;
143 }
144 }
144
145
145 // Delete any key value pairs that the back-end already knows about.
146 // Delete any key value pairs that the back-end already knows about.
146 var attrs = (method === 'patch') ? options.attrs : model.toJSON(options);
147 var attrs = (method === 'patch') ? options.attrs : model.toJSON(options);
147 if (this.key_value_lock !== null) {
148 if (this.key_value_lock !== null) {
148 var key = this.key_value_lock[0];
149 var key = this.key_value_lock[0];
149 var value = this.key_value_lock[1];
150 var value = this.key_value_lock[1];
150 if (attrs[key] === value) {
151 if (attrs[key] === value) {
151 delete attrs[key];
152 delete attrs[key];
152 }
153 }
153 }
154 }
154
155
155 // Only sync if there are attributes to send to the back-end.
156 // Only sync if there are attributes to send to the back-end.
156 if (attr.length > 0) {
157 if (attr.length > 0) {
157 var callbacks = options.callbacks || {};
158 var callbacks = options.callbacks || {};
158 if (this.pending_msgs >= this.msg_throttle) {
159 if (this.pending_msgs >= this.msg_throttle) {
159 // The throttle has been exceeded, buffer the current msg so
160 // The throttle has been exceeded, buffer the current msg so
160 // it can be sent once the kernel has finished processing
161 // it can be sent once the kernel has finished processing
161 // some of the existing messages.
162 // some of the existing messages.
162
163
163 // Combine updates if it is a 'patch' sync, otherwise replace updates
164 // Combine updates if it is a 'patch' sync, otherwise replace updates
164 switch (method) {
165 switch (method) {
165 case 'patch':
166 case 'patch':
166 this.msg_buffer = $.extend(this.msg_buffer || {}, attrs);
167 this.msg_buffer = $.extend(this.msg_buffer || {}, attrs);
167 break;
168 break;
168 case 'update':
169 case 'update':
169 case 'create':
170 case 'create':
170 this.msg_buffer = attrs;
171 this.msg_buffer = attrs;
171 break;
172 break;
172 default:
173 default:
173 error();
174 error();
174 return false;
175 return false;
175 }
176 }
176 this.msg_buffer_callbacks = callbacks;
177 this.msg_buffer_callbacks = callbacks;
177
178
178 } else {
179 } else {
179 // We haven't exceeded the throttle, send the message like
180 // We haven't exceeded the throttle, send the message like
180 // normal. If this is a patch operation, just send the
181 // normal. If this is a patch operation, just send the
181 // changes.
182 // changes.
182 var data = {method: 'backbone', sync_data: attrs};
183 var data = {method: 'backbone', sync_data: attrs};
183 this.comm.send(data, callbacks);
184 this.comm.send(data, callbacks);
184 this.pending_msgs++;
185 this.pending_msgs++;
185 }
186 }
186 }
187 }
187 // Since the comm is a one-way communication, assume the message
188 // Since the comm is a one-way communication, assume the message
188 // arrived. Don't call success since we don't have a model back from the server
189 // arrived. Don't call success since we don't have a model back from the server
189 // this means we miss out on the 'sync' event.
190 // this means we miss out on the 'sync' event.
190 },
191 },
191
192
192 save_changes: function(callbacks) {
193 save_changes: function(callbacks) {
193 // Push this model's state to the back-end
194 // Push this model's state to the back-end
194 //
195 //
195 // This invokes a Backbone.Sync.
196 // This invokes a Backbone.Sync.
196 this.save(this.changedAttributes(), {patch: true, callbacks: callbacks});
197 this.save(this.changedAttributes(), {patch: true, callbacks: callbacks});
197 },
198 },
198
199
199 _pack_models: function(value) {
200 _pack_models: function(value) {
200 // Replace models with model ids recursively.
201 // Replace models with model ids recursively.
201 if (value instanceof Backbone.Model) {
202 if (value instanceof Backbone.Model) {
202 return value.id;
203 return value.id;
203 } else if (value instanceof Object) {
204 } else if (value instanceof Object) {
204 var packed = {};
205 var packed = {};
205 _.each(value, function(sub_value, key) {
206 _.each(value, function(sub_value, key) {
206 packed[key] = this._pack_models(sub_value);
207 packed[key] = this._pack_models(sub_value);
207 });
208 });
208 return packed;
209 return packed;
209 } else {
210 } else {
210 return value;
211 return value;
211 }
212 }
212 },
213 },
213
214
214 _unpack_models: function(value) {
215 _unpack_models: function(value) {
215 // Replace model ids with models recursively.
216 // Replace model ids with models recursively.
216 if (value instanceof Object) {
217 if (value instanceof Object) {
217 var unpacked = {};
218 var unpacked = {};
218 _.each(value, function(sub_value, key) {
219 _.each(value, function(sub_value, key) {
219 unpacked[key] = this._unpack_models(sub_value);
220 unpacked[key] = this._unpack_models(sub_value);
220 });
221 });
221 return unpacked;
222 return unpacked;
222 } else {
223 } else {
223 var model = this.widget_manager.get_model(value);
224 var model = this.widget_manager.get_model(value);
224 if (model !== null) {
225 if (model !== null) {
225 return model;
226 return model;
226 } else {
227 } else {
227 return value;
228 return value;
228 }
229 }
229 }
230 }
230 },
231 },
231
232
232 });
233 });
233 WidgetManager.register_widget_model('WidgetModel', WidgetModel);
234 WidgetManager.register_widget_model('WidgetModel', WidgetModel);
234
235
235
236
236 var WidgetView = Backbone.View.extend({
237 var WidgetView = Backbone.View.extend({
237 initialize: function(parameters) {
238 initialize: function(parameters) {
238 // Public constructor.
239 // Public constructor.
239 this.model.on('change',this.update,this);
240 this.model.on('change',this.update,this);
240 this.options = parameters.options;
241 this.options = parameters.options;
241 this.child_views = [];
242 this.child_views = [];
242 this.model.views.push(this);
243 this.model.views.push(this);
243 },
244 },
244
245
245 update: function(){
246 update: function(){
246 // Triggered on model change.
247 // Triggered on model change.
247 //
248 //
248 // Update view to be consistent with this.model
249 // Update view to be consistent with this.model
249 },
250 },
250
251
251 create_child_view: function(child_model, options) {
252 create_child_view: function(child_model, options) {
252 // Create and return a child view.
253 // Create and return a child view.
253 //
254 //
254 // -given a model and (optionally) a view name if the view name is
255 // -given a model and (optionally) a view name if the view name is
255 // not given, it defaults to the model's default view attribute.
256 // not given, it defaults to the model's default view attribute.
256
257
257 // TODO: this is hacky, and makes the view depend on this cell attribute and widget manager behavior
258 // TODO: this is hacky, and makes the view depend on this cell attribute and widget manager behavior
258 // it would be great to have the widget manager add the cell metadata
259 // it would be great to have the widget manager add the cell metadata
259 // to the subview without having to add it here.
260 // to the subview without having to add it here.
260 var child_view = this.model.widget_manager.create_view(child_model, options || {});
261 var child_view = this.model.widget_manager.create_view(child_model, options || {});
261 this.child_views[child_model.id] = child_view;
262 this.child_views[child_model.id] = child_view;
262 return child_view;
263 return child_view;
263 },
264 },
264
265
265 delete_child_view: function(child_model, options) {
266 delete_child_view: function(child_model, options) {
266 // Delete a child view that was previously created using create_child_view.
267 // Delete a child view that was previously created using create_child_view.
267 var view = this.child_views[child_model.id];
268 var view = this.child_views[child_model.id];
268 if (view !== undefined) {
269 if (view !== undefined) {
269 delete this.child_views[child_model.id];
270 delete this.child_views[child_model.id];
270 view.remove();
271 view.remove();
271 }
272 }
272 },
273 },
273
274
274 do_diff: function(old_list, new_list, removed_callback, added_callback) {
275 do_diff: function(old_list, new_list, removed_callback, added_callback) {
275 // Difference a changed list and call remove and add callbacks for
276 // Difference a changed list and call remove and add callbacks for
276 // each removed and added item in the new list.
277 // each removed and added item in the new list.
277 //
278 //
278 // Parameters
279 // Parameters
279 // ----------
280 // ----------
280 // old_list : array
281 // old_list : array
281 // new_list : array
282 // new_list : array
282 // removed_callback : Callback(item)
283 // removed_callback : Callback(item)
283 // Callback that is called for each item removed.
284 // Callback that is called for each item removed.
284 // added_callback : Callback(item)
285 // added_callback : Callback(item)
285 // Callback that is called for each item added.
286 // Callback that is called for each item added.
286
287
287
288
288 // removed items
289 // removed items
289 _.each(_.difference(old_list, new_list), function(item, index, list) {
290 _.each(_.difference(old_list, new_list), function(item, index, list) {
290 removed_callback(item);
291 removed_callback(item);
291 }, this);
292 }, this);
292
293
293 // added items
294 // added items
294 _.each(_.difference(new_list, old_list), function(item, index, list) {
295 _.each(_.difference(new_list, old_list), function(item, index, list) {
295 added_callback(item);
296 added_callback(item);
296 }, this);
297 }, this);
297 },
298 },
298
299
299 callbacks: function(){
300 callbacks: function(){
300 // Create msg callbacks for a comm msg.
301 // Create msg callbacks for a comm msg.
301 return this.model.callbacks(this);
302 return this.model.callbacks(this);
302 },
303 },
303
304
304 render: function(){
305 render: function(){
305 // Render the view.
306 // Render the view.
306 //
307 //
307 // By default, this is only called the first time the view is created
308 // By default, this is only called the first time the view is created
308 },
309 },
309
310
310 send: function (content) {
311 send: function (content) {
311 // Send a custom msg associated with this view.
312 // Send a custom msg associated with this view.
312 this.model.send(content, this.callbacks());
313 this.model.send(content, this.callbacks());
313 },
314 },
314
315
315 touch: function () {
316 touch: function () {
316 this.model.save_changes(this.callbacks());
317 this.model.save_changes(this.callbacks());
317 },
318 },
318
319 });
319 });
320
320
321
321
322 var DOMWidgetView = WidgetView.extend({
322 var DOMWidgetView = WidgetView.extend({
323 initialize: function (options) {
323 initialize: function (options) {
324 // Public constructor
324 // Public constructor
325
325
326 // In the future we may want to make changes more granular
326 // In the future we may want to make changes more granular
327 // (e.g., trigger on visible:change).
327 // (e.g., trigger on visible:change).
328 this.model.on('change', this.update, this);
328 this.model.on('change', this.update, this);
329 this.model.on('msg:custom', this.on_msg, this);
329 this.model.on('msg:custom', this.on_msg, this);
330 DOMWidgetView.__super__.initialize.apply(this, arguments);
330 DOMWidgetView.__super__.initialize.apply(this, arguments);
331 },
331 },
332
332
333 on_msg: function(msg) {
333 on_msg: function(msg) {
334 // Handle DOM specific msgs.
334 // Handle DOM specific msgs.
335 switch(msg.msg_type) {
335 switch(msg.msg_type) {
336 case 'add_class':
336 case 'add_class':
337 this.add_class(msg.selector, msg.class_list);
337 this.add_class(msg.selector, msg.class_list);
338 break;
338 break;
339 case 'remove_class':
339 case 'remove_class':
340 this.remove_class(msg.selector, msg.class_list);
340 this.remove_class(msg.selector, msg.class_list);
341 break;
341 break;
342 }
342 }
343 },
343 },
344
344
345 add_class: function (selector, class_list) {
345 add_class: function (selector, class_list) {
346 // Add a DOM class to an element.
346 // Add a DOM class to an element.
347 this._get_selector_element(selector).addClass(class_list);
347 this._get_selector_element(selector).addClass(class_list);
348 },
348 },
349
349
350 remove_class: function (selector, class_list) {
350 remove_class: function (selector, class_list) {
351 // Remove a DOM class from an element.
351 // Remove a DOM class from an element.
352 this._get_selector_element(selector).removeClass(class_list);
352 this._get_selector_element(selector).removeClass(class_list);
353 },
353 },
354
354
355 update: function () {
355 update: function () {
356 // Update the contents of this view
356 // Update the contents of this view
357 //
357 //
358 // Called when the model is changed. The model may have been
358 // Called when the model is changed. The model may have been
359 // changed by another view or by a state update from the back-end.
359 // changed by another view or by a state update from the back-end.
360 // The very first update seems to happen before the element is
360 // The very first update seems to happen before the element is
361 // finished rendering so we use setTimeout to give the element time
361 // finished rendering so we use setTimeout to give the element time
362 // to render
362 // to render
363 var e = this.$el;
363 var e = this.$el;
364 var visible = this.model.get('visible');
364 var visible = this.model.get('visible');
365 setTimeout(function() {e.toggle(visible)},0);
365 setTimeout(function() {e.toggle(visible)},0);
366
366
367 var css = this.model.get('_css');
367 var css = this.model.get('_css');
368 if (css === undefined) {return;}
368 if (css === undefined) {return;}
369 _.each(css, function(css_traits, selector){
369 _.each(css, function(css_traits, selector){
370 // Apply the css traits to all elements that match the selector.
370 // Apply the css traits to all elements that match the selector.
371 var elements = this._get_selector_element(selector);
371 var elements = this._get_selector_element(selector);
372 if (elements.length > 0) {
372 if (elements.length > 0) {
373 _.each(css_traits, function(css_value, css_key){
373 _.each(css_traits, function(css_value, css_key){
374 elements.css(css_key, css_value);
374 elements.css(css_key, css_value);
375 });
375 });
376 }
376 }
377 });
377 });
378
378
379 },
379 },
380
380
381 _get_selector_element: function (selector) {
381 _get_selector_element: function (selector) {
382 // Get the elements via the css selector.
382 // Get the elements via the css selector.
383
383
384 // If the selector is blank, apply the style to the $el_to_style
384 // If the selector is blank, apply the style to the $el_to_style
385 // element. If the $el_to_style element is not defined, use apply
385 // element. If the $el_to_style element is not defined, use apply
386 // the style to the view's element.
386 // the style to the view's element.
387 var elements;
387 var elements;
388 if (selector === undefined || selector === null || selector === '') {
388 if (selector === undefined || selector === null || selector === '') {
389 if (this.$el_to_style === undefined) {
389 if (this.$el_to_style === undefined) {
390 elements = this.$el;
390 elements = this.$el;
391 } else {
391 } else {
392 elements = this.$el_to_style;
392 elements = this.$el_to_style;
393 }
393 }
394 } else {
394 } else {
395 elements = this.$el.find(selector);
395 elements = this.$el.find(selector);
396 }
396 }
397 return elements;
397 return elements;
398 },
398 },
399 });
399 });
400
400
401 IPython.WidgetModel = WidgetModel;
401 IPython.WidgetModel = WidgetModel;
402 IPython.WidgetView = WidgetView;
402 IPython.WidgetView = WidgetView;
403 IPython.DOMWidgetView = DOMWidgetView;
403 IPython.DOMWidgetView = DOMWidgetView;
404
404
405 // Pass through WidgetManager namespace.
405 // Pass through WidgetManager namespace.
406 return WidgetManager;
406 return WidgetManager;
407 });
407 });
General Comments 0
You need to be logged in to leave comments. Login now