CtrlK
BlogDocsLog inGet started
Tessl Logo

tessl/npm-jupyter-widgets--base

Foundational classes and utilities for building interactive widgets in Jupyter environments

Pending
Quality

Pending

Does it follow best practices?

Impact

Pending

No eval scenarios have been run

SecuritybySnyk

Pending

The risk profile of this skill

Overview
Eval results
Files

widget-manager.mddocs/

Widget Manager

The widget manager interface provides the central system for managing widget lifecycles, creation, registration, and communication within Jupyter environments.

Capabilities

IWidgetManager Interface

Core interface that all widget managers must implement for managing models, views, and communication.

/**
 * Interface for widget managers that handle model and view lifecycle
 */
interface IWidgetManager {
  /**
   * Get a model by its unique identifier
   * @param model_id - Unique model identifier
   * @returns Promise that resolves to the widget model, or undefined if not found
   */
  get_model(model_id: string): Promise<WidgetModel>;

  /**
   * Check if a model is registered with the manager
   * @param model_id - Model identifier to check
   * @returns True if model exists, false otherwise
   */
  has_model(model_id: string): boolean;

  /**
   * Register a model instance with the manager
   * @param model_id - Unique identifier for the model
   * @param modelPromise - Promise that resolves to the model instance
   */
  register_model(model_id: string, modelPromise: Promise<WidgetModel>): void;

  /**
   * Create a new widget with communication channel
   * @param options - Widget creation options (includes view information)
   * @param serialized_state - Optional initial state for the widget
   * @returns Promise that resolves to the created widget model
   */
  new_widget(options: IWidgetOptions, serialized_state?: JSONObject): Promise<WidgetModel>;

  /**
   * Create a new model instance
   * @param options - Model creation options
   * @param serialized_state - Optional initial state for the model
   * @returns Promise that resolves to the created model
   */
  new_model(options: IModelOptions, serialized_state?: JSONObject): Promise<WidgetModel>;

  /**
   * Create a view for a given model
   * @param model - Widget model to create view for
   * @param options - View creation options
   * @returns Promise that resolves to the created view
   */
  create_view<VT extends DOMWidgetView = DOMWidgetView>(
    model: DOMWidgetModel,
    options?: unknown
  ): Promise<VT>;
  create_view<VT extends WidgetView = WidgetView>(
    model: WidgetModel,
    options?: unknown
  ): Promise<VT>;

  /**
   * Get callback handlers for a specific view
   * @param view - View to get callbacks for (optional)
   * @returns Callback configuration object
   */
  callbacks(view?: WidgetView): ICallbacks;

  /**
   * Resolve a URL relative to the current notebook location
   * @param url - URL to resolve
   * @returns Promise that resolves to the absolute URL
   */
  resolveUrl(url: string): Promise<string>;

  /**
   * Sanitize HTML content for inline display
   * @param s - HTML string to sanitize
   * @returns Sanitized HTML string
   */
  inline_sanitize(s: string): string;
}

Usage Examples:

// Get existing model
const model = await widgetManager.get_model('widget-123');

// Check if model exists
if (widgetManager.has_model('widget-123')) {
  // Model is available
}

// Create new widget with comm
const widget = await widgetManager.new_widget({
  model_name: 'IntSlider',
  model_module: '@jupyter-widgets/controls',
  model_module_version: '1.0.0',
  view_name: 'IntSliderView',
  view_module: '@jupyter-widgets/controls',
  view_module_version: '1.0.0'
}, { value: 50, min: 0, max: 100 });

// Create view for model
const view = await widgetManager.create_view(model);

Model Creation Options

Configuration options for creating widget models and establishing their metadata.

/**
 * Options for creating widget models
 */
interface IModelOptions {
  /**
   * Target name of the widget model class to create
   */
  model_name: string;

  /**
   * Module name containing the widget model class
   */
  model_module: string;

  /**
   * Semver version requirement for the model module
   */
  model_module_version: string;

  /**
   * Target name of the widget view class (optional for model-only creation)
   */
  view_name?: string | null;

  /**
   * Module name containing the widget view class
   */
  view_module?: string | null;

  /**
   * Semver version requirement for the view module
   */
  view_module_version?: string;

  /**
   * Communication object for kernel interaction
   */
  comm?: any;

  /**
   * Unique identifier for the model (auto-generated if not provided)
   */
  model_id?: string;
}

Widget Creation Options

Extended options for creating complete widgets with both model and view components.

/**
 * Options for creating connected widgets (requires view information)
 */
