| 1 |
// Copyright (c) Jupyter Development Team. |
| 2 |
// Distributed under the terms of the Modified BSD License. |
| 3 |
import * as utils from './utils'; |
| 4 |
import * as backbonePatch from './backbone-patch'; |
| 5 |
import * as Backbone from 'backbone'; |
| 6 |
import $ from 'jquery'; |
| 7 |
import { NativeView } from './nativeview'; |
| 8 |
import { JSONExt } from '@lumino/coreutils'; |
| 9 |
import { MessageLoop } from '@lumino/messaging'; |
| 10 |
import { Widget, Panel } from '@lumino/widgets'; |
| 11 |
import { JUPYTER_WIDGETS_VERSION } from './version'; |
| 12 |
/** |
| 13 |
* The magic key used in the widget graph serialization. |
| 14 |
*/ |
| 15 |
const IPY_MODEL_ = 'IPY_MODEL_'; |
| 16 |
/** |
| 17 |
* Replace model ids with models recursively. |
| 18 |
*/ |
| 19 |
export function unpack_models(value, manager // actually required, but typed to be compatible with ISerializers |
| 20 |
) { |
| 21 |
if (Array.isArray(value)) { |
| 22 |
const unpacked = []; |
| 23 |
for (const sub_value of value) { |
| 24 |
unpacked.push(unpack_models(sub_value, manager)); |
| 25 |
} |
| 26 |
return Promise.all(unpacked); |
| 27 |
} |
| 28 |
else if (value instanceof Object && typeof value !== 'string') { |
| 29 |
const unpacked = {}; |
| 30 |
for (const [key, sub_value] of Object.entries(value)) { |
| 31 |
unpacked[key] = unpack_models(sub_value, manager); |
| 32 |
} |
| 33 |
return utils.resolvePromisesDict(unpacked); |
| 34 |
} |
| 35 |
else if (typeof value === 'string' && value.slice(0, 10) === IPY_MODEL_) { |
| 36 |
// get_model returns a promise already |
| 37 |
return manager.get_model(value.slice(10, value.length)); |
| 38 |
} |
| 39 |
else { |
| 40 |
return Promise.resolve(value); |
| 41 |
} |
| 42 |
} |
| 43 |
/** Replace models with ids recursively. |
| 44 |
* |
| 45 |
* If the commonly-used `unpack_models` is given as the `deseralize` method, |
| 46 |
* pack_models would be the appropriate `serialize`. |
| 47 |
* However, the default serialize method will have the same effect, when |
| 48 |
* `unpack_models` is used as the deserialize method. |
| 49 |
* This is to ensure backwards compatibility, see: |
| 50 |
* https://github.com/jupyter-widgets/ipywidgets/pull/3738/commits/f9e27328bb631eb5247a7a6563595d3e655492c7#diff-efb19099381ae8911dd7f69b015a0138d08da7164512c1ee112aa75100bc9be2 |
| 51 |
*/ |
| 52 |
export function pack_models(value, widget) { |
| 53 |
if (Array.isArray(value)) { |
| 54 |
const model_ids = []; |
| 55 |
for (const model of value) { |
| 56 |
model_ids.push(pack_models(model, widget)); |
| 57 |
} |
| 58 |
return model_ids; |
| 59 |
} |
| 60 |
else if (value instanceof WidgetModel) { |
| 61 |
return `${IPY_MODEL_}${value.model_id}`; |
| 62 |
} |
| 63 |
else if (value instanceof Object && typeof value !== 'string') { |
| 64 |
const packed = {}; |
| 65 |
for (const [key, sub_value] of Object.entries(value)) { |
| 66 |
packed[key] = pack_models(sub_value, widget); |
| 67 |
} |
| 68 |
return packed; |
| 69 |
} |
| 70 |
else { |
| 71 |
return value; |
| 72 |
} |
| 73 |
} |
| 74 |
export class WidgetModel extends Backbone.Model { |
| 75 |
/** |
| 76 |
* The default attributes. |
| 77 |
*/ |
| 78 |
defaults() { |
| 79 |
return { |
| 80 |
_model_module: '@jupyter-widgets/base', |
| 81 |
_model_name: 'WidgetModel', |
| 82 |
_model_module_version: JUPYTER_WIDGETS_VERSION, |
| 83 |
_view_module: '@jupyter-widgets/base', |
| 84 |
_view_name: null, |
| 85 |
_view_module_version: JUPYTER_WIDGETS_VERSION, |
| 86 |
_view_count: null, |
| 87 |
}; |
| 88 |
} |
| 89 |
/** |
| 90 |
* Test to see if the model has been synced with the server. |
| 91 |
* |
| 92 |
* #### Notes |
| 93 |
* As of backbone 1.1, backbone ignores `patch` if it thinks the |
| 94 |
* model has never been pushed. |
| 95 |
*/ |
| 96 |
isNew() { |
| 97 |
return false; |
| 98 |
} |
| 99 |
/** |
| 100 |
* Constructor |
| 101 |
* |
| 102 |
* Initializes a WidgetModel instance. Called by the Backbone constructor. |
| 103 |
* |
| 104 |
* Parameters |
| 105 |
* ---------- |
| 106 |
* widget_manager : WidgetManager instance |
| 107 |
* model_id : string |
| 108 |
* An ID unique to this model. |
| 109 |
* comm : Comm instance (optional) |
| 110 |
*/ |
| 111 |
initialize(attributes, options) { |
| 112 |
this._expectedEchoMsgIds = new Map(); |
| 113 |
this._attrsToUpdate = new Set(); |
| 114 |
super.initialize(attributes, options); |
| 115 |
// Attributes should be initialized here, since user initialization may depend on it |
| 116 |
this.widget_manager = options.widget_manager; |
| 117 |
this.model_id = options.model_id; |
| 118 |
const comm = options.comm; |
| 119 |
this.views = Object.create(null); |
| 120 |
this.state_change = Promise.resolve(); |
| 121 |
this._closed = false; |
| 122 |
this._state_lock = null; |
| 123 |
this._msg_buffer = null; |
| 124 |
this._msg_buffer_callbacks = null; |
| 125 |
this._pending_msgs = 0; |
| 126 |
// _buffered_state_diff must be created *after* the super.initialize |
| 127 |
// call above. See the note in the set() method below. |
| 128 |
this._buffered_state_diff = {}; |
| 129 |
if (comm) { |
| 130 |
// Remember comm associated with the model. |
| 131 |
this.comm = comm; |
| 132 |
// Hook comm messages up to model. |
| 133 |
comm.on_close(this._handle_comm_closed.bind(this)); |
| 134 |
comm.on_msg(this._handle_comm_msg.bind(this)); |
| 135 |
this.comm_live = true; |
| 136 |
} |
| 137 |
else { |
| 138 |
this.comm_live = false; |
| 139 |
} |
| 140 |
} |
| 141 |
get comm_live() { |
| 142 |
return this._comm_live; |
| 143 |
} |
| 144 |
set comm_live(x) { |
| 145 |
this._comm_live = x; |
| 146 |
this.trigger('comm_live_update'); |
| 147 |
} |
| 148 |
/** |
| 149 |
* Send a custom msg over the comm. |
| 150 |
*/ |
| 151 |
send(content, callbacks, buffers) { |
| 152 |
if (this.comm !== undefined) { |
| 153 |
const data = { method: 'custom', content: content }; |
| 154 |
this.comm.send(data, callbacks, {}, buffers); |
| 155 |
} |
| 156 |
} |
| 157 |
/** |
| 158 |
* Close model |
| 159 |
* |
| 160 |
* @param comm_closed - true if the comm is already being closed. If false, the comm will be closed. |
| 161 |
* |
| 162 |
* @returns - a promise that is fulfilled when all the associated views have been removed. |
| 163 |
*/ |
| 164 |
close(comm_closed = false) { |
| 165 |
// can only be closed once. |
| 166 |
if (this._closed) { |
| 167 |
return Promise.resolve(); |
| 168 |
} |
| 169 |
this._closed = true; |
| 170 |
if (this.comm && !comm_closed) { |
| 171 |
this.comm.close(); |
| 172 |
} |
| 173 |
this.stopListening(); |
| 174 |
this.trigger('destroy', this); |
| 175 |
if (this.comm) { |
| 176 |
delete this.comm; |
| 177 |
} |
| 178 |
// Delete all views of this model |
| 179 |
if (this.views) { |
| 180 |
const views = Object.keys(this.views).map((id) => { |
| 181 |
return this.views[id].then((view) => view.remove()); |
| 182 |
}); |
| 183 |
delete this.views; |
| 184 |
return Promise.all(views).then(() => { |
| 185 |
return; |
| 186 |
}); |
| 187 |
} |
| 188 |
return Promise.resolve(); |
| 189 |
} |
| 190 |
/** |
| 191 |
* Handle when a widget comm is closed. |
| 192 |
*/ |
| 193 |
_handle_comm_closed(msg) { |
| 194 |
this.trigger('comm:close'); |
| 195 |
this.close(true); |
| 196 |
} |
| 197 |
/** |
| 198 |
* Handle incoming comm msg. |
| 199 |
*/ |
| 200 |
_handle_comm_msg(msg) { |
| 201 |
const data = msg.content.data; |
| 202 |
const method = data.method; |
| 203 |
switch (method) { |
| 204 |
case 'update': |
| 205 |
case 'echo_update': |
| 206 |
this.state_change = this.state_change |
| 207 |
.then(() => { |
| 208 |
var _a, _b, _c; |
| 209 |
const state = data.state; |
| 210 |
const buffer_paths = (_a = data.buffer_paths) !== null && _a !== void 0 ? _a : []; |
| 211 |
const buffers = (_c = (_b = msg.buffers) === null || _b === void 0 ? void 0 : _b.slice(0, buffer_paths.length)) !== null && _c !== void 0 ? _c : []; |
| 212 |
utils.put_buffers(state, buffer_paths, buffers); |
| 213 |
if (msg.parent_header && method === 'echo_update') { |
| 214 |
const msgId = msg.parent_header.msg_id; |
| 215 |
// we may have echos coming from other clients, we only care about |
| 216 |
// dropping echos for which we expected a reply |
| 217 |
const expectedEcho = Object.keys(state).filter((attrName) => this._expectedEchoMsgIds.has(attrName)); |
| 218 |
expectedEcho.forEach((attrName) => { |
| 219 |
// Skip echo messages until we get the reply we are expecting. |
| 220 |
const isOldMessage = this._expectedEchoMsgIds.get(attrName) !== msgId; |
| 221 |
if (isOldMessage) { |
| 222 |
// Ignore an echo update that comes before our echo. |
| 223 |
delete state[attrName]; |
| 224 |
} |
| 225 |
else { |
| 226 |
// we got our echo confirmation, so stop looking for it |
| 227 |
this._expectedEchoMsgIds.delete(attrName); |
| 228 |
// Start accepting echo updates unless we plan to send out a new state soon |
| 229 |
if (this._msg_buffer !== null && |
| 230 |
Object.prototype.hasOwnProperty.call(this._msg_buffer, attrName)) { |
| 231 |
delete state[attrName]; |
| 232 |
} |
| 233 |
} |
| 234 |
}); |
| 235 |
} |
| 236 |
return this.constructor._deserialize_state( |
| 237 |
// Combine the state updates, with preference for kernel updates |
| 238 |
state, this.widget_manager); |
| 239 |
}) |
| 240 |
.then((state) => { |
| 241 |
this.set_state(state); |
| 242 |
}) |
| 243 |
.catch(utils.reject(`Could not process update msg for model id: ${this.model_id}`, true)); |
| 244 |
return this.state_change; |
| 245 |
case 'custom': |
| 246 |
this.trigger('msg:custom', data.content, msg.buffers); |
| 247 |
return Promise.resolve(); |
| 248 |
} |
| 249 |
return Promise.resolve(); |
| 250 |
} |
| 251 |
/** |
| 252 |
* Handle when a widget is updated from the backend. |
| 253 |
* |
| 254 |
* This function is meant for internal use only. Values set here will not be propagated on a sync. |
| 255 |
*/ |
| 256 |
set_state(state) { |
| 257 |
this._state_lock = state; |
| 258 |
try { |
| 259 |
this.set(state); |
| 260 |
} |
| 261 |
catch (e) { |
| 262 |
console.error(`Error setting state: ${e instanceof Error ? e.message : e}`); |
| 263 |
} |
| 264 |
finally { |
| 265 |
this._state_lock = null; |
| 266 |
} |
| 267 |
} |
| 268 |
/** |
| 269 |
* Get the serializable state of the model. |
| 270 |
* |
| 271 |
* If drop_default is truthy, attributes that are equal to their default |
| 272 |
* values are dropped. |
| 273 |
*/ |
| 274 |
get_state(drop_defaults) { |
| 275 |
const fullState = this.attributes; |
| 276 |
if (drop_defaults) { |
| 277 |
// if defaults is a function, call it |
| 278 |
const d = this.defaults; |
| 279 |
const defaults = typeof d === 'function' ? d.call(this) : d; |
| 280 |
const state = {}; |
| 281 |
Object.keys(fullState).forEach((key) => { |
| 282 |
if (!utils.isEqual(fullState[key], defaults[key])) { |
| 283 |
state[key] = fullState[key]; |
| 284 |
} |
| 285 |
}); |
| 286 |
return state; |
| 287 |
} |
| 288 |
else { |
| 289 |
return Object.assign({}, fullState); |
| 290 |
} |
| 291 |
} |
| 292 |
/** |
| 293 |
* Handle status msgs. |
| 294 |
* |
| 295 |
* execution_state : ('busy', 'idle', 'starting') |
| 296 |
*/ |
| 297 |
_handle_status(msg) { |
| 298 |
if (this.comm !== void 0) { |
| 299 |
if (msg.content.execution_state === 'idle') { |
| 300 |
this._pending_msgs--; |
| 301 |
// Sanity check for logic errors that may push this below zero. |
| 302 |
if (this._pending_msgs < 0) { |
| 303 |
console.error(`Jupyter Widgets message throttle: Pending messages < 0 (=${this._pending_msgs}), which is unexpected. Resetting to 0 to continue.`); |
| 304 |
this._pending_msgs = 0; // do not break message throttling in case of unexpected errors |
| 305 |
} |
| 306 |
// Send buffer if one is waiting and we are below the throttle. |
| 307 |
if (this._msg_buffer !== null && this._pending_msgs < 1) { |
| 308 |
const msgId = this.send_sync_message(this._msg_buffer, this._msg_buffer_callbacks); |
| 309 |
this.rememberLastUpdateFor(msgId); |
| 310 |
this._msg_buffer = null; |
| 311 |
this._msg_buffer_callbacks = null; |
| 312 |
} |
| 313 |
} |
| 314 |
} |
| 315 |
} |
| 316 |
/** |
| 317 |
* Create msg callbacks for a comm msg. |
| 318 |
*/ |
| 319 |
callbacks(view) { |
| 320 |
return this.widget_manager.callbacks(view); |
| 321 |
} |
| 322 |
/** |
| 323 |
* Set one or more values. |
| 324 |
* |
| 325 |
* We just call the super method, in which val and options are optional. |
| 326 |
* Handles both "key", value and {key: value} -style arguments. |
| 327 |
*/ |
| 328 |
set(key, val, options) { |
| 329 |
// Call our patched backbone set. See #1642 and #1643. |
| 330 |
const return_value = backbonePatch.set.call(this, key, val, options); |
| 331 |
// Backbone only remembers the diff of the most recent set() |
| 332 |
// operation. Calling set multiple times in a row results in a |
| 333 |
// loss of change information. Here we keep our own running diff. |
| 334 |
// |
| 335 |
// We don't buffer the state set in the constructor (including |
| 336 |
// defaults), so we first check to see if we've initialized _buffered_state_diff. |
| 337 |
// which happens after the constructor sets attributes at creation. |
| 338 |
if (this._buffered_state_diff !== void 0) { |
| 339 |
const attrs = this.changedAttributes() || {}; |
| 340 |
// The state_lock lists attributes that are currently being changed |
| 341 |
// right now from a kernel message. We don't want to send these |
| 342 |
// non-changes back to the kernel, so we delete them out of attrs if |
| 343 |
// they haven't changed from their state_lock value. |
| 344 |
// The state lock could be null or undefined (if set is being called from |
| 345 |
// the initializer). |
| 346 |
if (this._state_lock) { |
| 347 |
for (const key of Object.keys(this._state_lock)) { |
| 348 |
if (attrs[key] === this._state_lock[key]) { |
| 349 |
delete attrs[key]; |
| 350 |
} |
| 351 |
} |
| 352 |
} |
| 353 |
// _buffered_state_diff_synced lists things that have already been sent to the kernel during a top-level call to .set(), so we don't need to buffer these things either. |
| 354 |
if (this._buffered_state_diff_synced) { |
| 355 |
for (const key of Object.keys(this._buffered_state_diff_synced)) { |
| 356 |
if (attrs[key] === this._buffered_state_diff_synced[key]) { |
| 357 |
delete attrs[key]; |
| 358 |
} |
| 359 |
} |
| 360 |
} |
| 361 |
this._buffered_state_diff = utils.assign(this._buffered_state_diff, attrs); |
| 362 |
} |
| 363 |
// If this ended a top-level call to .set, then reset _buffered_state_diff_synced |
| 364 |
if (this._changing === false) { |
| 365 |
this._buffered_state_diff_synced = {}; |
| 366 |
} |
| 367 |
return return_value; |
| 368 |
} |
| 369 |
/** |
| 370 |
* Handle sync to the back-end. Called when a model.save() is called. |
| 371 |
* |
| 372 |
* Make sure a comm exists. |
| 373 |
* |
| 374 |
* Parameters |
| 375 |
* ---------- |
| 376 |
* method : create, update, patch, delete, read |
| 377 |
* create/update always send the full attribute set |
| 378 |
* patch - only send attributes listed in options.attrs, and if we |
| 379 |
* are queuing up messages, combine with previous messages that have |
| 380 |
* not been sent yet |
| 381 |
* model : the model we are syncing |
| 382 |
* will normally be the same as `this` |
| 383 |
* options : dict |
| 384 |
* the `attrs` key, if it exists, gives an {attr: value} dict that |
| 385 |
* should be synced, otherwise, sync all attributes. |
| 386 |
* |
| 387 |
*/ |
| 388 |
sync(method, model, options = {}) { |
| 389 |
// the typing is to return `any` since the super.sync method returns a JqXHR, but we just return false if there is an error. |
| 390 |
if (this.comm === undefined) { |
| 391 |
throw 'Syncing error: no comm channel defined'; |
| 392 |
} |
| 393 |
const attrs = method === 'patch' |
| 394 |
? options.attrs |
| 395 |
: model.get_state(options.drop_defaults); |
| 396 |
// The state_lock lists attributes that are currently being changed |
| 397 |
// right now from a kernel message. We don't want to send these |
| 398 |
// non-changes back to the kernel, so we delete them out of attrs if |
| 399 |
// they haven't changed from their state_lock value. |
| 400 |
// The state lock could be null or undefined (if this is triggered |
| 401 |
// from the initializer). |
| 402 |
if (this._state_lock) { |
| 403 |
for (const key of Object.keys(this._state_lock)) { |
| 404 |
if (attrs[key] === this._state_lock[key]) { |
| 405 |
delete attrs[key]; |
| 406 |
} |
| 407 |
} |
| 408 |
} |
| 409 |
Object.keys(attrs).forEach((attrName) => { |
| 410 |
this._attrsToUpdate.add(attrName); |
| 411 |
}); |
| 412 |
const msgState = this.serialize(attrs); |
| 413 |
if (Object.keys(msgState).length > 0) { |
| 414 |
// If this message was sent via backbone itself, it will not |
| 415 |
// have any callbacks. It's important that we create callbacks |
| 416 |
// so we can listen for status messages, etc... |
| 417 |
const callbacks = options.callbacks || this.callbacks(); |
| 418 |
// Check throttle. |
| 419 |
if (this._pending_msgs >= 1) { |
| 420 |
// The throttle has been exceeded, buffer the current msg so |
| 421 |
// it can be sent once the kernel has finished processing |
| 422 |
// some of the existing messages. |
| 423 |
// Combine updates if it is a 'patch' sync, otherwise replace updates |
| 424 |
switch (method) { |
| 425 |
case 'patch': |
| 426 |
this._msg_buffer = utils.assign(this._msg_buffer || {}, msgState); |
| 427 |
break; |
| 428 |
case 'update': |
| 429 |
case 'create': |
| 430 |
this._msg_buffer = msgState; |
| 431 |
break; |
| 432 |
default: |
| 433 |
throw 'unrecognized syncing method'; |
| 434 |
} |
| 435 |
this._msg_buffer_callbacks = callbacks; |
| 436 |
} |
| 437 |
else { |
| 438 |
// We haven't exceeded the throttle, send the message like |
| 439 |
// normal. |
| 440 |
const msgId = this.send_sync_message(attrs, callbacks); |
| 441 |
this.rememberLastUpdateFor(msgId); |
| 442 |
// Since the comm is a one-way communication, assume the message |
| 443 |
// arrived and was processed successfully. |
| 444 |
// Don't call options.success since we don't have a model back from |
| 445 |
// the server. Note that this means we don't have the Backbone |
| 446 |
// 'sync' event. |
| 447 |
} |
| 448 |
} |
| 449 |
} |
| 450 |
rememberLastUpdateFor(msgId) { |
| 451 |
this._attrsToUpdate.forEach((attrName) => { |
| 452 |
this._expectedEchoMsgIds.set(attrName, msgId); |
| 453 |
}); |
| 454 |
this._attrsToUpdate = new Set(); |
| 455 |
} |
| 456 |
/** |
| 457 |
* Serialize widget state. |
| 458 |
* |
| 459 |
* A serializer is a function which takes in a state attribute and a widget, |
| 460 |
* and synchronously returns a JSONable object. The returned object will |
| 461 |
* have toJSON called if possible, and the final result should be a |
| 462 |
* primitive object that is a snapshot of the widget state that may have |
| 463 |
* binary array buffers. |
| 464 |
*/ |
| 465 |
serialize(state) { |
| 466 |
const serializers = this.constructor.serializers || |
| 467 |
JSONExt.emptyObject; |
| 468 |
for (const k of Object.keys(state)) { |
| 469 |
try { |
| 470 |
if (serializers[k] && serializers[k].serialize) { |
| 471 |
state[k] = serializers[k].serialize(state[k], this); |
| 472 |
} |
| 473 |
else { |
| 474 |
// the default serializer just deep-copies the object |
| 475 |
state[k] = JSON.parse(JSON.stringify(state[k])); |
| 476 |
} |
| 477 |
if (state[k] && state[k].toJSON) { |
| 478 |
state[k] = state[k].toJSON(); |
| 479 |
} |
| 480 |
} |
| 481 |
catch (e) { |
| 482 |
console.error('Error serializing widget state attribute: ', k); |
| 483 |
throw e; |
| 484 |
} |
| 485 |
} |
| 486 |
return state; |
| 487 |
} |
| 488 |
/** |
| 489 |
* Send a sync message to the kernel. |
| 490 |
* |
| 491 |
* If a message is sent successfully, this returns the message ID of that |
| 492 |
* message. Otherwise it returns an empty string |
| 493 |
*/ |
| 494 |
send_sync_message(state, callbacks = {}) { |
| 495 |
if (!this.comm) { |
| 496 |
return ''; |
| 497 |
} |
| 498 |
try { |
| 499 |
// Make a 2-deep copy so we don't modify the caller's callbacks object. |
| 500 |
callbacks = { |
| 501 |
shell: Object.assign({}, callbacks.shell), |
| 502 |
iopub: Object.assign({}, callbacks.iopub), |
| 503 |
input: callbacks.input, |
| 504 |
}; |
| 505 |
// Save the caller's status callback so we can call it after we handle the message. |
| 506 |
const statuscb = callbacks.iopub.status; |
| 507 |
callbacks.iopub.status = (msg) => { |
| 508 |
this._handle_status(msg); |
| 509 |
if (statuscb) { |
| 510 |
statuscb(msg); |
| 511 |
} |
| 512 |
}; |
| 513 |
// split out the binary buffers |
| 514 |
const split = utils.remove_buffers(state); |
| 515 |
const msgId = this.comm.send({ |
| 516 |
method: 'update', |
| 517 |
state: split.state, |
| 518 |
buffer_paths: split.buffer_paths, |
| 519 |
}, callbacks, {}, split.buffers); |
| 520 |
this._pending_msgs++; |
| 521 |
return msgId; |
| 522 |
} |
| 523 |
catch (e) { |
| 524 |
console.error('Could not send widget sync message', e); |
| 525 |
} |
| 526 |
return ''; |
| 527 |
} |
| 528 |
/** |
| 529 |
* Push this model's state to the back-end |
| 530 |
* |
| 531 |
* This invokes a Backbone.Sync. |
| 532 |
*/ |
| 533 |
save_changes(callbacks) { |
| 534 |
if (this.comm_live) { |
| 535 |
const options = { patch: true }; |
| 536 |
if (callbacks) { |
| 537 |
options.callbacks = callbacks; |
| 538 |
} |
| 539 |
this.save(this._buffered_state_diff, options); |
| 540 |
// If we are currently in a .set() call, save what state we have synced |
| 541 |
// to the kernel so we don't buffer it again as we come out of the .set call. |
| 542 |
if (this._changing) { |
| 543 |
utils.assign(this._buffered_state_diff_synced, this._buffered_state_diff); |
| 544 |
} |
| 545 |
this._buffered_state_diff = {}; |
| 546 |
} |
| 547 |
} |
| 548 |
/** |
| 549 |
* on_some_change(['key1', 'key2'], foo, context) differs from |
| 550 |
* on('change:key1 change:key2', foo, context). |
| 551 |
* If the widget attributes key1 and key2 are both modified, |
| 552 |
* the second form will result in foo being called twice |
| 553 |
* while the first will call foo only once. |
| 554 |
*/ |
| 555 |
on_some_change(keys, callback, context) { |
| 556 |
this.on('change', (...args) => { |
| 557 |
if (keys.some(this.hasChanged, this)) { |
| 558 |
callback.apply(context, args); |
| 559 |
} |
| 560 |
}, this); |
| 561 |
} |
| 562 |
/** |
| 563 |
* Serialize the model. See the deserialization function at the top of this file |
| 564 |
* and the kernel-side serializer/deserializer. |
| 565 |
*/ |
| 566 |
toJSON(options) { |
| 567 |
return `IPY_MODEL_${this.model_id}`; |
| 568 |
} |
| 569 |
/** |
| 570 |
* Returns a promise for the deserialized state. The second argument |
| 571 |
* is an instance of widget manager, which is required for the |
| 572 |
* deserialization of widget models. |
| 573 |
*/ |
| 574 |
static _deserialize_state(state, manager) { |
| 575 |
const serializers = this.serializers; |
| 576 |
let deserialized; |
| 577 |
if (serializers) { |
| 578 |
deserialized = {}; |
| 579 |
for (const k in state) { |
| 580 |
if (serializers[k] && serializers[k].deserialize) { |
| 581 |
deserialized[k] = serializers[k].deserialize(state[k], manager); |
| 582 |
} |
| 583 |
else { |
| 584 |
deserialized[k] = state[k]; |
| 585 |
} |
| 586 |
} |
| 587 |
} |
| 588 |
else { |
| 589 |
deserialized = state; |
| 590 |
} |
| 591 |
return utils.resolvePromisesDict(deserialized); |
| 592 |
} |
| 593 |
} |
| 594 |
export class DOMWidgetModel extends WidgetModel { |
| 595 |
defaults() { |
| 596 |
return utils.assign(super.defaults(), { |
| 597 |
_dom_classes: [], |
| 598 |
tabbable: null, |
| 599 |
tooltip: null, |
| 600 |
// We do not declare defaults for the layout and style attributes. |
| 601 |
// Those defaults are constructed on the kernel side and synced here |
| 602 |
// as needed, and our code here copes with those attributes being |
| 603 |
// undefined. See |
| 604 |
// https://github.com/jupyter-widgets/ipywidgets/issues/1620 and |
| 605 |
// https://github.com/jupyter-widgets/ipywidgets/pull/1621 |
| 606 |
}); |
| 607 |
} |
| 608 |
} |
| 609 |
DOMWidgetModel.serializers = Object.assign(Object.assign({}, WidgetModel.serializers), { layout: { deserialize: unpack_models }, style: { deserialize: unpack_models } }); |
| 610 |
export class WidgetView extends NativeView { |
| 611 |
/** |
| 612 |
* Public constructor. |
| 613 |
*/ |
| 614 |
constructor(options) { |
| 615 |
super(options); |
| 616 |
} |
| 617 |
/** |
| 618 |
* Initializer, called at the end of the constructor. |
| 619 |
*/ |
| 620 |
initialize(parameters) { |
| 621 |
this.listenTo(this.model, 'change', (model, options) => { |
| 622 |
const changed = Object.keys(this.model.changedAttributes() || {}); |
| 623 |
if (changed[0] === '_view_count' && changed.length === 1) { |
| 624 |
// Just the view count was updated |
| 625 |
return; |
| 626 |
} |
| 627 |
this.update(options); |
| 628 |
}); |
| 629 |
this.options = parameters.options; |
| 630 |
this.once('remove', () => { |
| 631 |
if (typeof this.model.get('_view_count') === 'number') { |
| 632 |
this.model.set('_view_count', this.model.get('_view_count') - 1); |
| 633 |
this.model.save_changes(); |
| 634 |
} |
| 635 |
}); |
| 636 |
this.once('displayed', () => { |
| 637 |
if (typeof this.model.get('_view_count') === 'number') { |
| 638 |
this.model.set('_view_count', this.model.get('_view_count') + 1); |
| 639 |
this.model.save_changes(); |
| 640 |
} |
| 641 |
}); |
| 642 |
this.displayed = new Promise((resolve, reject) => { |
| 643 |
this.once('displayed', resolve); |
| 644 |
this.model.on('msg:custom', this.handle_message.bind(this)); |
| 645 |
}); |
| 646 |
} |
| 647 |
/** |
| 648 |
* Handle message sent to the front end. |
| 649 |
* |
| 650 |
* Used to focus or blur the widget. |
| 651 |
*/ |
| 652 |
handle_message(content) { |
| 653 |
if (content.do === 'focus') { |
| 654 |
this.el.focus(); |
| 655 |
} |
| 656 |
else if (content.do === 'blur') { |
| 657 |
this.el.blur(); |
| 658 |
} |
| 659 |
} |
| 660 |
/** |
| 661 |
* Triggered on model change. |
| 662 |
* |
| 663 |
* Update view to be consistent with this.model |
| 664 |
*/ |
| 665 |
update(options) { |
| 666 |
return; |
| 667 |
} |
| 668 |
/** |
| 669 |
* Render a view |
| 670 |
* |
| 671 |
* @returns the view or a promise to the view. |
| 672 |
*/ |
| 673 |
render() { |
| 674 |
return; |
| 675 |
} |
| 676 |
create_child_view(child_model, options = {}) { |
| 677 |
options = Object.assign({ parent: this }, options); |
| 678 |
return this.model.widget_manager |
| 679 |
.create_view(child_model, options) |
| 680 |
.catch(utils.reject('Could not create child view', true)); |
| 681 |
} |
| 682 |
/** |
| 683 |
* Create msg callbacks for a comm msg. |
| 684 |
*/ |
| 685 |
callbacks() { |
| 686 |
return this.model.callbacks(this); |
| 687 |
} |
| 688 |
/** |
| 689 |
* Send a custom msg associated with this view. |
| 690 |
*/ |
| 691 |
send(content, buffers) { |
| 692 |
this.model.send(content, this.callbacks(), buffers); |
| 693 |
} |
| 694 |
touch() { |
| 695 |
this.model.save_changes(this.callbacks()); |
| 696 |
} |
| 697 |
remove() { |
| 698 |
// Raise a remove event when the view is removed. |
| 699 |
super.remove(); |
| 700 |
this.trigger('remove'); |
| 701 |
return this; |
| 702 |
} |
| 703 |
} |
| 704 |
export class JupyterLuminoWidget extends Widget { |
| 705 |
constructor(options) { |
| 706 |
const view = options.view; |
| 707 |
// Cast as any since we cannot delete a mandatory value |
| 708 |
delete options.view; |
| 709 |
super(options); |
| 710 |
this._view = view; |
| 711 |
} |
| 712 |
/** |
| 713 |
* Dispose the widget. |
| 714 |
* |
| 715 |
* This causes the view to be destroyed as well with 'remove' |
| 716 |
*/ |
| 717 |
dispose() { |
| 718 |
if (this.isDisposed) { |
| 719 |
return; |
| 720 |
} |
| 721 |
super.dispose(); |
| 722 |
this._view.remove(); |
| 723 |
this._view = null; |
| 724 |
} |
| 725 |
/** |
| 726 |
* Process the Lumino message. |
| 727 |
* |
| 728 |
* Any custom Lumino widget used inside a Jupyter widget should override |
| 729 |
* the processMessage function like this. |
| 730 |
*/ |
| 731 |
processMessage(msg) { |
| 732 |
super.processMessage(msg); |
| 733 |
this._view.processLuminoMessage(msg); |
| 734 |
} |
| 735 |
} |
| 736 |
/** |
| 737 |
* @deprecated Use {@link JupyterLuminoWidget} instead (Since 8.0). |
| 738 |
*/ |
| 739 |
export const JupyterPhosphorWidget = JupyterLuminoWidget; |
| 740 |
export class JupyterLuminoPanelWidget extends Panel { |
| 741 |
constructor(options) { |
| 742 |
const view = options.view; |
| 743 |
delete options.view; |
| 744 |
super(options); |
| 745 |
this._view = view; |
| 746 |
} |
| 747 |
/** |
| 748 |
* Process the Lumino message. |
| 749 |
* |
| 750 |
* Any custom Lumino widget used inside a Jupyter widget should override |
| 751 |
* the processMessage function like this. |
| 752 |
*/ |
| 753 |
processMessage(msg) { |
| 754 |
super.processMessage(msg); |
| 755 |
this._view.processLuminoMessage(msg); |
| 756 |
} |
| 757 |
/** |
| 758 |
* Dispose the widget. |
| 759 |
* |
| 760 |
* This causes the view to be destroyed as well with 'remove' |
| 761 |
*/ |
| 762 |
dispose() { |
| 763 |
var _a; |
| 764 |
if (this.isDisposed) { |
| 765 |
return; |
| 766 |
} |
| 767 |
super.dispose(); |
| 768 |
(_a = this._view) === null || _a === void 0 ? void 0 : _a.remove(); |
| 769 |
this._view = null; |
| 770 |
} |
| 771 |
} |
| 772 |
/** |
| 773 |
* @deprecated Use {@link JupyterLuminoPanelWidget} instead (Since 8.0). |
| 774 |
*/ |
| 775 |
export const JupyterPhosphorPanelWidget = JupyterLuminoPanelWidget; |
| 776 |
export class DOMWidgetView extends WidgetView { |
| 777 |
/** |
| 778 |
* Public constructor |
| 779 |
*/ |
| 780 |
initialize(parameters) { |
| 781 |
super.initialize(parameters); |
| 782 |
this.listenTo(this.model, 'change:_dom_classes', (model, new_classes) => { |
| 783 |
const old_classes = model.previous('_dom_classes'); |
| 784 |
this.update_classes(old_classes, new_classes); |
| 785 |
}); |
| 786 |
this.layoutPromise = Promise.resolve(); |
| 787 |
this.listenTo(this.model, 'change:layout', (model, value) => { |
| 788 |
this.setLayout(value, model.previous('layout')); |
| 789 |
}); |
| 790 |
this.stylePromise = Promise.resolve(); |
| 791 |
this.listenTo(this.model, 'change:style', (model, value) => { |
| 792 |
this.setStyle(value, model.previous('style')); |
| 793 |
}); |
| 794 |
this.displayed.then(() => { |
| 795 |
this.update_classes([], this.model.get('_dom_classes')); |
| 796 |
this.setLayout(this.model.get('layout')); |
| 797 |
this.setStyle(this.model.get('style')); |
| 798 |
}); |
| 799 |
this._comm_live_update(); |
| 800 |
this.listenTo(this.model, 'comm_live_update', () => { |
| 801 |
this._comm_live_update(); |
| 802 |
}); |
| 803 |
this.listenTo(this.model, 'change:tooltip', this.updateTooltip); |
| 804 |
this.updateTooltip(); |
| 805 |
} |
| 806 |
setLayout(layout, oldLayout) { |
| 807 |
if (layout) { |
| 808 |
this.layoutPromise = this.layoutPromise.then((oldLayoutView) => { |
| 809 |
if (oldLayoutView) { |
| 810 |
oldLayoutView.unlayout(); |
| 811 |
this.stopListening(oldLayoutView.model); |
| 812 |
oldLayoutView.remove(); |
| 813 |
} |
| 814 |
return this.create_child_view(layout) |
| 815 |
.then((view) => { |
| 816 |
// Trigger the displayed event of the child view. |
| 817 |
return this.displayed.then(() => { |
| 818 |
view.trigger('displayed'); |
| 819 |
this.listenTo(view.model, 'change', () => { |
| 820 |
// Post (asynchronous) so layout changes can take |
| 821 |
// effect first. |
| 822 |
MessageLoop.postMessage(this.luminoWidget, Widget.ResizeMessage.UnknownSize); |
| 823 |
}); |
| 824 |
MessageLoop.postMessage(this.luminoWidget, Widget.ResizeMessage.UnknownSize); |
| 825 |
this.trigger('layout-changed'); |
| 826 |
return view; |
| 827 |
}); |
| 828 |
}) |
| 829 |
.catch(utils.reject('Could not add LayoutView to DOMWidgetView', true)); |
| 830 |
}); |
| 831 |
} |
| 832 |
} |
| 833 |
setStyle(style, oldStyle) { |
| 834 |
if (style) { |
| 835 |
this.stylePromise = this.stylePromise.then((oldStyleView) => { |
| 836 |
if (oldStyleView) { |
| 837 |
oldStyleView.unstyle(); |
| 838 |
this.stopListening(oldStyleView.model); |
| 839 |
oldStyleView.remove(); |
| 840 |
} |
| 841 |
return this.create_child_view(style) |
| 842 |
.then((view) => { |
| 843 |
// Trigger the displayed event of the child view. |
| 844 |
return this.displayed.then(() => { |
| 845 |
view.trigger('displayed'); |
| 846 |
this.trigger('style-changed'); |
| 847 |
// Unlike for the layout attribute, style changes don't |
| 848 |
// trigger Lumino resize messages. |
| 849 |
return view; |
| 850 |
}); |
| 851 |
}) |
| 852 |
.catch(utils.reject('Could not add styleView to DOMWidgetView', true)); |
| 853 |
}); |
| 854 |
} |
| 855 |
} |
| 856 |
updateTooltip() { |
| 857 |
const title = this.model.get('tooltip'); |
| 858 |
if (!title) { |
| 859 |
this.el.removeAttribute('title'); |
| 860 |
} |
| 861 |
else if (this.model.get('description').length === 0) { |
| 862 |
this.el.setAttribute('title', title); |
| 863 |
} |
| 864 |
} |
| 865 |
/** |
| 866 |
* Update the DOM classes applied to an element, default to this.el. |
| 867 |
*/ |
| 868 |
update_classes(old_classes, new_classes, el) { |
| 869 |
if (el === undefined) { |
| 870 |
el = this.el; |
| 871 |
} |
| 872 |
utils.difference(old_classes, new_classes).map(function (c) { |
| 873 |
if (el.classList) { |
| 874 |
// classList is not supported by IE for svg elements |
| 875 |
el.classList.remove(c); |
| 876 |
} |
| 877 |
else { |
| 878 |
el.setAttribute('class', el.getAttribute('class').replace(c, '')); |
| 879 |
} |
| 880 |
}); |
| 881 |
utils.difference(new_classes, old_classes).map(function (c) { |
| 882 |
if (el.classList) { |
| 883 |
// classList is not supported by IE for svg elements |
| 884 |
el.classList.add(c); |
| 885 |
} |
| 886 |
else { |
| 887 |
el.setAttribute('class', el.getAttribute('class').concat(' ', c)); |
| 888 |
} |
| 889 |
}); |
| 890 |
} |
| 891 |
/** |
| 892 |
* Update the DOM classes applied to the widget based on a single |
| 893 |
* trait's value. |
| 894 |
* |
| 895 |
* Given a trait value classes map, this function automatically |
| 896 |
* handles applying the appropriate classes to the widget element |
| 897 |
* and removing classes that are no longer valid. |
| 898 |
* |
| 899 |
* Parameters |
| 900 |
* ---------- |
| 901 |
* class_map: dictionary |
| 902 |
* Dictionary of trait values to class lists. |
| 903 |
* Example: |
| 904 |
* { |
| 905 |
* success: ['alert', 'alert-success'], |
| 906 |
* info: ['alert', 'alert-info'], |
| 907 |
* warning: ['alert', 'alert-warning'], |
| 908 |
* danger: ['alert', 'alert-danger'] |
| 909 |
* }; |
| 910 |
* trait_name: string |
| 911 |
* Name of the trait to check the value of. |
| 912 |
* el: optional DOM element handle, defaults to this.el |
| 913 |
* Element that the classes are applied to. |
| 914 |
*/ |
| 915 |
update_mapped_classes(class_map, trait_name, el) { |
| 916 |
let key = this.model.previous(trait_name); |
| 917 |
const old_classes = class_map[key] ? class_map[key] : []; |
| 918 |
key = this.model.get(trait_name); |
| 919 |
const new_classes = class_map[key] ? class_map[key] : []; |
| 920 |
this.update_classes(old_classes, new_classes, el || this.el); |
| 921 |
} |
| 922 |
set_mapped_classes(class_map, trait_name, el) { |
| 923 |
const key = this.model.get(trait_name); |
| 924 |
const new_classes = class_map[key] ? class_map[key] : []; |
| 925 |
this.update_classes([], new_classes, el || this.el); |
| 926 |
} |
| 927 |
_setElement(el) { |
| 928 |
if (this.luminoWidget) { |
| 929 |
this.luminoWidget.dispose(); |
| 930 |
} |
| 931 |
this.$el = el instanceof $ ? el : $(el); |
| 932 |
this.el = this.$el[0]; |
| 933 |
this.luminoWidget = new JupyterLuminoWidget({ |
| 934 |
node: el, |
| 935 |
view: this, |
| 936 |
}); |
| 937 |
} |
| 938 |
remove() { |
| 939 |
if (this.luminoWidget) { |
| 940 |
this.luminoWidget.dispose(); |
| 941 |
} |
| 942 |
return super.remove(); |
| 943 |
} |
| 944 |
processLuminoMessage(msg) { |
| 945 |
switch (msg.type) { |
| 946 |
case 'after-attach': |
| 947 |
this.trigger('displayed'); |
| 948 |
break; |
| 949 |
case 'show': |
| 950 |
this.trigger('shown'); |
| 951 |
break; |
| 952 |
} |
| 953 |
} |
| 954 |
_comm_live_update() { |
| 955 |
if (this.model.comm_live) { |
| 956 |
this.luminoWidget.removeClass('jupyter-widgets-disconnected'); |
| 957 |
} |
| 958 |
else { |
| 959 |
this.luminoWidget.addClass('jupyter-widgets-disconnected'); |
| 960 |
} |
| 961 |
} |
| 962 |
updateTabindex() { |
| 963 |
const tabbable = this.model.get('tabbable'); |
| 964 |
if (tabbable === true) { |
| 965 |
this.el.setAttribute('tabIndex', '0'); |
| 966 |
} |
| 967 |
else if (tabbable === false) { |
| 968 |
this.el.setAttribute('tabIndex', '-1'); |
| 969 |
} |
| 970 |
else if (tabbable === null) { |
| 971 |
this.el.removeAttribute('tabIndex'); |
| 972 |
} |
| 973 |
} |
| 974 |
/** |
| 975 |
* @deprecated Use {@link luminoWidget} instead (Since 8.0). |
| 976 |
*/ |
| 977 |
get pWidget() { |
| 978 |
return this.luminoWidget; |
| 979 |
} |
| 980 |
/** |
| 981 |
* @deprecated Use {@link luminoWidget} instead (Since 8.0). |
| 982 |
*/ |
| 983 |
set pWidget(value) { |
| 984 |
this.luminoWidget = value; |
| 985 |
} |
| 986 |
} |
| 987 |
//# sourceMappingURL=widget.js.map |