Debian Codegraph @

jupyter-widgets-base-manager/lib/manager-base.js

raw
1 // Copyright (c) Jupyter Development Team.
2 // Distributed under the terms of the Modified BSD License.
3 import * as widgets from '@jupyter-widgets/base';
4 import { PromiseDelegate, } from '@lumino/coreutils';
5 import { put_buffers, remove_buffers, resolvePromisesDict, reject, uuid, PROTOCOL_VERSION, } from '@jupyter-widgets/base';
6 import { base64ToBuffer, bufferToBase64, hexToBuffer } from './utils';
7 import { removeMath, replaceMath } from './latex';
8 import sanitize from 'sanitize-html';
9 const PROTOCOL_MAJOR_VERSION = PROTOCOL_VERSION.split('.', 1)[0];
10 /**
11 * The control comm target name.
12 */
13 export const CONTROL_COMM_TARGET = 'jupyter.widget.control';
14 /**
15 * The supported version for the control comm channel.
16 */
17 export const CONTROL_COMM_PROTOCOL_VERSION = '1.0.0';
18 /**
19 * Time (in ms) after which we consider the control comm target not responding.
20 */
21 export const CONTROL_COMM_TIMEOUT = 4000;
22 /**
23 * Sanitize HTML-formatted descriptions.
24 */
25 function default_inline_sanitize(s) {
26 const allowedTags = [
27 'a',
28 'abbr',
29 'b',
30 'code',
31 'em',
32 'i',
33 'img',
34 'li',
35 'ol',
36 'span',
37 'strong',
38 'ul',
39 ];
40 const allowedAttributes = {
41 '*': ['aria-*', 'class', 'style', 'title'],
42 a: ['href'],
43 img: ['src'],
44 style: ['media', 'type'],
45 };
46 return sanitize(s, {
47 allowedTags: allowedTags,
48 allowedAttributes: allowedAttributes,
49 });
50 }
51 /**
52 * Manager abstract base class
53 */
54 export class ManagerBase {
55 constructor() {
56 /**
57 * The comm target name to register
58 */
59 this.comm_target_name = 'jupyter.widget';
60 /**
61 * Dictionary of model ids and model instance promises
62 */
63 this._models = Object.create(null);
64 }
65 /**
66 * Modifies view options. Generally overloaded in custom widget manager
67 * implementations.
68 */
69 setViewOptions(options = {}) {
70 return options;
71 }
72 create_view(model, options = {}) {
73 const id = uuid();
74 const viewPromise = (model.state_change = model.state_change.then(async () => {
75 const _view_name = model.get('_view_name');
76 const _view_module = model.get('_view_module');
77 try {
78 const ViewType = (await this.loadViewClass(_view_name, _view_module, model.get('_view_module_version')));
79 const view = new ViewType({
80 model: model,
81 options: this.setViewOptions(options),
82 });
83 view.listenTo(model, 'destroy', view.remove);
84 await view.render();
85 // This presumes the view is added to the list of model views below
86 view.once('remove', () => {
87 if (model.views) {
88 delete model.views[id];
89 }
90 });
91 return view;
92 }
93 catch (e) {
94 console.error(`Could not create a view for model id ${model.model_id}`);
95 const msg = `Failed to create view for '${_view_name}' from module '${_view_module}' with model '${model.name}' from module '${model.module}'`;
96 const ModelCls = widgets.createErrorWidgetModel(e, msg);
97 const errorModel = new ModelCls();
98 const view = new widgets.ErrorWidgetView({
99 model: errorModel,
100 options: this.setViewOptions(options),
101 });
102 await view.render();
103 return view;
104 }
105 }));
106 if (model.views) {
107 model.views[id] = viewPromise;
108 }
109 return viewPromise;
110 }
111 /**
112 * callback handlers specific to a view
113 */
114 callbacks(view) {
115 return {};
116 }
117 /**
118 * Get a promise for a model by model id.
119 *
120 * #### Notes
121 * If the model is not found, the returned Promise object is rejected.
122 *
123 * If you would like to synchronously test if a model exists, use .has_model().
124 */
125 async get_model(model_id) {
126 const modelPromise = this._models[model_id];
127 if (modelPromise === undefined) {
128 throw new Error('widget model not found');
129 }
130 return modelPromise;
131 }
132 /**
133 * Returns true if the given model is registered, otherwise false.
134 *
135 * #### Notes
136 * This is a synchronous way to check if a model is registered.
137 */
138 has_model(model_id) {
139 return this._models[model_id] !== undefined;
140 }
141 /**
142 * Handle when a comm is opened.
143 */
144 handle_comm_open(comm, msg) {
145 const protocolVersion = (msg.metadata || {})['version'] || '';
146 if (protocolVersion.split('.', 1)[0] !== PROTOCOL_MAJOR_VERSION) {
147 const error = `Wrong widget protocol version: received protocol version '${protocolVersion}', but was expecting major version '${PROTOCOL_MAJOR_VERSION}'`;
148 console.error(error);
149 return Promise.reject(error);
150 }
151 const data = msg.content.data;
152 const buffer_paths = data.buffer_paths || [];
153 const buffers = msg.buffers || [];
154 put_buffers(data.state, buffer_paths, buffers);
155 return this.new_model({
156 model_name: data.state['_model_name'],
157 model_module: data.state['_model_module'],
158 model_module_version: data.state['_model_module_version'],
159 comm: comm,
160 }, data.state).catch(reject('Could not create a model.', true));
161 }
162 /**
163 * Create a comm and new widget model.
164 * @param options - same options as new_model but comm is not
165 * required and additional options are available.
166 * @param serialized_state - serialized model attributes.
167 */
168 new_widget(options, serialized_state = {}) {
169 let commPromise;
170 // we check to make sure the view information is provided, to help catch
171 // backwards incompatibility errors.
172 if (options.view_name === undefined ||
173 options.view_module === undefined ||
174 options.view_module_version === undefined) {
175 return Promise.reject('new_widget(...) must be given view information in the options.');
176 }
177 // If no comm is provided, a new comm is opened for the jupyter.widget
178 // target.
179 if (options.comm) {
180 commPromise = Promise.resolve(options.comm);
181 }
182 else {
183 commPromise = this._create_comm(this.comm_target_name, options.model_id, {
184 state: {
185 _model_module: options.model_module,
186 _model_module_version: options.model_module_version,
187 _model_name: options.model_name,
188 _view_module: options.view_module,
189 _view_module_version: options.view_module_version,
190 _view_name: options.view_name,
191 },
192 }, { version: PROTOCOL_VERSION });
193 }
194 // The options dictionary is copied since data will be added to it.
195 const options_clone = Object.assign({}, options);
196 // Create the model. In the case where the comm promise is rejected a
197 // comm-less model is still created with the required model id.
198 return commPromise.then((comm) => {
199 // Comm Promise Resolved.
200 options_clone.comm = comm;
201 const widget_model = this.new_model(options_clone, serialized_state);
202 return widget_model.then((model) => {
203 model.sync('create', model);
204 return model;
205 });
206 }, () => {
207 // Comm Promise Rejected.
208 if (!options_clone.model_id) {
209 options_clone.model_id = uuid();
210 }
211 return this.new_model(options_clone, serialized_state);
212 });
213 }
214 register_model(model_id, modelPromise) {
215 this._models[model_id] = modelPromise;
216 modelPromise.then((model) => {
217 model.once('comm:close', () => {
218 delete this._models[model_id];
219 });
220 });
221 }
222 /**
223 * Create and return a promise for a new widget model
224 *
225 * @param options - the options for creating the model.
226 * @param serialized_state - attribute values for the model.
227 *
228 * @example
229 * widget_manager.new_model({
230 * model_name: 'IntSlider',
231 * model_module: '@jupyter-widgets/controls',
232 * model_module_version: '1.0.0',
233 * model_id: 'u-u-i-d'
234 * }).then((model) => { console.log('Create success!', model); },
235 * (err) => {console.error(err)});
236 *
237 */
238 async new_model(options, serialized_state = {}) {
239 var _a, _b;
240 const model_id = (_a = options.model_id) !== null && _a !== void 0 ? _a : (_b = options.comm) === null || _b === void 0 ? void 0 : _b.comm_id;
241 if (!model_id) {
242 throw new Error('Neither comm nor model_id provided in options object. At least one must exist.');
243 }
244 options.model_id = model_id;
245 const modelPromise = this._make_model(options, serialized_state);
246 // this call needs to happen before the first `await`, see note in `set_state`:
247 this.register_model(model_id, modelPromise);
248 return await modelPromise;
249 }
250 /**
251 * Fetch all widgets states from the kernel using the control comm channel
252 * If this fails (control comm handler not implemented kernel side),
253 * it will fall back to `_loadFromKernelModels`.
254 *
255 * This is a utility function that can be used in subclasses.
256 */
257 async _loadFromKernel() {
258 // Try fetching all widget states through the control comm
259 let data;
260 let buffers;
261 try {
262 const initComm = await this._create_comm(CONTROL_COMM_TARGET, uuid(), {}, { version: CONTROL_COMM_PROTOCOL_VERSION });
263 await new Promise((resolve, reject) => {
264 initComm.on_msg((msg) => {
265 data = msg['content']['data'];
266 if (data.method !== 'update_states') {
267 console.warn(`
268 Unknown ${data.method} message on the Control channel
269 `);
270 return;
271 }
272 buffers = (msg.buffers || []).map((b) => {
273 if (b instanceof DataView) {
274 return b;
275 }
276 else {
277 return new DataView(b instanceof ArrayBuffer ? b : b.buffer);
278 }
279 });
280 resolve(null);
281 });
282 initComm.on_close(() => reject('Control comm was closed too early'));
283 // Send a states request msg
284 initComm.send({ method: 'request_states' }, {});
285 // Reject if we didn't get a response in time
286 setTimeout(() => reject('Control comm did not respond in time'), CONTROL_COMM_TIMEOUT);
287 });
288 initComm.close();
289 }
290 catch (error) {
291 // Fall back to the old implementation for old ipywidgets backend versions (ipywidgets<=7.6)
292 return this._loadFromKernelModels();
293 }
294 const states = data.states;
295 const bufferPaths = {};
296 const bufferGroups = {};
297 // Group buffers and buffer paths by widget id
298 for (let i = 0; i < data.buffer_paths.length; i++) {
299 const [widget_id, ...path] = data.buffer_paths[i];
300 const b = buffers[i];
301 if (!bufferPaths[widget_id]) {
302 bufferPaths[widget_id] = [];
303 bufferGroups[widget_id] = [];
304 }
305 bufferPaths[widget_id].push(path);
306 bufferGroups[widget_id].push(b);
307 }
308 // Create comms for all new widgets.
309 const widget_comms = await Promise.all(Object.keys(states).map(async (widget_id) => {
310 const comm = this.has_model(widget_id)
311 ? undefined
312 : await this._create_comm('jupyter.widget', widget_id);
313 return { widget_id, comm };
314 }));
315 await Promise.all(widget_comms.map(async ({ widget_id, comm }) => {
316 const state = states[widget_id];
317 // Put binary buffers
318 if (widget_id in bufferPaths) {
319 put_buffers(state, bufferPaths[widget_id], bufferGroups[widget_id]);
320 }
321 try {
322 if (comm) {
323 // This must be the first await in the code path that
324 // reaches here so that registering the model promise in
325 // new_model can register the widget promise before it may
326 // be required by other widgets.
327 await this.new_model({
328 model_name: state.model_name,
329 model_module: state.model_module,
330 model_module_version: state.model_module_version,
331 model_id: widget_id,
332 comm: comm,
333 }, state.state);
334 }
335 else {
336 // model already exists here
337 const model = await this.get_model(widget_id);
338 const deserializedState = await model.constructor._deserialize_state(state.state, this);
339 model.set_state(deserializedState);
340 }
341 }
342 catch (error) {
343 // Failed to create a widget model, we continue creating other models so that
344 // other widgets can render
345 console.error(error);
346 }
347 }));
348 }
349 /**
350 * Old implementation of fetching widget models one by one using
351 * the request_state message on each comm.
352 *
353 * This is a utility function that can be used in subclasses.
354 */
355 async _loadFromKernelModels() {
356 const comm_ids = await this._get_comm_info();
357 // For each comm id that we do not know about, create the comm, and request the state.
358 const widgets_info = await Promise.all(Object.keys(comm_ids).map(async (comm_id) => {
359 if (this.has_model(comm_id)) {
360 return;
361 }
362 const comm = await this._create_comm(this.comm_target_name, comm_id);
363 let msg_id = '';
364 const info = new PromiseDelegate();
365 comm.on_msg((msg) => {
366 if (msg.parent_header.msg_id === msg_id &&
367 msg.header.msg_type === 'comm_msg' &&
368 msg.content.data.method === 'update') {
369 const data = msg.content.data;
370 const buffer_paths = data.buffer_paths || [];
371 const buffers = msg.buffers || [];
372 put_buffers(data.state, buffer_paths, buffers);
373 info.resolve({ comm, msg });
374 }
375 });
376 msg_id = comm.send({
377 method: 'request_state',
378 }, this.callbacks(undefined));
379 return info.promise;
380 }));
381 // We put in a synchronization barrier here so that we don't have to
382 // topologically sort the restored widgets. `new_model` synchronously
383 // registers the widget ids before reconstructing their state
384 // asynchronously, so promises to every widget reference should be available
385 // by the time they are used.
386 await Promise.all(widgets_info.map(async (widget_info) => {
387 if (!widget_info) {
388 return;
389 }
390 const content = widget_info.msg.content;
391 await this.new_model({
392 model_name: content.data.state._model_name,
393 model_module: content.data.state._model_module,
394 model_module_version: content.data.state._model_module_version,
395 comm: widget_info.comm,
396 }, content.data.state);
397 }));
398 }
399 async _make_model(options, serialized_state = {}) {
400 const model_id = options.model_id;
401 const model_promise = this.loadModelClass(options.model_name, options.model_module, options.model_module_version);
402 let ModelType;
403 const makeErrorModel = (error, msg) => {
404 const Cls = widgets.createErrorWidgetModel(error, msg);
405 const widget_model = new Cls();
406 return widget_model;
407 };
408 try {
409 ModelType = await model_promise;
410 }
411 catch (error) {
412 const msg = 'Could not instantiate widget';
413 console.error(msg);
414 return makeErrorModel(error, msg);
415 }
416 if (!ModelType) {
417 const msg = 'Could not instantiate widget';
418 console.error(msg);
419 const error = new Error(`Cannot find model module ${options.model_module}@${options.model_module_version}, ${options.model_name}`);
420 return makeErrorModel(error, msg);
421 }
422 let widget_model;
423 try {
424 const attributes = await ModelType._deserialize_state(serialized_state, this);
425 const modelOptions = {
426 widget_manager: this,
427 model_id: model_id,
428 comm: options.comm,
429 };
430 widget_model = new ModelType(attributes, modelOptions);
431 }
432 catch (error) {
433 console.error(error);
434 const msg = `Model class '${options.model_name}' from module '${options.model_module}' is loaded but can not be instantiated`;
435 widget_model = makeErrorModel(error, msg);
436 }
437 widget_model.name = options.model_name;
438 widget_model.module = options.model_module;
439 return widget_model;
440 }
441 /**
442 * Close all widgets and empty the widget state.
443 * @return Promise that resolves when the widget state is cleared.
444 */
445 clear_state() {
446 return resolvePromisesDict(this._models).then((models) => {
447 Object.keys(models).forEach((id) => models[id].close());
448 this._models = Object.create(null);
449 });
450 }
451 /**
452 * Asynchronously get the state of the widget manager.
453 *
454 * This includes all of the widget models, and follows the format given in
455 * the @jupyter-widgets/schema package.
456 *
457 * @param options - The options for what state to return.
458 * @returns Promise for a state dictionary
459 */
460 get_state(options = {}) {
461 const modelPromises = Object.keys(this._models).map((id) => this._models[id]);
462 return Promise.all(modelPromises).then((models) => {
463 return serialize_state(models, options);
464 });
465 }
466 /**
467 * Set the widget manager state.
468 *
469 * @param state - a Javascript object conforming to the application/vnd.jupyter.widget-state+json spec.
470 *
471 * Reconstructs all of the widget models in the state, merges that with the
472 * current manager state, and then attempts to redisplay the widgets in the
473 * state.
474 */
475 set_state(state) {
476 // Check to make sure that it's the same version we are parsing.
477 if (!(state.version_major && state.version_major <= 2)) {
478 throw 'Unsupported widget state format';
479 }
480 const models = state.state;
481 // Recreate all the widget models for the given widget manager state.
482 const all_models = this._get_comm_info().then((live_comms) => {
483 /* Note: It is currently safe to just loop over the models in any order,
484 given that the following holds (does at the time of writing):
485 1: any call to `new_model` with state registers the model promise (e.g. with `register_model`)
486 synchronously (before it's first `await` statement).
487 2: any calls to a model constructor or the `set_state` method on a model,
488 happens asynchronously (in a `then` clause, or after an `await` statement).
489
490 Without these assumptions, one risks trying to set model state with a reference
491 to another model that doesn't exist yet!
492 */
493 return Promise.all(Object.keys(models).map((model_id) => {
494 // First put back the binary buffers
495 const decode = {
496 base64: base64ToBuffer,
497 hex: hexToBuffer,
498 };
499 const model = models[model_id];
500 const modelState = model.state;
501 if (model.buffers) {
502 const bufferPaths = model.buffers.map((b) => b.path);
503 // put_buffers expects buffers to be DataViews
504 const buffers = model.buffers.map((b) => new DataView(decode[b.encoding](b.data)));
505 put_buffers(model.state, bufferPaths, buffers);
506 }
507 // If the model has already been created, set its state and then
508 // return it.
509 if (this.has_model(model_id)) {
510 return this.get_model(model_id).then((model) => {
511 // deserialize state
512 return model.constructor
513 ._deserialize_state(modelState || {}, this)
514 .then((attributes) => {
515 model.set_state(attributes); // case 2
516 return model;
517 });
518 });
519 }
520 const modelCreate = {
521 model_id: model_id,
522 model_name: model.model_name,
523 model_module: model.model_module,
524 model_module_version: model.model_module_version,
525 };
526 if (Object.prototype.hasOwnProperty.call(live_comms, 'model_id')) {
527 // live comm
528 // This connects to an existing comm if it exists, and
529 // should *not* send a comm open message.
530 return this._create_comm(this.comm_target_name, model_id).then((comm) => {
531 modelCreate.comm = comm;
532 return this.new_model(modelCreate); // No state, so safe wrt. case 1
533 });
534 }
535 else {
536 return this.new_model(modelCreate, modelState); // case 1
537 }
538 }));
539 });
540 return all_models;
541 }
542 /**
543 * Disconnect the widget manager from the kernel, setting each model's comm
544 * as dead.
545 */
546 disconnect() {
547 Object.keys(this._models).forEach((i) => {
548 this._models[i].then((model) => {
549 model.comm_live = false;
550 });
551 });
552 }
553 /**
554 * Resolve a URL relative to the current notebook location.
555 *
556 * The default implementation just returns the original url.
557 */
558 resolveUrl(url) {
559 return Promise.resolve(url);
560 }
561 inline_sanitize(source) {
562 const parts = removeMath(source);
563 // Sanitize tags for inline output.
564 const sanitized = default_inline_sanitize(parts['text']);
565 return replaceMath(sanitized, parts['math']);
566 }
567 async loadModelClass(className, moduleName, moduleVersion) {
568 try {
569 const promise = this.loadClass(className, moduleName, moduleVersion);
570 await promise;
571 return promise;
572 }
573 catch (error) {
574 console.error(error);
575 const msg = `Failed to load model class '${className}' from module '${moduleName}'`;
576 return widgets.createErrorWidgetModel(error, msg);
577 }
578 }
579 async loadViewClass(className, moduleName, moduleVersion) {
580 try {
581 const promise = this.loadClass(className, moduleName, moduleVersion);
582 await promise;
583 return promise;
584 }
585 catch (error) {
586 console.error(error);
587 const msg = `Failed to load view class '${className}' from module '${moduleName}'`;
588 return widgets.createErrorWidgetView(error, msg);
589 }
590 }
591 /**
592 * Filter serialized widget state to remove any ID's already present in manager.
593 *
594 * @param {*} state Serialized state to filter
595 *
596 * @returns {*} A copy of the state, with its 'state' attribute filtered
597 */
598 filterExistingModelState(serialized_state) {
599 let models = serialized_state.state;
600 models = Object.keys(models)
601 .filter((model_id) => !this.has_model(model_id))
602 .reduce((res, model_id) => {
603 res[model_id] = models[model_id];
604 return res;
605 }, {});
606 return Object.assign(Object.assign({}, serialized_state), { state: models });
607 }
608 }
609 /**
610 * Serialize an array of widget models
611 *
612 * #### Notes
613 * The return value follows the format given in the
614 * @jupyter-widgets/schema package.
615 */
616 export function serialize_state(models, options = {}) {
617 const state = {};
618 models.forEach((model) => {
619 const model_id = model.model_id;
620 const split = remove_buffers(model.serialize(model.get_state(options.drop_defaults)));
621 const buffers = split.buffers.map((buffer, index) => {
622 return {
623 data: bufferToBase64(buffer),
624 path: split.buffer_paths[index],
625 encoding: 'base64',
626 };
627 });
628 state[model_id] = {
629 model_name: model.name,
630 model_module: model.module,
631 model_module_version: model.get('_model_module_version'),
632 state: split.state,
633 };
634 // To save space, only include the buffers key if we have buffers
635 if (buffers.length > 0) {
636 state[model_id].buffers = buffers;
637 }
638 });
639 return { version_major: 2, version_minor: 0, state: state };
640 }
641 //# sourceMappingURL=manager-base.js.map