interface IWidgetOptions extends IModelOptions {
  /**
   * Target name of the widget model class to create (required)
   */
  model_name: string;

  /**
   * Module name containing the widget model class (required)
   */
  model_module: string;

  /**
   * Semver version requirement for the model module (required)
   */
  model_module_version: string;

  /**
   * Target name of the widget view class (required for widgets)
   */
  view_name: string | null;

  /**
   * Module name containing the widget view class (required for widgets)
   */
  view_module: string | null;

  /**
   * Semver version requirement for the view module (required)
   */
  view_module_version: string;

  /**
   * Communication object for kernel interaction
   */
  comm?: IClassicComm;

  /**
   * Unique identifier for the model
   */
  model_id?: string;
}

Usage Examples:

// Create model-only (no view)
const modelOptions: IModelOptions = {
  model_name: 'DataModel',
  model_module: 'my-widgets',
  model_module_version: '1.0.0',
  model_id: 'unique-data-model'
};
const dataModel = await widgetManager.new_model(modelOptions);

// Create complete widget
const widgetOptions: IWidgetOptions = {
  model_name: 'SliderModel',
  model_module: '@jupyter-widgets/controls',
  model_module_version: '1.0.0',
  view_name: 'SliderView',
  view_module: '@jupyter-widgets/controls',
  view_module_version: '1.0.0'
};
const slider = await widgetManager.new_widget(widgetOptions, { value: 42 });

Widget Manager Implementation Patterns

Typical Manager Workflow

Common patterns for implementing and using widget managers:

// Manager initialization
class MyWidgetManager implements IWidgetManager {
  private models: Map<string, Promise<WidgetModel>> = new Map();
  
  async get_model(model_id: string): Promise<WidgetModel> {
    const modelPromise = this.models.get(model_id);
    if (!modelPromise) {
      throw new Error(`Model ${model_id} not found`);
    }
    return modelPromise;
  }
  
  has_model(model_id: string): boolean {
    return this.models.has(model_id);
  }
  
  register_model(model_id: string, modelPromise: Promise<WidgetModel>): void {
    this.models.set(model_id, modelPromise);
  }
  
  async new_model(options: IModelOptions, state?: JSONObject): Promise<WidgetModel> {
    // Load model class
    const ModelClass = await this.loadModelClass(options.model_module, options.model_name);
    
    // Create instance
    const model = new ModelClass(state || {}, {
      model_id: options.model_id || this.generateId(),
      widget_manager: this,
      comm: options.comm
    });
    
    // Register and return
    this.register_model(model.model_id, Promise.resolve(model));
    return model;
  }
  
  // Additional implementation methods...
}

View Creation Patterns

// Create views with proper error handling
async createWidgetView(model: WidgetModel): Promise<WidgetView> {
  try {
    const view = await this.widgetManager.create_view(model, {
      parent: this.parentView
    });
    
    // Setup view lifecycle
    view.displayed.then(() => {
      console.log('View displayed');
    });
    
    return view;
  } catch (error) {
    console.error('Failed to create view:', error);
    throw error;
  }
}

// Manage view collections
const views = await Promise.all(
  models.map(model => this.widgetManager.create_view(model))
);

Model Registration and Lookup

// Register models with manager
const registerWidget = async (modelClass: typeof WidgetModel, initialState: any) => {
  const model = new modelClass(initialState, {
    model_id: generateUniqueId(),
    widget_manager: widgetManager
  });
  
  widgetManager.register_model(model.model_id, Promise.resolve(model));
  return model;
};

// Lookup and use existing models
const findOrCreateModel = async (modelId: string, fallbackOptions: IModelOptions) => {
  if (widgetManager.has_model(modelId)) {
    return await widgetManager.get_model(modelId);
  } else {
    return await widgetManager.new_model({
      ...fallbackOptions,
      model_id: modelId
    });
  }
};

Communication Integration

// Setup callbacks for widget communication
const setupWidgetCallbacks = (view: WidgetView): ICallbacks => {
  return widgetManager.callbacks(view);
};

// Handle model creation with communication
const createConnectedWidget = async (comm: IClassicComm, options: IWidgetOptions) => {
  const widget = await widgetManager.new_widget({
    ...options,
    comm: comm,
    model_id: comm.comm_id
  });
  
  // Widget is now connected to kernel
  return widget;
};

docs

communication.md

error-handling.md

index.md

layout-style.md

nativeview.md

registry.md

utilities.md

widget-classes.md

widget-manager.md

tile.json