0
# @lumino/messaging
1
2
@lumino/messaging provides a comprehensive message passing system for JavaScript/TypeScript applications, implementing a sophisticated message queue and dispatch mechanism. It defines core Message classes with support for message conflation to optimize performance by merging similar messages, message handlers for processing different message types, and a message loop system that ensures proper message ordering and delivery.
3
4
## Package Information
5
6
- **Package Name**: @lumino/messaging
7
- **Package Type**: npm
8
- **Language**: TypeScript
9
- **Installation**: `npm install @lumino/messaging`
10
11
## Core Imports
12
13
```typescript
14
import {
15
Message,
16
ConflatableMessage,
17
IMessageHandler,
18
IMessageHook,
19
MessageHook,
20
MessageLoop
21
} from "@lumino/messaging";
22
```
23
24
For CommonJS:
25
26
```javascript
27
const {
28
Message,
29
ConflatableMessage,
30
IMessageHandler,
31
IMessageHook,
32
MessageHook,
33
MessageLoop
34
} = require("@lumino/messaging");
35
```
36
37
## Basic Usage
38
39
```typescript
40
import { Message, MessageLoop, IMessageHandler } from "@lumino/messaging";
41
42
// Create a message handler
43
class MyHandler implements IMessageHandler {
44
processMessage(msg: Message): void {
45
console.log(`Processing message: ${msg.type}`);
46
}
47
}
48
49
// Send messages immediately
50
const handler = new MyHandler();
51
const message = new Message("update");
52
53
// Send message immediately
54
MessageLoop.sendMessage(handler, message);
55
56
// Post message for future processing
57
MessageLoop.postMessage(handler, message);
58
```
59
60
## Architecture
61
62
@lumino/messaging is built around several key components:
63
64
- **Message Classes**: Base `Message` class and specialized `ConflatableMessage` for automatic message merging
65
- **Handler Interface**: `IMessageHandler` defines objects that can process messages
66
- **Hook System**: `IMessageHook` enables message interception and filtering
67
- **Message Loop**: Central dispatcher managing message queuing, conflation, and delivery
68
- **Exception Handling**: Built-in error handling with customizable exception handlers
69
70
## Capabilities
71
72
### Message Creation
73
74
Core message classes for creating and managing messages in the system.
75
76
```typescript { .api }
77
/**
78
* Base message class for message passing system
79
*/
80
class Message {
81
constructor(type: string);
82
readonly type: string;
83
get isConflatable(): boolean;
84
conflate(other: Message): boolean;
85
}
86
87
/**
88
* Convenience message class that conflates automatically
89
*/
90
class ConflatableMessage extends Message {
91
constructor(type: string);
92
get isConflatable(): boolean;
93
conflate(other: ConflatableMessage): boolean;
94
}
95
```
96
97
**Usage Example:**
98
99
```typescript
100
import { Message, ConflatableMessage } from "@lumino/messaging";
101
102
// Create basic message
103
const basicMessage = new Message("resize");
104
105
// Create conflatable message for optimization
106
const conflatable = new ConflatableMessage("update-layout");
107
108
// Check if message can be conflated
109
console.log(basicMessage.isConflatable); // false
110
console.log(conflatable.isConflatable); // true
111
```
112
113
### Message Handling
114
115
Interface for objects that can process messages.
116
117
```typescript { .api }
118
/**
119
* Interface for objects that can process messages
120
*/
121
interface IMessageHandler {
122
processMessage(msg: Message): void;
123
}
124
```
125
126
**Usage Example:**
127
128
```typescript
129
import { IMessageHandler, Message } from "@lumino/messaging";
130
131
class WidgetHandler implements IMessageHandler {
132
private element: HTMLElement;
133
134
constructor(element: HTMLElement) {
135
this.element = element;
136
}
137
138
processMessage(msg: Message): void {
139
switch (msg.type) {
140
case "resize":
141
this.handleResize();
142
break;
143
case "update":
144
this.handleUpdate();
145
break;
146
}
147
}
148
149
private handleResize(): void {
150
// Handle resize logic
151
}
152
153
private handleUpdate(): void {
154
// Handle update logic
155
}
156
}
157
```
158
159
### Message Hooks
160
161
Interface and type for intercepting messages before they reach handlers.
162
163
```typescript { .api }
164
/**
165
* Interface for objects that can intercept messages
166
*/
167
interface IMessageHook {
168
messageHook(handler: IMessageHandler, msg: Message): boolean;
169
}
170
171
/**
172
* Type alias for message hook object or function
173
*/
174
type MessageHook = IMessageHook | ((handler: IMessageHandler, msg: Message) => boolean);
175
```
176
177
**Usage Example:**
178
179
```typescript
180
import { IMessageHook, MessageHook, IMessageHandler, Message } from "@lumino/messaging";
181
182
// Hook as object
183
class LoggingHook implements IMessageHook {
184
messageHook(handler: IMessageHandler, msg: Message): boolean {
185
console.log(`Intercepted message: ${msg.type}`);
186
return true; // Allow message to continue
187
}
188
}
189
190
// Hook as function
191
const filterHook: MessageHook = (handler, msg) => {
192
// Block messages of type "blocked"
193
return msg.type !== "blocked";
194
};
195
```
196
197
### Message Dispatching
198
199
Central message loop functionality for sending, posting, and managing messages.
200
201
```typescript { .api }
202
namespace MessageLoop {
203
/**
204
* Send a message to a handler immediately
205
*/
206
function sendMessage(handler: IMessageHandler, msg: Message): void;
207
208
/**
209
* Post a message to a handler for future processing with conflation
210
*/
211
function postMessage(handler: IMessageHandler, msg: Message): void;
212
213
/**
214
* Install a message hook for a handler
215
*/
216
function installMessageHook(handler: IMessageHandler, hook: MessageHook): void;
217
218
/**
219
* Remove an installed message hook
220
*/
221
function removeMessageHook(handler: IMessageHandler, hook: MessageHook): void;
222
223
/**
224
* Clear all message data for a handler
225
*/
226
function clearData(handler: IMessageHandler): void;
227
228
/**
229
* Process all pending posted messages immediately
230
*/
231
function flush(): void;
232
233
/**
234
* Get the current exception handler
235
*/
236
function getExceptionHandler(): ExceptionHandler;
237
238
/**
239
* Set the exception handler, returns the old one
240
*/
241
function setExceptionHandler(handler: ExceptionHandler): ExceptionHandler;
242
243
/**
244
* Type alias for exception handler function
245
*/
246
type ExceptionHandler = (err: Error) => void;
247
}
248
```
249
250
**Usage Examples:**
251
252
```typescript
253
import { MessageLoop, Message, IMessageHandler } from "@lumino/messaging";
254
255
class Handler implements IMessageHandler {
256
messages: string[] = [];
257
258
processMessage(msg: Message): void {
259
this.messages.push(msg.type);
260
}
261
}
262
263
const handler = new Handler();
264
265
// Send message immediately
266
MessageLoop.sendMessage(handler, new Message("immediate"));
267
268
// Post message for later (with conflation)
269
MessageLoop.postMessage(handler, new Message("deferred"));
270
271
// Install hook to intercept messages
272
MessageLoop.installMessageHook(handler, (h, msg) => {
273
console.log(`Hook intercepted: ${msg.type}`);
274
return true; // Allow message to continue
275
});
276
277
// Clear all data for handler
278
MessageLoop.clearData(handler);
279
280
// Process pending messages immediately
281
MessageLoop.flush();
282
283
// Custom exception handling
284
MessageLoop.setExceptionHandler((err) => {
285
console.error("Message processing error:", err);
286
});
287
```
288
289
### Message Conflation
290
291
Advanced feature for optimizing message processing by merging similar messages.
292
293
**Key Concepts:**
294
295
- **Conflatable Messages**: Messages with `isConflatable` returning `true`
296
- **Automatic Conflation**: Only applies to posted messages (not sent messages)
297
- **Performance Optimization**: Reduces duplicate message processing
298
- **Custom Conflation**: Override `conflate()` method for custom merge logic
299
300
**Usage Example:**
301
302
```typescript
303
import { ConflatableMessage, MessageLoop, IMessageHandler } from "@lumino/messaging";
304
305
// Custom conflatable message
306
class UpdateMessage extends ConflatableMessage {
307
constructor(public data: any) {
308
super("update");
309
}
310
311
conflate(other: UpdateMessage): boolean {
312
// Merge data from other message
313
this.data = { ...this.data, ...other.data };
314
return true; // Successfully conflated
315
}
316
}
317
318
const handler: IMessageHandler = {
319
processMessage(msg: Message): void {
320
if (msg instanceof UpdateMessage) {
321
console.log("Processing update with data:", msg.data);
322
}
323
}
324
};
325
326
// These will be conflated into a single message
327
MessageLoop.postMessage(handler, new UpdateMessage({ x: 1 }));
328
MessageLoop.postMessage(handler, new UpdateMessage({ y: 2 }));
329
MessageLoop.postMessage(handler, new UpdateMessage({ z: 3 }));
330
331
// Only one message will be processed with merged data: { x: 1, y: 2, z: 3 }
332
```
333
334
## Error Handling
335
336
The message system includes built-in exception handling:
337
338
- All exceptions in message handlers are caught and logged
339
- All exceptions in message hooks are caught and logged
340
- Default exception handler uses `console.error`
341
- Custom exception handlers can be installed via `MessageLoop.setExceptionHandler()`
342
- Hook exceptions return `true` by default to continue message processing
343
- Handler exceptions do not prevent other messages from being processed