@ama-mfe/ng-utils 13.6.0-prerelease.1 → 13.6.0-prerelease.11
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +154 -0
- package/fesm2022/ama-mfe-ng-utils.mjs +429 -2
- package/fesm2022/ama-mfe-ng-utils.mjs.map +1 -1
- package/index.d.ts +300 -3
- package/index.d.ts.map +1 -1
- package/package.json +6 -6
package/README.md
CHANGED
|
@@ -295,3 +295,157 @@ The host information is stored in session storage so it won't be lost when navig
|
|
|
295
295
|
When using iframes to embed applications, the browser history might be shared by the main page and the embedded iframe. For example `<iframe src="https://example.com" sandbox="allow-same-origin">` will share the same history as the main page. This can lead to unexpected behavior when using browser 'back' and 'forward' buttons.
|
|
296
296
|
|
|
297
297
|
To avoid this, the `@ama-mfe/ng-utils` will forbid the application running in the iframe to alter the browser history. It will happen when connection is configured using `provideConection()` function. This will prevent the iframe to be able to use the `history.pushState` and `history.replaceState` methods.
|
|
298
|
+
|
|
299
|
+
### User Activity Tracking
|
|
300
|
+
|
|
301
|
+
The User Activity Tracking feature allows a host application (shell) to monitor user interactions across embedded micro-frontends. This is useful for implementing session timeout functionality, analytics, or any feature that needs to know when users are actively interacting with the application.
|
|
302
|
+
|
|
303
|
+
#### How it works
|
|
304
|
+
|
|
305
|
+
- **Producer**: The `ActivityProducerService` listens for DOM events (click, keydown, scroll, touchstart, focus) and:
|
|
306
|
+
- Exposes a `localActivity` signal for consumers within the same application (not throttled for local detection).
|
|
307
|
+
- Sends throttled activity messages via the communication protocol to connected peers.
|
|
308
|
+
- **Consumer**: The `ActivityConsumerService` receives activity messages from connected peers via the communication protocol and exposes them via the `latestReceivedActivity` signal.
|
|
309
|
+
|
|
310
|
+
Both services can be used in either the shell (host) or embedded applications depending on your use case. For example:
|
|
311
|
+
- A shell can produce activity signals to notify embedded modules of user interactions in the host.
|
|
312
|
+
- An embedded module can consume activity signals from the shell.
|
|
313
|
+
- An application can use the producer's `localActivity` signal to detect activity locally.
|
|
314
|
+
|
|
315
|
+
The service automatically throttles messages sent to peers to prevent flooding the communication channel. High-frequency events like `scroll` have additional throttling.
|
|
316
|
+
|
|
317
|
+
#### Producer Configuration
|
|
318
|
+
|
|
319
|
+
Start the `ActivityProducerService` to send activity signals to connected peers:
|
|
320
|
+
|
|
321
|
+
```typescript
|
|
322
|
+
import { inject, runInInjectionContext } from '@angular/core';
|
|
323
|
+
import { bootstrapApplication } from '@angular/platform-browser';
|
|
324
|
+
import { ConnectionService, ActivityProducerService } from '@ama-mfe/ng-utils';
|
|
325
|
+
|
|
326
|
+
bootstrapApplication(App, appConfig)
|
|
327
|
+
.then((m) => {
|
|
328
|
+
runInInjectionContext(m.injector, () => {
|
|
329
|
+
if (window.top !== window.self) {
|
|
330
|
+
inject(ConnectionService).connect('hostUniqueID');
|
|
331
|
+
// Start activity tracking with custom throttle
|
|
332
|
+
inject(ActivityProducerService).start({
|
|
333
|
+
throttleMs: 5000 // Send at most one message every 5 seconds
|
|
334
|
+
});
|
|
335
|
+
}
|
|
336
|
+
});
|
|
337
|
+
});
|
|
338
|
+
```
|
|
339
|
+
|
|
340
|
+
##### Configuration Options
|
|
341
|
+
|
|
342
|
+
| Option | Type | Default | Description |
|
|
343
|
+
|--------|------|---------|-------------|
|
|
344
|
+
| `throttleMs` | `number` | `1000` | Minimum interval between activity messages sent to the host |
|
|
345
|
+
| `trackNestedIframes` | `boolean` | `false` | Enable tracking of nested iframes within the application |
|
|
346
|
+
| `nestedIframePollIntervalMs` | `number` | `1000` | Polling interval for detecting iframe focus changes |
|
|
347
|
+
| `nestedIframeActivityEmitIntervalMs` | `number` | `30000` | Interval for sending activity signals while an iframe has focus |
|
|
348
|
+
| `highFrequencyThrottleMs` | `number` | `300` | Throttle time for high-frequency events (scroll) |
|
|
349
|
+
| `shouldBroadcast` | `(event: Event) => boolean` | - | Optional filter function to control which events are broadcast |
|
|
350
|
+
|
|
351
|
+
##### Filtering Events with shouldBroadcast
|
|
352
|
+
|
|
353
|
+
The `shouldBroadcast` option allows you to filter which events trigger activity messages. This is useful in the shell application to exclude events that occur on iframes, since user activity inside embedded modules is already tracked via the communication protocol.
|
|
354
|
+
|
|
355
|
+
```typescript
|
|
356
|
+
// In the shell application
|
|
357
|
+
inject(ActivityProducerService).start({
|
|
358
|
+
throttleMs: 1000,
|
|
359
|
+
shouldBroadcast: (event: Event) => {
|
|
360
|
+
// Exclude events on iframes - activity from embedded modules comes via the communication protocol
|
|
361
|
+
return !(event.target instanceof HTMLIFrameElement);
|
|
362
|
+
}
|
|
363
|
+
});
|
|
364
|
+
```
|
|
365
|
+
|
|
366
|
+
##### Tracking Nested Iframes
|
|
367
|
+
|
|
368
|
+
When a user interacts with content inside an iframe (e.g., a third-party widget, payment form, or embedded content), the parent application cannot detect those interactions directly. This is because:
|
|
369
|
+
|
|
370
|
+
1. **Cross-origin restrictions**: DOM events inside cross-origin iframes do not bubble up to the parent document.
|
|
371
|
+
2. **Focus isolation**: When an iframe has focus, the parent document stops receiving keyboard and mouse events.
|
|
372
|
+
|
|
373
|
+
This creates a problem for detection of user interactions: a user could be actively filling out a form inside an iframe, but the host application would see no activity and might incorrectly trigger a session timeout.
|
|
374
|
+
|
|
375
|
+
**Solution**: When `trackNestedIframes` is enabled, the `ActivityProducerService` polls `document.activeElement` to detect when an iframe gains focus. While an iframe has focus, the service simulates activity by periodically emitting `iframeinteraction` events. This ensures the host application knows the user is still active, even though it cannot see the actual interactions inside the iframe.
|
|
376
|
+
|
|
377
|
+
Enable nested iframe tracking in embedded applications that contain other iframes:
|
|
378
|
+
|
|
379
|
+
```typescript
|
|
380
|
+
inject(ActivityProducerService).start({
|
|
381
|
+
throttleMs: 5000,
|
|
382
|
+
trackNestedIframes: true,
|
|
383
|
+
nestedIframePollIntervalMs: 1000, // Check for iframe focus every second
|
|
384
|
+
nestedIframeActivityEmitIntervalMs: 30000 // Send activity every 30s while iframe has focus
|
|
385
|
+
});
|
|
386
|
+
```
|
|
387
|
+
|
|
388
|
+
**When to use**: Enable this option in embedded modules that contain iframes whose content you cannot modify to include activity tracking (e.g., third-party widgets, payment providers, or external content).
|
|
389
|
+
|
|
390
|
+
#### Consumer Configuration
|
|
391
|
+
|
|
392
|
+
Start the `ActivityConsumerService` to receive activity signals from connected peers:
|
|
393
|
+
|
|
394
|
+
```typescript
|
|
395
|
+
import { Component, inject, effect } from '@angular/core';
|
|
396
|
+
import { ActivityConsumerService } from '@ama-mfe/ng-utils';
|
|
397
|
+
|
|
398
|
+
@Component({
|
|
399
|
+
selector: 'app-shell',
|
|
400
|
+
template: '...'
|
|
401
|
+
})
|
|
402
|
+
export class ShellComponent {
|
|
403
|
+
private readonly activityConsumer = inject(ActivityConsumerService);
|
|
404
|
+
|
|
405
|
+
constructor() {
|
|
406
|
+
// Start listening for activity messages
|
|
407
|
+
this.activityConsumer.start();
|
|
408
|
+
|
|
409
|
+
// React to activity changes
|
|
410
|
+
effect(() => {
|
|
411
|
+
const activity = this.activityConsumer.latestReceivedActivity();
|
|
412
|
+
if (activity) {
|
|
413
|
+
console.log(`Activity from ${activity.channelId}: ${activity.eventType} at ${activity.timestamp}`);
|
|
414
|
+
// Reset session timeout, update analytics, etc.
|
|
415
|
+
}
|
|
416
|
+
});
|
|
417
|
+
}
|
|
418
|
+
|
|
419
|
+
ngOnDestroy() {
|
|
420
|
+
this.activityConsumer.stop();
|
|
421
|
+
}
|
|
422
|
+
}
|
|
423
|
+
```
|
|
424
|
+
|
|
425
|
+
#### Local Activity Signal
|
|
426
|
+
|
|
427
|
+
The `ActivityProducerService` also exposes a `localActivity` signal for detecting activity within the same application:
|
|
428
|
+
|
|
429
|
+
```typescript
|
|
430
|
+
import { Component, inject, effect } from '@angular/core';
|
|
431
|
+
import { ActivityProducerService } from '@ama-mfe/ng-utils';
|
|
432
|
+
|
|
433
|
+
@Component({
|
|
434
|
+
selector: 'app-root',
|
|
435
|
+
template: '...'
|
|
436
|
+
})
|
|
437
|
+
export class AppComponent {
|
|
438
|
+
private readonly activityProducer = inject(ActivityProducerService);
|
|
439
|
+
|
|
440
|
+
constructor() {
|
|
441
|
+
this.activityProducer.start({ throttleMs: 1000 });
|
|
442
|
+
|
|
443
|
+
effect(() => {
|
|
444
|
+
const activity = this.activityProducer.localActivity();
|
|
445
|
+
if (activity) {
|
|
446
|
+
// React to local activity (not throttled for local detection)
|
|
447
|
+
}
|
|
448
|
+
});
|
|
449
|
+
}
|
|
450
|
+
}
|
|
451
|
+
```
|
|
@@ -4,7 +4,7 @@ import * as i0 from '@angular/core';
|
|
|
4
4
|
import { input, inject, ElementRef, computed, SecurityContext, effect, HostBinding, Directive, Injectable, signal, DestroyRef, provideAppInitializer, Pipe, makeEnvironmentProviders, untracked, afterNextRender, Renderer2 } from '@angular/core';
|
|
5
5
|
import { DomSanitizer } from '@angular/platform-browser';
|
|
6
6
|
import { LoggerService } from '@o3r/logger';
|
|
7
|
-
import { HISTORY_MESSAGE_TYPE, NAVIGATION_MESSAGE_TYPE, RESIZE_MESSAGE_TYPE, THEME_MESSAGE_TYPE } from '@ama-mfe/messages';
|
|
7
|
+
import { HISTORY_MESSAGE_TYPE, USER_ACTIVITY_MESSAGE_TYPE, NAVIGATION_MESSAGE_TYPE, RESIZE_MESSAGE_TYPE, THEME_MESSAGE_TYPE } from '@ama-mfe/messages';
|
|
8
8
|
import { takeUntilDestroyed, toSignal } from '@angular/core/rxjs-interop';
|
|
9
9
|
import { Router, ActivatedRoute, NavigationEnd } from '@angular/router';
|
|
10
10
|
import { Subject, filter, map } from 'rxjs';
|
|
@@ -444,6 +444,17 @@ i0.ɵɵngDeclareClassMetadata({ minVersion: "12.0.0", version: "20.3.15", ngImpo
|
|
|
444
444
|
/** the error message type */
|
|
445
445
|
const ERROR_MESSAGE_TYPE = 'error';
|
|
446
446
|
|
|
447
|
+
/**
|
|
448
|
+
* Type guard to check if a message is a user activity message
|
|
449
|
+
* @param message The message to check
|
|
450
|
+
*/
|
|
451
|
+
function isUserActivityMessage(message) {
|
|
452
|
+
return (typeof message === 'object'
|
|
453
|
+
&& message !== null
|
|
454
|
+
&& 'type' in message
|
|
455
|
+
&& message.type === USER_ACTIVITY_MESSAGE_TYPE);
|
|
456
|
+
}
|
|
457
|
+
|
|
447
458
|
/**
|
|
448
459
|
* A constant array of known message types and their versions.
|
|
449
460
|
*/
|
|
@@ -1237,9 +1248,425 @@ i0.ɵɵngDeclareClassMetadata({ minVersion: "12.0.0", version: "20.3.15", ngImpo
|
|
|
1237
1248
|
}]
|
|
1238
1249
|
}], ctorParameters: () => [] });
|
|
1239
1250
|
|
|
1251
|
+
/**
|
|
1252
|
+
* DOM events that indicate user activity
|
|
1253
|
+
*/
|
|
1254
|
+
const ACTIVITY_EVENTS = [
|
|
1255
|
+
'click',
|
|
1256
|
+
'keydown',
|
|
1257
|
+
'scroll',
|
|
1258
|
+
'touchstart',
|
|
1259
|
+
'focus'
|
|
1260
|
+
];
|
|
1261
|
+
/**
|
|
1262
|
+
* Custom activity event type for iframe interactions.
|
|
1263
|
+
* Emitted programmatically when an iframe gains focus, not from a DOM event listener.
|
|
1264
|
+
*/
|
|
1265
|
+
const IFRAME_INTERACTION_EVENT = 'iframeinteraction';
|
|
1266
|
+
/**
|
|
1267
|
+
* Custom activity event type for visibility changes.
|
|
1268
|
+
* Emitted programmatically when the document becomes visible, not from a DOM event listener.
|
|
1269
|
+
*/
|
|
1270
|
+
const VISIBILITY_CHANGE_EVENT = 'visibilitychange';
|
|
1271
|
+
/**
|
|
1272
|
+
* High-frequency events that require throttling to avoid performance issues
|
|
1273
|
+
*/
|
|
1274
|
+
const HIGH_FREQUENCY_EVENTS = [
|
|
1275
|
+
'scroll'
|
|
1276
|
+
];
|
|
1277
|
+
/**
|
|
1278
|
+
* Default configuration values for the ActivityProducerService
|
|
1279
|
+
*/
|
|
1280
|
+
const DEFAULT_ACTIVITY_PRODUCER_CONFIG = {
|
|
1281
|
+
/** Default throttle time in milliseconds between activity messages */
|
|
1282
|
+
throttleMs: 1000,
|
|
1283
|
+
/** Default throttle time in milliseconds for high-frequency events */
|
|
1284
|
+
highFrequencyThrottleMs: 300,
|
|
1285
|
+
/** Whether to track nested iframes by default */
|
|
1286
|
+
trackNestedIframes: false,
|
|
1287
|
+
/** Default interval for iframe activity signals (30 seconds) */
|
|
1288
|
+
nestedIframeActivityEmitIntervalMs: 30_000,
|
|
1289
|
+
/** Default polling interval for detecting iframe focus changes (1 second) */
|
|
1290
|
+
nestedIframePollIntervalMs: 1000
|
|
1291
|
+
};
|
|
1292
|
+
|
|
1293
|
+
/**
|
|
1294
|
+
* Service that tracks user activity within nested iframes.
|
|
1295
|
+
*
|
|
1296
|
+
* Polls document.activeElement frequently to detect when an iframe has focus.
|
|
1297
|
+
* When an iframe gains focus, emits immediately and then at the configured interval.
|
|
1298
|
+
* When focus leaves the iframe, it stops emitting.
|
|
1299
|
+
*
|
|
1300
|
+
* This is needed because cross-origin iframes don't fire focus/blur events
|
|
1301
|
+
* that bubble to the parent, and the regular activity tracker can't detect
|
|
1302
|
+
* user interactions inside iframes.
|
|
1303
|
+
*/
|
|
1304
|
+
class IframeActivityTrackerService {
|
|
1305
|
+
constructor() {
|
|
1306
|
+
/**
|
|
1307
|
+
* Bound visibility change handler for cleanup
|
|
1308
|
+
*/
|
|
1309
|
+
this.visibilityChangeHandler = () => this.handleVisibilityChange();
|
|
1310
|
+
}
|
|
1311
|
+
/**
|
|
1312
|
+
* Whether the service has been started
|
|
1313
|
+
*/
|
|
1314
|
+
get started() {
|
|
1315
|
+
return this.config !== undefined;
|
|
1316
|
+
}
|
|
1317
|
+
/**
|
|
1318
|
+
* Whether we are currently tracking iframe activity (iframe had focus on last poll)
|
|
1319
|
+
*/
|
|
1320
|
+
get isTrackingIframeActivity() {
|
|
1321
|
+
return this.activityIntervalId !== undefined;
|
|
1322
|
+
}
|
|
1323
|
+
/**
|
|
1324
|
+
* Polls document.activeElement to detect iframe focus changes.
|
|
1325
|
+
* When iframe gains focus: emit immediately and start activity interval.
|
|
1326
|
+
* When iframe loses focus: stop activity interval.
|
|
1327
|
+
*/
|
|
1328
|
+
checkActiveElement() {
|
|
1329
|
+
const activeElement = document.activeElement;
|
|
1330
|
+
const iframeFocused = activeElement instanceof HTMLIFrameElement;
|
|
1331
|
+
if (iframeFocused && !this.isTrackingIframeActivity) {
|
|
1332
|
+
// Iframe just gained focus - emit immediately and start activity interval
|
|
1333
|
+
this.config?.onActivity();
|
|
1334
|
+
this.startActivityInterval();
|
|
1335
|
+
}
|
|
1336
|
+
else if (!iframeFocused && this.isTrackingIframeActivity) {
|
|
1337
|
+
// Focus left the iframe - stop activity interval
|
|
1338
|
+
this.stopActivityInterval();
|
|
1339
|
+
}
|
|
1340
|
+
}
|
|
1341
|
+
/**
|
|
1342
|
+
* Handles visibility change events to pause/resume polling when tab visibility changes.
|
|
1343
|
+
*/
|
|
1344
|
+
handleVisibilityChange() {
|
|
1345
|
+
if (document.visibilityState === 'visible') {
|
|
1346
|
+
this.startPolling();
|
|
1347
|
+
}
|
|
1348
|
+
else {
|
|
1349
|
+
this.stopPolling();
|
|
1350
|
+
this.stopActivityInterval();
|
|
1351
|
+
}
|
|
1352
|
+
}
|
|
1353
|
+
/**
|
|
1354
|
+
* Starts polling for active element changes.
|
|
1355
|
+
*/
|
|
1356
|
+
startPolling() {
|
|
1357
|
+
if (this.pollIntervalId) {
|
|
1358
|
+
return;
|
|
1359
|
+
}
|
|
1360
|
+
this.pollIntervalId = setInterval(() => this.checkActiveElement(), this.config.pollIntervalMs);
|
|
1361
|
+
}
|
|
1362
|
+
/**
|
|
1363
|
+
* Stops polling for active element changes.
|
|
1364
|
+
*/
|
|
1365
|
+
stopPolling() {
|
|
1366
|
+
if (this.pollIntervalId) {
|
|
1367
|
+
clearInterval(this.pollIntervalId);
|
|
1368
|
+
this.pollIntervalId = undefined;
|
|
1369
|
+
}
|
|
1370
|
+
}
|
|
1371
|
+
/**
|
|
1372
|
+
* Starts the activity emission interval.
|
|
1373
|
+
*/
|
|
1374
|
+
startActivityInterval() {
|
|
1375
|
+
this.stopActivityInterval();
|
|
1376
|
+
this.activityIntervalId = setInterval(() => {
|
|
1377
|
+
this.config?.onActivity();
|
|
1378
|
+
}, this.config.activityIntervalMs);
|
|
1379
|
+
}
|
|
1380
|
+
/**
|
|
1381
|
+
* Stops the activity emission interval.
|
|
1382
|
+
*/
|
|
1383
|
+
stopActivityInterval() {
|
|
1384
|
+
if (this.activityIntervalId) {
|
|
1385
|
+
clearInterval(this.activityIntervalId);
|
|
1386
|
+
this.activityIntervalId = undefined;
|
|
1387
|
+
}
|
|
1388
|
+
}
|
|
1389
|
+
/**
|
|
1390
|
+
* Starts tracking nested iframes within the document.
|
|
1391
|
+
* @param config Configuration for the tracker
|
|
1392
|
+
*/
|
|
1393
|
+
start(config) {
|
|
1394
|
+
if (this.started) {
|
|
1395
|
+
return;
|
|
1396
|
+
}
|
|
1397
|
+
this.config = config;
|
|
1398
|
+
// Listen for visibility changes to pause/resume polling
|
|
1399
|
+
document.addEventListener('visibilitychange', this.visibilityChangeHandler);
|
|
1400
|
+
// Only start polling if document is currently visible
|
|
1401
|
+
if (document.visibilityState === 'visible') {
|
|
1402
|
+
this.startPolling();
|
|
1403
|
+
}
|
|
1404
|
+
}
|
|
1405
|
+
/**
|
|
1406
|
+
* Stops tracking nested iframes and cleans up resources.
|
|
1407
|
+
*/
|
|
1408
|
+
stop() {
|
|
1409
|
+
if (!this.started) {
|
|
1410
|
+
return;
|
|
1411
|
+
}
|
|
1412
|
+
document.removeEventListener('visibilitychange', this.visibilityChangeHandler);
|
|
1413
|
+
this.stopPolling();
|
|
1414
|
+
this.stopActivityInterval();
|
|
1415
|
+
this.config = undefined;
|
|
1416
|
+
}
|
|
1417
|
+
/** @nocollapse */ static { this.ɵfac = i0.ɵɵngDeclareFactory({ minVersion: "12.0.0", version: "20.3.15", ngImport: i0, type: IframeActivityTrackerService, deps: [], target: i0.ɵɵFactoryTarget.Injectable }); }
|
|
1418
|
+
/** @nocollapse */ static { this.ɵprov = i0.ɵɵngDeclareInjectable({ minVersion: "12.0.0", version: "20.3.15", ngImport: i0, type: IframeActivityTrackerService, providedIn: 'root' }); }
|
|
1419
|
+
}
|
|
1420
|
+
i0.ɵɵngDeclareClassMetadata({ minVersion: "12.0.0", version: "20.3.15", ngImport: i0, type: IframeActivityTrackerService, decorators: [{
|
|
1421
|
+
type: Injectable,
|
|
1422
|
+
args: [{
|
|
1423
|
+
providedIn: 'root'
|
|
1424
|
+
}]
|
|
1425
|
+
}] });
|
|
1426
|
+
|
|
1427
|
+
/**
|
|
1428
|
+
* Generic service that tracks user activity and sends messages.
|
|
1429
|
+
* Can be configured for different contexts (cockpit or modules) via start() method parameter.
|
|
1430
|
+
*/
|
|
1431
|
+
class ActivityProducerService {
|
|
1432
|
+
constructor() {
|
|
1433
|
+
this.messageService = inject(MessagePeerService);
|
|
1434
|
+
this.destroyRef = inject(DestroyRef);
|
|
1435
|
+
this.iframeActivityTracker = inject(IframeActivityTrackerService);
|
|
1436
|
+
this.logger = inject(LoggerService);
|
|
1437
|
+
/**
|
|
1438
|
+
* Timestamp of the last sent activity message
|
|
1439
|
+
*/
|
|
1440
|
+
this.lastSentTimestamp = 0;
|
|
1441
|
+
/**
|
|
1442
|
+
* Bound event listeners for cleanup
|
|
1443
|
+
*/
|
|
1444
|
+
this.boundListeners = new Map();
|
|
1445
|
+
/**
|
|
1446
|
+
* Last emission timestamps for throttled high-frequency events
|
|
1447
|
+
*/
|
|
1448
|
+
this.lastEmitTimestamps = new Map();
|
|
1449
|
+
/**
|
|
1450
|
+
* Whether the service has been started
|
|
1451
|
+
*/
|
|
1452
|
+
this.started = false;
|
|
1453
|
+
/**
|
|
1454
|
+
* Signal that emits local activity information.
|
|
1455
|
+
* This allows consumers to react to activity detected by this producer.
|
|
1456
|
+
*/
|
|
1457
|
+
this.localActivityWritable = signal(undefined, ...(ngDevMode ? [{ debugName: "localActivityWritable" }] : []));
|
|
1458
|
+
/**
|
|
1459
|
+
* Read-only signal containing the latest local activity info.
|
|
1460
|
+
* Use this signal to react to locally detected activity.
|
|
1461
|
+
*/
|
|
1462
|
+
this.localActivity = this.localActivityWritable.asReadonly();
|
|
1463
|
+
/**
|
|
1464
|
+
* @inheritdoc
|
|
1465
|
+
*/
|
|
1466
|
+
this.types = USER_ACTIVITY_MESSAGE_TYPE;
|
|
1467
|
+
registerProducer(this);
|
|
1468
|
+
this.destroyRef.onDestroy(() => this.stop());
|
|
1469
|
+
}
|
|
1470
|
+
/**
|
|
1471
|
+
* Handles high-frequency events by applying a per-eventType throttle before calling onActivity.
|
|
1472
|
+
*
|
|
1473
|
+
* Difference with onActivity:
|
|
1474
|
+
* - onActivityThrottled limits how often a given high-frequency event type (e.g. scroll) is processed
|
|
1475
|
+
* (based on highFrequencyThrottleMs and lastEmitTimestamps)
|
|
1476
|
+
* - onActivity updates the local activity signal and applies the global message throttle
|
|
1477
|
+
* (based on global throttleMs and lastSentTimestamp)
|
|
1478
|
+
* @param eventType The type of activity event that occurred
|
|
1479
|
+
* @param configObject
|
|
1480
|
+
*/
|
|
1481
|
+
onActivityThrottled(eventType, configObject) {
|
|
1482
|
+
const now = Date.now();
|
|
1483
|
+
const lastEmit = this.lastEmitTimestamps.get(eventType) ?? 0;
|
|
1484
|
+
const throttleMs = configObject.highFrequencyThrottleMs;
|
|
1485
|
+
if (now - lastEmit >= throttleMs) {
|
|
1486
|
+
this.lastEmitTimestamps.set(eventType, now);
|
|
1487
|
+
this.onActivity(eventType, configObject);
|
|
1488
|
+
}
|
|
1489
|
+
}
|
|
1490
|
+
/**
|
|
1491
|
+
* Handles activity by sending a throttled message and emitting to local signal.
|
|
1492
|
+
* @param eventType The type of activity event that occurred
|
|
1493
|
+
* @param configObject
|
|
1494
|
+
*/
|
|
1495
|
+
onActivity(eventType, configObject) {
|
|
1496
|
+
const now = Date.now();
|
|
1497
|
+
// Always emit local activity signal (not throttled for local detection)
|
|
1498
|
+
this.localActivityWritable.set({
|
|
1499
|
+
channelId: 'local',
|
|
1500
|
+
eventType,
|
|
1501
|
+
timestamp: now
|
|
1502
|
+
});
|
|
1503
|
+
// Send message with throttling
|
|
1504
|
+
if (now - this.lastSentTimestamp >= configObject.throttleMs) {
|
|
1505
|
+
this.lastSentTimestamp = now;
|
|
1506
|
+
this.sendActivityMessage(eventType, now);
|
|
1507
|
+
}
|
|
1508
|
+
}
|
|
1509
|
+
/**
|
|
1510
|
+
* Sends an activity message.
|
|
1511
|
+
* @param eventType The type of activity event
|
|
1512
|
+
* @param timestamp The timestamp of the event
|
|
1513
|
+
*/
|
|
1514
|
+
sendActivityMessage(eventType, timestamp) {
|
|
1515
|
+
const message = {
|
|
1516
|
+
type: USER_ACTIVITY_MESSAGE_TYPE,
|
|
1517
|
+
version: '1.0',
|
|
1518
|
+
eventType,
|
|
1519
|
+
timestamp
|
|
1520
|
+
};
|
|
1521
|
+
const registeredPeersIdsForUserActivity = [...this.messageService.knownPeers.entries()]
|
|
1522
|
+
.filter(([peerId]) => peerId !== this.messageService.id)
|
|
1523
|
+
.filter(([, messages]) => messages.some((msg) => msg.type === USER_ACTIVITY_MESSAGE_TYPE))
|
|
1524
|
+
.map((peer) => peer[0]);
|
|
1525
|
+
// send messages to the peers waiting for user activity
|
|
1526
|
+
// avoids sending the message to modules which are not using it
|
|
1527
|
+
if (registeredPeersIdsForUserActivity.length > 0) {
|
|
1528
|
+
this.messageService.send(message, { to: registeredPeersIdsForUserActivity });
|
|
1529
|
+
}
|
|
1530
|
+
}
|
|
1531
|
+
/**
|
|
1532
|
+
* @inheritdoc
|
|
1533
|
+
*/
|
|
1534
|
+
handleError(message) {
|
|
1535
|
+
this.logger.error('Error in user activity service message', message);
|
|
1536
|
+
}
|
|
1537
|
+
/**
|
|
1538
|
+
* Starts observing user activity events.
|
|
1539
|
+
* When activity is detected, it sends a throttled message.
|
|
1540
|
+
* Event listeners are attached after the next render to ensure DOM is ready.
|
|
1541
|
+
* @param config Configuration for the activity producer
|
|
1542
|
+
*/
|
|
1543
|
+
start(config) {
|
|
1544
|
+
if (this.started) {
|
|
1545
|
+
return;
|
|
1546
|
+
}
|
|
1547
|
+
this.started = true;
|
|
1548
|
+
const configObject = { ...DEFAULT_ACTIVITY_PRODUCER_CONFIG, ...config };
|
|
1549
|
+
// Always use afterNextRender to ensure DOM is ready in all contexts
|
|
1550
|
+
afterNextRender(() => {
|
|
1551
|
+
ACTIVITY_EVENTS.forEach((eventType) => {
|
|
1552
|
+
const isHighFrequency = HIGH_FREQUENCY_EVENTS.includes(eventType);
|
|
1553
|
+
const listener = (event) => {
|
|
1554
|
+
// do nothing if the event is a key kept pressed
|
|
1555
|
+
if (eventType === 'keydown' && event instanceof KeyboardEvent && event.repeat) {
|
|
1556
|
+
return;
|
|
1557
|
+
}
|
|
1558
|
+
// Apply filter if provided
|
|
1559
|
+
if (configObject.shouldBroadcast?.(event) === false) {
|
|
1560
|
+
return;
|
|
1561
|
+
}
|
|
1562
|
+
if (isHighFrequency) {
|
|
1563
|
+
this.onActivityThrottled(eventType, configObject);
|
|
1564
|
+
}
|
|
1565
|
+
else {
|
|
1566
|
+
this.onActivity(eventType, configObject);
|
|
1567
|
+
}
|
|
1568
|
+
};
|
|
1569
|
+
this.boundListeners.set(eventType, listener);
|
|
1570
|
+
document.addEventListener(eventType, listener, { passive: true, capture: true });
|
|
1571
|
+
});
|
|
1572
|
+
// Also listen for visibility changes
|
|
1573
|
+
const visibilityListener = () => {
|
|
1574
|
+
if (document.visibilityState === 'visible') {
|
|
1575
|
+
this.onActivity(VISIBILITY_CHANGE_EVENT, configObject);
|
|
1576
|
+
}
|
|
1577
|
+
};
|
|
1578
|
+
this.boundListeners.set(VISIBILITY_CHANGE_EVENT, visibilityListener);
|
|
1579
|
+
document.addEventListener(VISIBILITY_CHANGE_EVENT, visibilityListener, { passive: true, capture: true });
|
|
1580
|
+
// Set up nested iframe tracking if enabled
|
|
1581
|
+
if (configObject.trackNestedIframes) {
|
|
1582
|
+
this.iframeActivityTracker.start({
|
|
1583
|
+
pollIntervalMs: configObject.nestedIframePollIntervalMs,
|
|
1584
|
+
activityIntervalMs: configObject.nestedIframeActivityEmitIntervalMs,
|
|
1585
|
+
onActivity: () => this.onActivity(IFRAME_INTERACTION_EVENT, configObject)
|
|
1586
|
+
});
|
|
1587
|
+
}
|
|
1588
|
+
});
|
|
1589
|
+
}
|
|
1590
|
+
/**
|
|
1591
|
+
* Stops observing user activity events.
|
|
1592
|
+
*/
|
|
1593
|
+
stop() {
|
|
1594
|
+
this.boundListeners.forEach((listener, eventType) => {
|
|
1595
|
+
document.removeEventListener(eventType, listener, { capture: true });
|
|
1596
|
+
});
|
|
1597
|
+
this.boundListeners.clear();
|
|
1598
|
+
this.lastEmitTimestamps.clear();
|
|
1599
|
+
this.iframeActivityTracker.stop();
|
|
1600
|
+
}
|
|
1601
|
+
/** @nocollapse */ static { this.ɵfac = i0.ɵɵngDeclareFactory({ minVersion: "12.0.0", version: "20.3.15", ngImport: i0, type: ActivityProducerService, deps: [], target: i0.ɵɵFactoryTarget.Injectable }); }
|
|
1602
|
+
/** @nocollapse */ static { this.ɵprov = i0.ɵɵngDeclareInjectable({ minVersion: "12.0.0", version: "20.3.15", ngImport: i0, type: ActivityProducerService, providedIn: 'root' }); }
|
|
1603
|
+
}
|
|
1604
|
+
i0.ɵɵngDeclareClassMetadata({ minVersion: "12.0.0", version: "20.3.15", ngImport: i0, type: ActivityProducerService, decorators: [{
|
|
1605
|
+
type: Injectable,
|
|
1606
|
+
args: [{
|
|
1607
|
+
providedIn: 'root'
|
|
1608
|
+
}]
|
|
1609
|
+
}], ctorParameters: () => [] });
|
|
1610
|
+
|
|
1611
|
+
/**
|
|
1612
|
+
* Generic service that consumes user activity messages.
|
|
1613
|
+
* Can be used in both shell (to receive from modules) and modules (to receive from shell).
|
|
1614
|
+
*/
|
|
1615
|
+
class ActivityConsumerService {
|
|
1616
|
+
constructor() {
|
|
1617
|
+
this.consumerManagerService = inject(ConsumerManagerService);
|
|
1618
|
+
/**
|
|
1619
|
+
* Signal containing the latest activity info
|
|
1620
|
+
*/
|
|
1621
|
+
this.latestReceivedActivityWritable = signal(undefined, ...(ngDevMode ? [{ debugName: "latestReceivedActivityWritable" }] : []));
|
|
1622
|
+
/**
|
|
1623
|
+
* Read-only signal containing the latest activity info received from other peers via the message protocol.
|
|
1624
|
+
* Access the timestamp via latestReceivedActivity()?.timestamp
|
|
1625
|
+
*/
|
|
1626
|
+
this.latestReceivedActivity = this.latestReceivedActivityWritable.asReadonly();
|
|
1627
|
+
/**
|
|
1628
|
+
* @inheritdoc
|
|
1629
|
+
*/
|
|
1630
|
+
this.type = USER_ACTIVITY_MESSAGE_TYPE;
|
|
1631
|
+
/**
|
|
1632
|
+
* @inheritdoc
|
|
1633
|
+
*/
|
|
1634
|
+
this.supportedVersions = {
|
|
1635
|
+
// eslint-disable-next-line @typescript-eslint/naming-convention -- Version keys follow message versioning convention
|
|
1636
|
+
'1.0': (message) => {
|
|
1637
|
+
this.latestReceivedActivityWritable.set({
|
|
1638
|
+
channelId: message.from || 'unknown',
|
|
1639
|
+
eventType: message.payload.eventType,
|
|
1640
|
+
timestamp: message.payload.timestamp
|
|
1641
|
+
});
|
|
1642
|
+
}
|
|
1643
|
+
};
|
|
1644
|
+
}
|
|
1645
|
+
/**
|
|
1646
|
+
* Starts the activity consumer service by registering it with the consumer manager.
|
|
1647
|
+
*/
|
|
1648
|
+
start() {
|
|
1649
|
+
this.consumerManagerService.register(this);
|
|
1650
|
+
}
|
|
1651
|
+
/**
|
|
1652
|
+
* Stops the activity consumer service by unregistering it from the consumer manager.
|
|
1653
|
+
*/
|
|
1654
|
+
stop() {
|
|
1655
|
+
this.consumerManagerService.unregister(this);
|
|
1656
|
+
}
|
|
1657
|
+
/** @nocollapse */ static { this.ɵfac = i0.ɵɵngDeclareFactory({ minVersion: "12.0.0", version: "20.3.15", ngImport: i0, type: ActivityConsumerService, deps: [], target: i0.ɵɵFactoryTarget.Injectable }); }
|
|
1658
|
+
/** @nocollapse */ static { this.ɵprov = i0.ɵɵngDeclareInjectable({ minVersion: "12.0.0", version: "20.3.15", ngImport: i0, type: ActivityConsumerService, providedIn: 'root' }); }
|
|
1659
|
+
}
|
|
1660
|
+
i0.ɵɵngDeclareClassMetadata({ minVersion: "12.0.0", version: "20.3.15", ngImport: i0, type: ActivityConsumerService, decorators: [{
|
|
1661
|
+
type: Injectable,
|
|
1662
|
+
args: [{
|
|
1663
|
+
providedIn: 'root'
|
|
1664
|
+
}]
|
|
1665
|
+
}] });
|
|
1666
|
+
|
|
1240
1667
|
/**
|
|
1241
1668
|
* Generated bundle index. Do not edit.
|
|
1242
1669
|
*/
|
|
1243
1670
|
|
|
1244
|
-
export { ApplyTheme, ConnectDirective, ConsumerManagerService, ERROR_MESSAGE_TYPE, HistoryConsumerService, HostInfoPipe, KNOWN_MESSAGES, MFE_HOST_APPLICATION_ID_PARAM, MFE_HOST_URL_PARAM, MFE_MODULE_APPLICATION_ID_PARAM, NavigationConsumerService, ProducerManagerService, ResizeConsumerService, ResizeService, RestoreRoute, RouteMemorizeDirective, RouteMemorizeService, RoutingService, ScalableDirective, THEME_QUERY_PARAM_NAME, THEME_URL_SUFFIX, ThemeConsumerService, ThemeProducerService, applyInitialTheme, applyTheme, downloadApplicationThemeCss, getAvailableConsumers, getDefaultClientEndpointStartOptions, getHostInfo, getStyle, hostQueryParams, isEmbedded, isErrorMessage, persistHostInfo, provideConnection, provideHistoryOverrides, registerConsumer, registerProducer, sendError };
|
|
1671
|
+
export { ACTIVITY_EVENTS, ActivityConsumerService, ActivityProducerService, ApplyTheme, ConnectDirective, ConsumerManagerService, DEFAULT_ACTIVITY_PRODUCER_CONFIG, ERROR_MESSAGE_TYPE, HIGH_FREQUENCY_EVENTS, HistoryConsumerService, HostInfoPipe, IFRAME_INTERACTION_EVENT, IframeActivityTrackerService, KNOWN_MESSAGES, MFE_HOST_APPLICATION_ID_PARAM, MFE_HOST_URL_PARAM, MFE_MODULE_APPLICATION_ID_PARAM, NavigationConsumerService, ProducerManagerService, ResizeConsumerService, ResizeService, RestoreRoute, RouteMemorizeDirective, RouteMemorizeService, RoutingService, ScalableDirective, THEME_QUERY_PARAM_NAME, THEME_URL_SUFFIX, ThemeConsumerService, ThemeProducerService, VISIBILITY_CHANGE_EVENT, applyInitialTheme, applyTheme, downloadApplicationThemeCss, getAvailableConsumers, getDefaultClientEndpointStartOptions, getHostInfo, getStyle, hostQueryParams, isEmbedded, isErrorMessage, isUserActivityMessage, persistHostInfo, provideConnection, provideHistoryOverrides, registerConsumer, registerProducer, sendError };
|
|
1245
1672
|
//# sourceMappingURL=ama-mfe-ng-utils.mjs.map
|