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