Foundational classes and utilities for building interactive widgets in Jupyter environments
—
Pending
Does it follow best practices?
Impact
Pending
No eval scenarios have been run
Pending
The risk profile of this skill
The core widget classes provide the foundation for all Jupyter interactive widgets, implementing the model-view architecture with Backbone.js integration and kernel communication.
Base class for all widget models, providing state management, serialization, and communication with Jupyter kernels.
/**
* Base class for all widget models, extends Backbone.Model
*/
class WidgetModel extends Backbone.Model {
/**
* Initialize the widget model with required options
* @param attributes - Initial model attributes
* @param options - Widget model options including widget_manager and model_id
*/
initialize(attributes: Backbone.ObjectHash, options: IBackboneModelOptions): void;
/**
* Send a custom message over the comm channel
* @param content - Message content as JSON value
* @param callbacks - Optional message callbacks
* @param buffers - Optional binary buffers
*/
send(content: JSONValue, callbacks?: ICallbacks, buffers?: ArrayBuffer[] | ArrayBufferView[]): void;
/**
* Close the model and clean up resources
* @param comm_closed - Whether the comm is already being closed
* @returns Promise that resolves when cleanup is complete
*/
close(comm_closed?: boolean): Promise<void>;
/**
* Get the serializable state of the model
* @param drop_defaults - Whether to exclude default values
* @returns Serializable state object
*/
get_state(drop_defaults?: boolean): JSONObject;
/**
* Set state from the backend (internal use)
* @param state - State object from kernel
*/
set_state(state: Dict<unknown>): void;
/**
* Push state changes to the backend
* @param callbacks - Optional callbacks for the sync operation
*/
save_changes(callbacks?: {}): void;
/**
* Serialize widget state for transmission
* @param state - State object to serialize
* @returns Serialized state
*/
serialize(state: Dict<any>): JSONObject;
/**
* Listen to changes on multiple attributes at once
* @param keys - Array of attribute names to watch
* @param callback - Callback function to execute
* @param context - Context for callback execution
*/
on_some_change(keys: string[], callback: (...args: any[]) => void, context: any): void;
/**
* JSON representation of the model (returns model reference)
* @returns Model reference string
*/
toJSON(): string;
// Properties
widget_manager: IWidgetManager;
model_id: string;
views?: { [key: string]: Promise<WidgetView> };
state_change: Promise<any>;
comm?: IClassicComm;
comm_live: boolean;
// Static properties
static serializers: ISerializers;
}
interface IBackboneModelOptions extends Backbone.ModelSetOptions {
model_id: string;
comm?: any;
widget_manager: any;
}
interface ISerializers {
[key: string]: {
deserialize?: (value?: any, manager?: IWidgetManager) => any;
serialize?: (value?: any, widget?: WidgetModel) => any;
};
}Usage Examples:
// Create a custom model
class CounterModel extends WidgetModel {
defaults() {
return {
...super.defaults(),
_model_name: 'CounterModel',
_view_name: 'CounterView',
value: 0
};
}
}
// Send custom message
model.send({ action: 'reset', timestamp: Date.now() });
// Listen to multiple attributes
model.on_some_change(['value', 'label'], this.handleUpdate, this);
// Get current state
const state = model.get_state(true); // drops defaultsExtension of WidgetModel specifically for DOM-based widgets with layout and style integration.
/**
* Extension of WidgetModel for DOM-based widgets
*/
class DOMWidgetModel extends WidgetModel {
static serializers: ISerializers;
/**
* Default attributes for DOM widgets
*/
defaults(): Backbone.ObjectHash;
}The DOMWidgetModel includes additional default attributes:
_dom_classes: string[] - CSS classes to apply to the widget elementtabbable: boolean | null - Tab navigation behavior (true, false, or null for default)tooltip: string | null - Tooltip text for the widgetBase class for all widget views, providing rendering, event handling, and child view management.
/**
* Base class for all widget views, extends NativeView
*/
class WidgetView extends NativeView<WidgetModel> {
/**
* Initialize the view with parameters
* @param parameters - View initialization parameters
*/
initialize(parameters: WidgetView.IInitializeParameters): void;
/**
* Update the view to match the current model state
* @param options - Update options
*/
update(options?: any): void;
/**
* Render the view (override in subclasses)
* @returns The view or a promise to the view
*/
render(): any;
/**
* Create a child view for a given model
* @param child_model - Model for the child view
* @param options - Options for view creation
* @returns Promise that resolves to the child view
*/
create_child_view<VT extends WidgetView = WidgetView>(
child_model: WidgetModel,
options?: any
): Promise<VT>;
/**
* Send a custom message associated with this view
* @param content - Message content
* @param buffers - Optional binary buffers
*/
send(content: {}, buffers?: ArrayBuffer[] | ArrayBufferView[]): void;
/**
* Trigger model save with view-specific callbacks
*/
touch(): void;
/**
* Get message callbacks for this view
* @returns Callback configuration
*/
callbacks(): ICallbacks;
/**
* Handle custom messages sent to the view
* @param content - Message content (focus/blur commands)
*/
handle_message(content: any): void;
// Properties
model: WidgetModel;
displayed: Promise<WidgetView>;
options: any;
}
namespace WidgetView {
export interface IInitializeParameters<T extends WidgetModel = WidgetModel> extends Backbone.ViewOptions<T> {
options: any;
}
}Usage Examples:
// Custom view implementation
class MyWidgetView extends WidgetView {
render() {
this.el.innerHTML = '<button>Click me</button>';
this.el.onclick = () => {
this.model.set('clicks', this.model.get('clicks') + 1);
this.touch(); // Save changes
};
}
update() {
// Update view based on model changes
this.el.textContent = `Clicked ${this.model.get('clicks')} times`;
}
}
// Create child views
const childView = await this.create_child_view(childModel);
this.el.appendChild(childView.el);
// Send custom message
this.send({ command: 'highlight', color: 'red' });Extension of WidgetView with DOM manipulation utilities, layout/style management, and Lumino integration.
/**
* Extension of WidgetView for DOM manipulation and styling
*/
class DOMWidgetView extends WidgetView {
/**
* Set the layout model for this view
* @param layout - Layout model to apply
* @param oldLayout - Previous layout model (for cleanup)
*/
setLayout(layout: LayoutModel, oldLayout?: LayoutModel): void;
/**
* Set the style model for this view
* @param style - Style model to apply
* @param oldStyle - Previous style model (for cleanup)
*/
setStyle(style: StyleModel, oldStyle?: StyleModel): void;
/**
* Update DOM classes on an element
* @param old_classes - Classes to remove
* @param new_classes - Classes to add
* @param el - Target element (defaults to this.el)
*/
update_classes(old_classes: string[], new_classes: string[], el?: HTMLElement): void;
/**
* Update classes based on a trait value mapping
* @param class_map - Map of trait values to class arrays
* @param trait_name - Name of the trait to check
* @param el - Target element (defaults to this.el)
*/
update_mapped_classes(class_map: Dict<string[]>, trait_name: string, el?: HTMLElement): void;
/**
* Set classes from a trait value mapping
* @param class_map - Map of trait values to class arrays
* @param trait_name - Name of the trait to check
* @param el - Target element (defaults to this.el)
*/
set_mapped_classes(class_map: Dict<string[]>, trait_name: string, el?: HTMLElement): void;
/**
* Update tooltip attribute based on model
*/
updateTooltip(): void;
/**
* Update tabindex attribute based on tabbable trait
*/
updateTabindex(): void;
/**
* Process Lumino widget messages
* @param msg - Lumino message to process
*/
processLuminoMessage(msg: Message): void;
// Properties
el: HTMLElement;
luminoWidget: Widget;
layoutPromise: Promise<any>;
stylePromise: Promise<any>;
}Usage Examples:
// Update classes based on state
this.update_classes(['old-state'], ['new-state', 'active']);
// Use class mapping for different states
const stateClasses = {
'success': ['alert', 'alert-success'],
'warning': ['alert', 'alert-warning'],
'error': ['alert', 'alert-danger']
};
this.update_mapped_classes(stateClasses, 'status');
// Custom layout handling
this.displayed.then(() => {
this.setLayout(this.model.get('layout'));
this.setStyle(this.model.get('style'));
});Wrapper class for integrating Jupyter widgets with the Lumino widget system.
/**
* Lumino widget wrapper for Jupyter widgets
*/
class JupyterLuminoWidget extends Widget {
constructor(options: Widget.IOptions & JupyterLuminoWidget.IOptions);
/**
* Dispose the widget and associated view
*/
dispose(): void;
/**
* Process Lumino messages and forward to view
* @param msg - Lumino message
*/
processMessage(msg: Message): void;
}
namespace JupyterLuminoWidget {
export interface IOptions {
view: DOMWidgetView;
}
}Panel wrapper for Jupyter widgets in Lumino layouts.
/**
* Lumino panel wrapper for Jupyter widgets
*/
class JupyterLuminoPanelWidget extends Panel {
constructor(options: JupyterLuminoWidget.IOptions & Panel.IOptions);
dispose(): void;
processMessage(msg: Message): void;
}Utilities for serializing and deserializing widget model references in complex data structures.
/**
* Replace model IDs with model instances recursively
* @param value - Value containing model references
* @param manager - Widget manager for model resolution
* @returns Promise resolving to value with unpacked models
*/
function unpack_models(
value: any | Dict<unknown> | string | (Dict<unknown> | string)[],
manager?: IWidgetManager
): Promise<WidgetModel | Dict<WidgetModel> | WidgetModel[] | any>;
/**
* Replace model instances with model IDs recursively
* @param value - Value containing model instances
* @param widget - Widget context for serialization
* @returns Value with packed model references
*/
function pack_models(
value: WidgetModel | Dict<WidgetModel> | WidgetModel[] | any,
widget?: WidgetModel
): any | Dict<unknown> | string | (Dict<unknown> | string)[];Usage Examples:
// Unpack model references in received data
const processedData = await unpack_models(rawData, this.widget_manager);
// Pack models for transmission
const serializedData = pack_models(dataWithModels, this);