0
# Core Widget Classes
1
2
The core widget classes provide the foundation for all Jupyter interactive widgets, implementing the model-view architecture with Backbone.js integration and kernel communication.
3
4
## Capabilities
5
6
### WidgetModel
7
8
Base class for all widget models, providing state management, serialization, and communication with Jupyter kernels.
9
10
```typescript { .api }
11
/**
12
* Base class for all widget models, extends Backbone.Model
13
*/
14
class WidgetModel extends Backbone.Model {
15
/**
16
* Initialize the widget model with required options
17
* @param attributes - Initial model attributes
18
* @param options - Widget model options including widget_manager and model_id
19
*/
20
initialize(attributes: Backbone.ObjectHash, options: IBackboneModelOptions): void;
21
22
/**
23
* Send a custom message over the comm channel
24
* @param content - Message content as JSON value
25
* @param callbacks - Optional message callbacks
26
* @param buffers - Optional binary buffers
27
*/
28
send(content: JSONValue, callbacks?: ICallbacks, buffers?: ArrayBuffer[] | ArrayBufferView[]): void;
29
30
/**
31
* Close the model and clean up resources
32
* @param comm_closed - Whether the comm is already being closed
33
* @returns Promise that resolves when cleanup is complete
34
*/
35
close(comm_closed?: boolean): Promise<void>;
36
37
/**
38
* Get the serializable state of the model
39
* @param drop_defaults - Whether to exclude default values
40
* @returns Serializable state object
41
*/
42
get_state(drop_defaults?: boolean): JSONObject;
43
44
/**
45
* Set state from the backend (internal use)
46
* @param state - State object from kernel
47
*/
48
set_state(state: Dict<unknown>): void;
49
50
/**
51
* Push state changes to the backend
52
* @param callbacks - Optional callbacks for the sync operation
53
*/
54
save_changes(callbacks?: {}): void;
55
56
/**
57
* Serialize widget state for transmission
58
* @param state - State object to serialize
59
* @returns Serialized state
60
*/
61
serialize(state: Dict<any>): JSONObject;
62
63
/**
64
* Listen to changes on multiple attributes at once
65
* @param keys - Array of attribute names to watch
66
* @param callback - Callback function to execute
67
* @param context - Context for callback execution
68
*/
69
on_some_change(keys: string[], callback: (...args: any[]) => void, context: any): void;
70
71
/**
72
* JSON representation of the model (returns model reference)
73
* @returns Model reference string
74
*/
75
toJSON(): string;
76
77
// Properties
78
widget_manager: IWidgetManager;
79
model_id: string;
80
views?: { [key: string]: Promise<WidgetView> };
81
state_change: Promise<any>;
82
comm?: IClassicComm;
83
comm_live: boolean;
84
85
// Static properties
86
static serializers: ISerializers;
87
}
88
89
interface IBackboneModelOptions extends Backbone.ModelSetOptions {
90
model_id: string;
91
comm?: any;
92
widget_manager: any;
93
}
94
95
interface ISerializers {
96
[key: string]: {
97
deserialize?: (value?: any, manager?: IWidgetManager) => any;
98
serialize?: (value?: any, widget?: WidgetModel) => any;
99
};
100
}
101
```
102
103
**Usage Examples:**
104
105
```typescript
106
// Create a custom model
107
class CounterModel extends WidgetModel {
108
defaults() {
109
return {
110
...super.defaults(),
111
_model_name: 'CounterModel',
112
_view_name: 'CounterView',
113
value: 0
114
};
115
}
116
}
117
118
// Send custom message
119
model.send({ action: 'reset', timestamp: Date.now() });
120
121
// Listen to multiple attributes
122
model.on_some_change(['value', 'label'], this.handleUpdate, this);
123
124
// Get current state
125
const state = model.get_state(true); // drops defaults
126
```
127
128
### DOMWidgetModel
129
130
Extension of WidgetModel specifically for DOM-based widgets with layout and style integration.
131
132
```typescript { .api }
133
/**
134
* Extension of WidgetModel for DOM-based widgets
135
*/
136
class DOMWidgetModel extends WidgetModel {
137
static serializers: ISerializers;
138
139
/**
140
* Default attributes for DOM widgets
141
*/
142
defaults(): Backbone.ObjectHash;
143
}
144
```
145
146
The DOMWidgetModel includes additional default attributes:
147
- `_dom_classes: string[]` - CSS classes to apply to the widget element
148
- `tabbable: boolean | null` - Tab navigation behavior (true, false, or null for default)
149
- `tooltip: string | null` - Tooltip text for the widget
150
151
### WidgetView
152
153
Base class for all widget views, providing rendering, event handling, and child view management.
154
155
```typescript { .api }
156
/**
157
* Base class for all widget views, extends NativeView
158
*/
159
class WidgetView extends NativeView<WidgetModel> {
160
/**
161
* Initialize the view with parameters
162
* @param parameters - View initialization parameters
163
*/
164
initialize(parameters: WidgetView.IInitializeParameters): void;
165
166
/**
167
* Update the view to match the current model state
168
* @param options - Update options
169
*/
170
update(options?: any): void;
171
172
/**
173
* Render the view (override in subclasses)
174
* @returns The view or a promise to the view
175
*/
176
render(): any;
177
178
/**
179
* Create a child view for a given model
180
* @param child_model - Model for the child view
181
* @param options - Options for view creation
182
* @returns Promise that resolves to the child view
183
*/
184
create_child_view<VT extends WidgetView = WidgetView>(
185
child_model: WidgetModel,
186
options?: any
187
): Promise<VT>;
188
189
/**
190
* Send a custom message associated with this view
191
* @param content - Message content
192
* @param buffers - Optional binary buffers
193
*/
194
send(content: {}, buffers?: ArrayBuffer[] | ArrayBufferView[]): void;
195
196
/**
197
* Trigger model save with view-specific callbacks
198
*/
199
touch(): void;
200
201
/**
202
* Get message callbacks for this view
203
* @returns Callback configuration
204
*/
205
callbacks(): ICallbacks;
206
207
/**
208
* Handle custom messages sent to the view
209
* @param content - Message content (focus/blur commands)
210
*/
211
handle_message(content: any): void;
212
213
// Properties
214
model: WidgetModel;
215
displayed: Promise<WidgetView>;
216
options: any;
217
}
218
219
namespace WidgetView {
220
export interface IInitializeParameters<T extends WidgetModel = WidgetModel> extends Backbone.ViewOptions<T> {
221
options: any;
222
}
223
}
224
```
225
226
**Usage Examples:**
227
228
```typescript
229
// Custom view implementation
230
class MyWidgetView extends WidgetView {
231
render() {
232
this.el.innerHTML = '<button>Click me</button>';
233
this.el.onclick = () => {
234
this.model.set('clicks', this.model.get('clicks') + 1);
235
this.touch(); // Save changes
236
};
237
}
238
239
update() {
240
// Update view based on model changes
241
this.el.textContent = `Clicked ${this.model.get('clicks')} times`;
242
}
243
}
244
245
// Create child views
246
const childView = await this.create_child_view(childModel);
247
this.el.appendChild(childView.el);
248
249
// Send custom message
250
this.send({ command: 'highlight', color: 'red' });
251
```
252
253
### DOMWidgetView
254
255
Extension of WidgetView with DOM manipulation utilities, layout/style management, and Lumino integration.
256
257
```typescript { .api }
258
/**
259
* Extension of WidgetView for DOM manipulation and styling
260
*/
261
class DOMWidgetView extends WidgetView {
262
/**
263
* Set the layout model for this view
264
* @param layout - Layout model to apply
265
* @param oldLayout - Previous layout model (for cleanup)
266
*/
267
setLayout(layout: LayoutModel, oldLayout?: LayoutModel): void;
268
269
/**
270
* Set the style model for this view
271
* @param style - Style model to apply
272
* @param oldStyle - Previous style model (for cleanup)
273
*/
274
setStyle(style: StyleModel, oldStyle?: StyleModel): void;
275
276
/**
277
* Update DOM classes on an element
278
* @param old_classes - Classes to remove
279
* @param new_classes - Classes to add
280
* @param el - Target element (defaults to this.el)
281
*/
282
update_classes(old_classes: string[], new_classes: string[], el?: HTMLElement): void;
283
284
/**
285
* Update classes based on a trait value mapping
286
* @param class_map - Map of trait values to class arrays
287
* @param trait_name - Name of the trait to check
288
* @param el - Target element (defaults to this.el)
289
*/
290
update_mapped_classes(class_map: Dict<string[]>, trait_name: string, el?: HTMLElement): void;
291
292
/**
293
* Set classes from a trait value mapping
294
* @param class_map - Map of trait values to class arrays
295
* @param trait_name - Name of the trait to check
296
* @param el - Target element (defaults to this.el)
297
*/
298
set_mapped_classes(class_map: Dict<string[]>, trait_name: string, el?: HTMLElement): void;
299
300
/**
301
* Update tooltip attribute based on model
302
*/
303
updateTooltip(): void;
304
305
/**
306
* Update tabindex attribute based on tabbable trait
307
*/
308
updateTabindex(): void;
309
310
/**
311
* Process Lumino widget messages
312
* @param msg - Lumino message to process
313
*/
314
processLuminoMessage(msg: Message): void;
315
316
// Properties
317
el: HTMLElement;
318
luminoWidget: Widget;
319
layoutPromise: Promise<any>;
320
stylePromise: Promise<any>;
321
}
322
```
323
324
**Usage Examples:**
325
326
```typescript
327
// Update classes based on state
328
this.update_classes(['old-state'], ['new-state', 'active']);
329
330
// Use class mapping for different states
331
const stateClasses = {
332
'success': ['alert', 'alert-success'],
333
'warning': ['alert', 'alert-warning'],
334
'error': ['alert', 'alert-danger']
335
};
336
this.update_mapped_classes(stateClasses, 'status');
337
338
// Custom layout handling
339
this.displayed.then(() => {
340
this.setLayout(this.model.get('layout'));
341
this.setStyle(this.model.get('style'));
342
});
343
```
344
345
## Lumino Integration
346
347
### JupyterLuminoWidget
348
349
Wrapper class for integrating Jupyter widgets with the Lumino widget system.
350
351
```typescript { .api }
352
/**
353
* Lumino widget wrapper for Jupyter widgets
354
*/
355
class JupyterLuminoWidget extends Widget {
356
constructor(options: Widget.IOptions & JupyterLuminoWidget.IOptions);
357
358
/**
359
* Dispose the widget and associated view
360
*/
361
dispose(): void;
362
363
/**
364
* Process Lumino messages and forward to view
365
* @param msg - Lumino message
366
*/
367
processMessage(msg: Message): void;
368
}
369
370
namespace JupyterLuminoWidget {
371
export interface IOptions {
372
view: DOMWidgetView;
373
}
374
}
375
```
376
377
### JupyterLuminoPanelWidget
378
379
Panel wrapper for Jupyter widgets in Lumino layouts.
380
381
```typescript { .api }
382
/**
383
* Lumino panel wrapper for Jupyter widgets
384
*/
385
class JupyterLuminoPanelWidget extends Panel {
386
constructor(options: JupyterLuminoWidget.IOptions & Panel.IOptions);
387
dispose(): void;
388
processMessage(msg: Message): void;
389
}
390
```
391
392
## Model Serialization
393
394
Utilities for serializing and deserializing widget model references in complex data structures.
395
396
```typescript { .api }
397
/**
398
* Replace model IDs with model instances recursively
399
* @param value - Value containing model references
400
* @param manager - Widget manager for model resolution
401
* @returns Promise resolving to value with unpacked models
402
*/
403
function unpack_models(
404
value: any | Dict<unknown> | string | (Dict<unknown> | string)[],
405
manager?: IWidgetManager
406
): Promise<WidgetModel | Dict<WidgetModel> | WidgetModel[] | any>;
407
408
/**
409
* Replace model instances with model IDs recursively
410
* @param value - Value containing model instances
411
* @param widget - Widget context for serialization
412
* @returns Value with packed model references
413
*/
414
function pack_models(
415
value: WidgetModel | Dict<WidgetModel> | WidgetModel[] | any,
416
widget?: WidgetModel
417
): any | Dict<unknown> | string | (Dict<unknown> | string)[];
418
```
419
420
**Usage Examples:**
421
422
```typescript
423
// Unpack model references in received data
424
const processedData = await unpack_models(rawData, this.widget_manager);
425
426
// Pack models for transmission
427
const serializedData = pack_models(dataWithModels, this);
428
```