@luigi-project/client 2.26.1-dev.202601280040 → 2.26.1-dev.202601281416

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.
@@ -0,0 +1,2126 @@
1
+ /**
2
+ * @private
3
+ * @abstract
4
+ */
5
+ class LuigiClientBase {
6
+ /**
7
+ * @private
8
+ */
9
+ constructor() {
10
+ this.promises = {};
11
+ }
12
+ /**
13
+ * Returns the promises object
14
+ * @private
15
+ */
16
+ setPromise(name, value) {
17
+ this.promises[name] = value;
18
+ }
19
+ /**
20
+ * Sets the promises object
21
+ * @private
22
+ */
23
+ getPromise(name) {
24
+ return this.promises[name];
25
+ }
26
+ }
27
+
28
+ /** @private */
29
+ class Helpers {
30
+ /** @private */
31
+ constructor() {
32
+ this.listeners = [];
33
+ this.origin = '';
34
+
35
+ const helperListener = function (evt) {
36
+ if (!evt.data.msg) {
37
+ return;
38
+ }
39
+ if (evt.data.msg === 'custom') {
40
+ const message = this.convertCustomMessageInternalToUser(evt.data);
41
+ this.listeners
42
+ .filter((listener) => listener.name === message.id)
43
+ .map((listener) => listener.eventFn(message, listener.listenerId));
44
+ } else {
45
+ this.listeners
46
+ .filter((listener) => listener.name === evt.data.msg)
47
+ .map((listener) => listener.eventFn(evt, listener.listenerId));
48
+ }
49
+ }.bind(this);
50
+
51
+ window.addEventListener('message', helperListener);
52
+ }
53
+
54
+ convertCustomMessageInternalToUser(internalMessage) {
55
+ return internalMessage.data;
56
+ }
57
+
58
+ convertCustomMessageUserToInternal(message) {
59
+ return {
60
+ msg: 'custom',
61
+ data: message
62
+ };
63
+ }
64
+
65
+ convertStorageMessageToInternal(message) {
66
+ return {
67
+ msg: 'storage',
68
+ data: message
69
+ };
70
+ }
71
+
72
+ /**
73
+ * Registers a post message listener
74
+ * Don't forget to remove the event listener at the end of
75
+ * your eventFn if you do not need it anymore.
76
+ * @private
77
+ * @param {string} name - event name
78
+ * @param {function} eventFn - callback function
79
+ * @returns {string} listener id
80
+ */
81
+ addEventListener(name, eventFn) {
82
+ const listenerId = this.getRandomId();
83
+ this.listeners.push({
84
+ name,
85
+ eventFn,
86
+ listenerId
87
+ });
88
+ return listenerId;
89
+ }
90
+
91
+ /**
92
+ * Removes a post message listener
93
+ * @private
94
+ * @param {string} id - listenerId
95
+ */
96
+ removeEventListener(id) {
97
+ const listenerExists = Boolean(this.listeners.find((l) => l.listenerId === id));
98
+ if (listenerExists) {
99
+ this.listeners = this.listeners.filter((l) => l.listenerId !== id);
100
+ return true;
101
+ }
102
+ return false;
103
+ }
104
+
105
+ /**
106
+ * Creates a random Id
107
+ * @private
108
+ */
109
+ getRandomId() {
110
+ return window.crypto.getRandomValues(new Uint32Array(1))[0];
111
+ }
112
+
113
+ /**
114
+ * Simple function check.
115
+ * @private
116
+ * @param {function} item
117
+ * @returns {boolean}
118
+ */
119
+ isFunction(item) {
120
+ return typeof item === 'function';
121
+ }
122
+
123
+ /**
124
+ * Simple object check.
125
+ * @private
126
+ * @param {Object} item
127
+ * @returns {boolean}
128
+ */
129
+ isObject(item) {
130
+ return Object.prototype.toString.call(item) === '[object Object]';
131
+ }
132
+
133
+ getLuigiCoreDomain() {
134
+ return this.origin;
135
+ }
136
+
137
+ setLuigiCoreDomain(origin) {
138
+ // protect against "null" string set by at least Chrome browser when file protocol used
139
+ if (origin && origin !== 'null') {
140
+ this.origin = origin;
141
+ }
142
+ }
143
+
144
+ setTargetOrigin(origin) {
145
+ this.setLuigiCoreDomain(origin);
146
+ }
147
+
148
+ sendPostMessageToLuigiCore(msg) {
149
+ if (this.origin) {
150
+ // protect against potential postMessage problems, since origin value may be set incorrectly
151
+ try {
152
+ window.parent.postMessage(msg, this.origin);
153
+ } catch (error) {
154
+ console.warn('Unable to post message ' + msg + ' to Luigi Core from origin ' + this.origin + ': ' + error);
155
+ }
156
+ } else {
157
+ console.warn(
158
+ 'There is no target origin set. You can specify the target origin by calling LuigiClient.setTargetOrigin("targetorigin") in your micro frontend.'
159
+ );
160
+ }
161
+ }
162
+
163
+ /**
164
+ * Checks if given path contains intent navigation special syntax
165
+ * @param {string} path - path to be checked
166
+ */
167
+ hasIntent(path) {
168
+ return !!path && path.toLowerCase().includes('#?intent=');
169
+ }
170
+
171
+ deSanitizeParamsMap(paramsMap) {
172
+ return Object.entries(paramsMap).reduce((sanitizedMap, paramPair) => {
173
+ sanitizedMap[this.deSanitizeParam(paramPair[0])] = this.deSanitizeParam(paramPair[1]);
174
+ return sanitizedMap;
175
+ }, {});
176
+ }
177
+
178
+ deSanitizeParam(param = '') {
179
+ return String(param)
180
+ .replaceAll('&lt;', '<')
181
+ .replaceAll('&gt;', '>')
182
+ .replaceAll('&quot;', '"')
183
+ .replaceAll('&#39;', "'")
184
+ .replaceAll('&sol;', '/');
185
+ }
186
+ }
187
+
188
+ const helpers = new Helpers();
189
+
190
+ var version = "2.26.0";
191
+
192
+ /**
193
+ * @summary Use the functions and parameters to define the Lifecycle of listeners, navigation nodes, and Event data.
194
+ * @augments LuigiClientBase
195
+ * @name Lifecycle
196
+ * @class
197
+ */
198
+ class LifecycleManager extends LuigiClientBase {
199
+ /** @private */
200
+ constructor() {
201
+ super();
202
+ this.luigiInitialized = false;
203
+ this.defaultContextKeys = ['context', 'internal', 'nodeParams', 'pathParams', 'searchParams'];
204
+ this.setCurrentContext(
205
+ this.defaultContextKeys.reduce(function (acc, key) {
206
+ acc[key] = {};
207
+ return acc;
208
+ }, {})
209
+ );
210
+
211
+ this._onContextUpdatedFns = {};
212
+ this._onInactiveFns = {};
213
+ this._onInitFns = {};
214
+ this.authData = {};
215
+
216
+ if (!this._isDeferInitDefined()) {
217
+ this.luigiClientInit();
218
+ }
219
+ }
220
+
221
+ /**
222
+ * Check if the html head element contains the attribute "defer-luigi-init"
223
+ * @private
224
+ * @memberof Lifecycle
225
+ */
226
+ _isDeferInitDefined() {
227
+ return window.document.head.hasAttribute('defer-luigi-init');
228
+ }
229
+
230
+ /**
231
+ * Check if the html head element contains the attribute "disable-tpc-check"
232
+ * @private
233
+ * @memberof Lifecycle
234
+ */
235
+ _isTpcCheckDisabled() {
236
+ return (
237
+ window.document.head.hasAttribute('disable-tpc-check') ||
238
+ this.currentContext?.internal?.thirdPartyCookieCheck?.disabled
239
+ );
240
+ }
241
+
242
+ /**
243
+ * Check if LuigiClient is initialized
244
+ * @returns {boolean} client initialized state
245
+ * @since 1.12.0
246
+ * @memberof Lifecycle
247
+ * @example
248
+ * const init = LuigiClient.isLuigiClientInitialized()
249
+ */
250
+ isLuigiClientInitialized() {
251
+ return this.luigiInitialized;
252
+ }
253
+
254
+ /**
255
+ * Starts the handshake with Luigi Core and thereafter results in initialization of Luigi Client. It is always ran by default when importing the Luigi Client package in your micro frontend. Note that when using `defer-luigi-init` to defer default initialization, you will need to initialize the handshake using this function manually wherever needed.
256
+ * @since 1.12.0
257
+ * @memberof Lifecycle
258
+ * @example
259
+ * LuigiClient.luigiClientInit()
260
+ */
261
+ luigiClientInit() {
262
+ if (this.luigiInitialized) {
263
+ console.warn('Luigi Client has been already initialized');
264
+ return;
265
+ }
266
+ /**
267
+ * Save context data every time navigation to a different node happens
268
+ * @private
269
+ */
270
+ const setContext = (rawData) => {
271
+ for (let index = 0; index < this.defaultContextKeys.length; index++) {
272
+ let key = this.defaultContextKeys[index];
273
+ try {
274
+ if (typeof rawData[key] === 'string') {
275
+ rawData[key] = JSON.parse(rawData[key]);
276
+ }
277
+ } catch (e) {
278
+ console.info('unable to parse luigi context data for', key, rawData[key], e);
279
+ }
280
+ }
281
+ this.setCurrentContext(rawData);
282
+ };
283
+
284
+ const setAuthData = (eventPayload) => {
285
+ if (eventPayload) {
286
+ this.authData = eventPayload;
287
+ }
288
+ };
289
+
290
+ helpers.addEventListener('luigi.init', (e) => {
291
+ setContext(e.data);
292
+ setAuthData(e.data.authData);
293
+ helpers.setLuigiCoreDomain(e.origin);
294
+ this.luigiInitialized = true;
295
+ this._notifyInit(e.origin);
296
+ this._tpcCheck();
297
+ helpers.sendPostMessageToLuigiCore({ msg: 'luigi.init.ok' });
298
+ });
299
+
300
+ helpers.addEventListener('luigi-client.inactive-microfrontend', (e) => {
301
+ this._notifyInactive(e.origin);
302
+ });
303
+
304
+ helpers.addEventListener('luigi.auth.tokenIssued', (e) => {
305
+ setAuthData(e.data.authData);
306
+ });
307
+
308
+ helpers.addEventListener('luigi.navigate', (e) => {
309
+ setContext(e.data);
310
+ if (!this.currentContext.internal.isNavigateBack && !this.currentContext.withoutSync) {
311
+ const previousHash = window.location.hash;
312
+ history.replaceState({ luigiInduced: true }, '', e.data.viewUrl);
313
+ window.dispatchEvent(new PopStateEvent('popstate', { state: 'luiginavigation' }));
314
+ if (window.location.hash !== previousHash) {
315
+ window.dispatchEvent(new HashChangeEvent('hashchange'));
316
+ }
317
+ }
318
+ // pass additional data to context to enable micro frontend developer to act on internal routing change
319
+ if (this.currentContext.withoutSync) {
320
+ Object.assign(this.currentContext.context, {
321
+ viewUrl: e.data.viewUrl ? e.data.viewUrl : undefined,
322
+ pathParams: e.data.pathParams ? e.data.pathParams : undefined
323
+ });
324
+ }
325
+ // execute the context change listener if set by the micro frontend
326
+ this._notifyUpdate();
327
+ helpers.sendPostMessageToLuigiCore({ msg: 'luigi.navigate.ok' });
328
+ });
329
+
330
+ /**
331
+ * Get context once initially
332
+ * @private
333
+ */
334
+ window.parent.postMessage(
335
+ {
336
+ msg: 'luigi.get-context',
337
+ clientVersion: version
338
+ },
339
+ '*'
340
+ );
341
+ }
342
+
343
+ _tpcCheck() {
344
+ if (this._isTpcCheckDisabled()) {
345
+ return;
346
+ }
347
+
348
+ let tpc = 'enabled';
349
+ let cookies = document.cookie;
350
+ let luigiCookie;
351
+ if (cookies) {
352
+ luigiCookie = cookies
353
+ .split(';')
354
+ .map((cookie) => cookie.trim())
355
+ .find((cookie) => cookie === 'luigiCookie=true');
356
+ }
357
+ if (luigiCookie === 'luigiCookie=true') {
358
+ document.cookie = 'luigiCookie=; Max-Age=-99999999; SameSite=None; Secure';
359
+ }
360
+ document.cookie = 'luigiCookie=true; SameSite=None; Secure';
361
+ cookies = document.cookie;
362
+ if (cookies) {
363
+ luigiCookie = cookies
364
+ .split(';')
365
+ .map((cookie) => cookie.trim())
366
+ .find((cookie) => cookie === 'luigiCookie=true');
367
+ }
368
+ if (luigiCookie === 'luigiCookie=true') {
369
+ document.cookie = 'luigiCookie=; Max-Age=-99999999; SameSite=None; Secure';
370
+ window.parent.postMessage({ msg: 'luigi.third-party-cookie', tpc }, '*');
371
+ } else {
372
+ tpc = 'disabled';
373
+ window.parent.postMessage({ msg: 'luigi.third-party-cookie', tpc }, '*');
374
+ console.warn('Third party cookies are not supported!');
375
+ }
376
+ }
377
+
378
+ /**
379
+ * Iterates over an object and executes all top-level functions
380
+ * with a given payload.
381
+ * @private
382
+ * @memberof Lifecycle
383
+ */
384
+ _callAllFns(objWithFns, payload, origin) {
385
+ for (let id in objWithFns) {
386
+ if (objWithFns.hasOwnProperty(id) && helpers.isFunction(objWithFns[id])) {
387
+ objWithFns[id](payload, origin);
388
+ }
389
+ }
390
+ }
391
+
392
+ /**
393
+ * Notifies all context init listeners.
394
+ * @private
395
+ * @memberof Lifecycle
396
+ */
397
+ _notifyInit(origin) {
398
+ this._callAllFns(this._onInitFns, this.currentContext.context, origin);
399
+ }
400
+
401
+ /**
402
+ * Notifies all context update listeners.
403
+ * @private
404
+ * @memberof Lifecycle
405
+ */
406
+ _notifyUpdate() {
407
+ this._callAllFns(this._onContextUpdatedFns, this.currentContext.context);
408
+ }
409
+
410
+ /**
411
+ * Notifies all inactive listeners.
412
+ * @private
413
+ * @memberof Lifecycle
414
+ */
415
+ _notifyInactive() {
416
+ this._callAllFns(this._onInactiveFns);
417
+ }
418
+
419
+ /**
420
+ * @private
421
+ * @memberof Lifecycle
422
+ */
423
+ setCurrentContext(value) {
424
+ this.currentContext = value;
425
+ }
426
+
427
+ /**
428
+ * Registers a listener called with the context object and the Luigi Core domain as soon as Luigi is instantiated. Defer your application bootstrap if you depend on authentication data coming from Luigi.
429
+ * @param {Lifecycle~initListenerCallback} initFn - the function that is called once Luigi is initialized, receives current context and origin as parameters
430
+ * @param {boolean} disableTpcCheck - if set to `true` third party cookie check will be disabled via LuigiClient.
431
+ * @memberof Lifecycle
432
+ * @example
433
+ * const initListenerId = LuigiClient.addInitListener((context) => storeContextToMF(context))
434
+ */
435
+ addInitListener(initFn, disableTpcCheck) {
436
+ const id = helpers.getRandomId();
437
+ this._onInitFns[id] = initFn;
438
+ if (disableTpcCheck) {
439
+ document.head.setAttribute('disable-tpc-check', '');
440
+ }
441
+ if (this.luigiInitialized && helpers.isFunction(initFn)) {
442
+ initFn(this.currentContext.context, helpers.getLuigiCoreDomain());
443
+ }
444
+ return id;
445
+ }
446
+
447
+ /**
448
+ * Callback of the addInitListener <br><br>
449
+ * Type: [Function](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/function)
450
+ * @callback Lifecycle~initListenerCallback
451
+ * @kind function
452
+ * @param {Object} context - current context data
453
+ * @param {string} origin - Luigi Core URL
454
+ */
455
+ /**
456
+ * Removes an init listener.
457
+ * @param {string} id - the id that was returned by the `addInitListener` function
458
+ * @memberof Lifecycle
459
+ * @example
460
+ * LuigiClient.removeInitListener(initListenerId)
461
+ */
462
+ removeInitListener(id) {
463
+ if (this._onInitFns[id]) {
464
+ this._onInitFns[id] = undefined;
465
+ return true;
466
+ }
467
+ return false;
468
+ }
469
+
470
+ /**
471
+ * Registers a listener called with the context object when the URL is changed. For example, you can use this when changing environments in a context switcher in order for the micro frontend to do an API call to the environment picked.
472
+ * @param {function} contextUpdatedFn - the listener function called each time Luigi context changes
473
+ * @memberof Lifecycle
474
+ * @example
475
+ * const updateListenerId = LuigiClient.addContextUpdateListener((context) => storeContextToMF(context))
476
+ */
477
+ addContextUpdateListener(contextUpdatedFn) {
478
+ const id = helpers.getRandomId();
479
+ this._onContextUpdatedFns[id] = contextUpdatedFn;
480
+ if (this.luigiInitialized && helpers.isFunction(contextUpdatedFn)) {
481
+ contextUpdatedFn(this.currentContext.context);
482
+ }
483
+ return id;
484
+ }
485
+
486
+ /**
487
+ * Removes a context update listener.
488
+ * @param {string} id - the id that was returned by the `addContextUpdateListener` function
489
+ * @memberof Lifecycle
490
+ * @example
491
+ * LuigiClient.removeContextUpdateListener(updateListenerId)
492
+ */
493
+ removeContextUpdateListener(id) {
494
+ if (this._onContextUpdatedFns[id]) {
495
+ this._onContextUpdatedFns[id] = undefined;
496
+ return true;
497
+ }
498
+ return false;
499
+ }
500
+
501
+ /**
502
+ * Registers a listener called upon micro frontend inactivity. This happens when a new micro frontend gets shown while keeping the old one cached.
503
+ * Gets called when:
504
+ * - navigating with **preserveView**
505
+ * - navigating from or to a **viewGroup**
506
+ *
507
+ * Does not get called when navigating normally, or when `openAsModal` or `openAsSplitView` are used.
508
+ * Once the micro frontend turns back into active state, the `addContextUpdateListener` receives an updated context.
509
+ * @param {function} inactiveFn - the listener function called each time a micro frontend turns into an inactive state
510
+ * @memberof Lifecycle
511
+ * @example
512
+ * LuigiClient.addInactiveListener(() => mfIsInactive = true)
513
+ * const inactiveListenerId = LuigiClient.addInactiveListener(() => mfIsInactive = true)
514
+ */
515
+ addInactiveListener(inactiveFn) {
516
+ const id = helpers.getRandomId();
517
+ this._onInactiveFns[id] = inactiveFn;
518
+ return id;
519
+ }
520
+
521
+ /**
522
+ * Removes a listener for inactive micro frontends.
523
+ * @param {string} id - the id that was returned by the `addInactiveListener` function
524
+ * @memberof Lifecycle
525
+ * @example
526
+ * LuigiClient.removeInactiveListener(inactiveListenerId)
527
+ */
528
+ removeInactiveListener(id) {
529
+ if (this._onInactiveFns[id]) {
530
+ this._onInactiveFns[id] = undefined;
531
+ return true;
532
+ }
533
+ return false;
534
+ }
535
+
536
+ /**
537
+ * Registers a listener called when the micro frontend receives a custom message.
538
+ * @param {string} customMessageId - the custom message id
539
+ * @param {Lifecycle~customMessageListenerCallback} customMessageListener - the function that is called when the micro frontend receives the corresponding event
540
+ * @memberof Lifecycle
541
+ * @since 0.6.2
542
+ * @example
543
+ * const customMsgId = LuigiClient.addCustomMessageListener('myapp.project-updated', (data) => doSomething(data))
544
+ */
545
+ addCustomMessageListener(customMessageId, customMessageListener) {
546
+ return helpers.addEventListener(customMessageId, (customMessage, listenerId) => {
547
+ return customMessageListener(customMessage, listenerId);
548
+ });
549
+ }
550
+
551
+ /**
552
+ * Callback of the customMessageListener <br><br>
553
+ * Type: [Function](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/function)
554
+ * @callback Lifecycle~customMessageListenerCallback
555
+ * @kind function
556
+ * @param {Object} customMessage - custom message object
557
+ * @param {string} customMessage.id - message id
558
+ * @param {*} customMessage.MY_DATA_FIELD - any other message data field
559
+ * @param {string} listenerId - custom message listener id to be used for unsubscription
560
+ */
561
+ /**
562
+ * Removes a custom message listener.
563
+ * @param {string} id - the id that was returned by the `addInitListener` function
564
+ * @memberof Lifecycle
565
+ * @since 0.6.2
566
+ * @example
567
+ * LuigiClient.removeCustomMessageListener(customMsgId)
568
+ */
569
+ removeCustomMessageListener(id) {
570
+ return helpers.removeEventListener(id);
571
+ }
572
+
573
+ /**
574
+ * Returns the currently valid access token.
575
+ * @returns {string} current access token
576
+ * @memberof Lifecycle
577
+ * @example
578
+ * const accessToken = LuigiClient.getToken()
579
+ */
580
+ getToken() {
581
+ return this.authData.accessToken;
582
+ }
583
+
584
+ /**
585
+ * Returns the context object. Typically it is not required as the {@link #addContextUpdateListener addContextUpdateListener()} receives the same values.
586
+ * @returns {Object} current context data
587
+ * @memberof Lifecycle
588
+ * @example
589
+ * const context = LuigiClient.getContext()
590
+ */
591
+ getContext() {
592
+ return this.getEventData();
593
+ }
594
+
595
+ /**
596
+ * Returns the context object. It is an alias function for getContext().
597
+ * @returns {Object} current context data
598
+ * @memberof Lifecycle
599
+ * @deprecated
600
+ */
601
+ getEventData() {
602
+ return this.currentContext.context;
603
+ }
604
+
605
+ /**
606
+ * Returns a list of active feature toggles
607
+ * @returns {Array} a list of feature toggle names
608
+ * @memberof Lifecycle
609
+ * @since 1.4.0
610
+ * @example
611
+ * const activeFeatureToggleList = LuigiClient.getActiveFeatureToggles()
612
+ */
613
+ getActiveFeatureToggles() {
614
+ return this.currentContext.internal.activeFeatureToggleList ?? [];
615
+ }
616
+
617
+ /**
618
+ * Sets node parameters in Luigi Core. The parameters will be added to the URL.
619
+ * @param {Object} params
620
+ * @param {boolean} keepBrowserHistory
621
+ * @memberof Lifecycle
622
+ * @example
623
+ * LuigiClient.addNodeParams({luigi:'rocks'}, true);
624
+ */
625
+ addNodeParams(params, keepBrowserHistory = true) {
626
+ if (params) {
627
+ helpers.sendPostMessageToLuigiCore({
628
+ msg: 'luigi.addNodeParams',
629
+ data: params,
630
+ keepBrowserHistory
631
+ });
632
+ }
633
+ }
634
+
635
+ /**
636
+ * Returns the node parameters of the active URL.
637
+ * Node parameters are defined like URL query parameters but with a specific prefix allowing Luigi to pass them to the micro frontend view. The default prefix is **~** and you can use it in the following way: `https://my.luigi.app/home/products?~sort=asc&~page=3`.
638
+ * <!-- add-attribute:class:warning -->
639
+ * > **NOTE:** some special characters (`<`, `>`, `"`, `'`, `/`) in node parameters are HTML-encoded.
640
+ * @param {boolean} shouldDesanitise - defines whether the specially encoded characters should be desanitised
641
+ * @returns {Object} node parameters, where the object property name is the node parameter name without the prefix, and its value is the value of the node parameter. For example `{sort: 'asc', page: 3}`
642
+ * @memberof Lifecycle
643
+ * @example
644
+ * const nodeParams = LuigiClient.getNodeParams()
645
+ * const nodeParams = LuigiClient.getNodeParams(true)
646
+ */
647
+ getNodeParams(shouldDesanitise = false) {
648
+ return shouldDesanitise
649
+ ? helpers.deSanitizeParamsMap(this.currentContext.nodeParams)
650
+ : this.currentContext.nodeParams;
651
+ }
652
+
653
+ /**
654
+ * Returns the dynamic path parameters of the active URL.
655
+ * Path parameters are defined by navigation nodes with a dynamic **pathSegment** value starting with **:**, such as **productId**.
656
+ * All path parameters in the current navigation path (as defined by the active URL) are returned.
657
+ * <!-- add-attribute:class:warning -->
658
+ * > **NOTE:** some special characters (`<`, `>`, `"`, `'`, `/`) in path parameters are HTML-encoded.
659
+ * @returns {Object} path parameters, where the object property name is the path parameter name without the prefix, and its value is the actual value of the path parameter. For example ` {productId: 1234, ...}`
660
+ * @memberof Lifecycle
661
+ * @example
662
+ * const pathParams = LuigiClient.getPathParams()
663
+ */
664
+ getPathParams() {
665
+ return this.currentContext.pathParams;
666
+ }
667
+
668
+ /**
669
+ * Read search query parameters which are sent from Luigi Core
670
+ * @memberof Lifecycle
671
+ * @returns Core search query parameters
672
+ * @example
673
+ * LuigiClient.getCoreSearchParams();
674
+ */
675
+ getCoreSearchParams() {
676
+ return this.currentContext.searchParams || {};
677
+ }
678
+
679
+ /**
680
+ * <!-- label-success: Web App API only -->
681
+ * Sends search query parameters to Luigi Core. The search parameters will be added to the URL if they are first allowed on a node level using {@link navigation-parameters-reference.md#clientpermissionsurlparameters clientPermissions.urlParameters}.
682
+
683
+ * @param {Object} searchParams
684
+ * @param {boolean} keepBrowserHistory
685
+ * @memberof Lifecycle
686
+ * @example
687
+ * LuigiClient.addCoreSearchParams({luigi:'rocks'}, false);
688
+ */
689
+ addCoreSearchParams(searchParams, keepBrowserHistory = true) {
690
+ if (searchParams) {
691
+ helpers.sendPostMessageToLuigiCore({
692
+ msg: 'luigi.addSearchParams',
693
+ data: searchParams,
694
+ keepBrowserHistory
695
+ });
696
+ }
697
+ }
698
+
699
+ /**
700
+ * Returns the current client permissions as specified in the navigation node or an empty object. For details, see [Node parameters](navigation-parameters-reference.md).
701
+ * @returns {Object} client permissions as specified in the navigation node
702
+ * @memberof Lifecycle
703
+ * @example
704
+ * const permissions = LuigiClient.getClientPermissions()
705
+ */
706
+ getClientPermissions() {
707
+ return this.currentContext.internal.clientPermissions || {};
708
+ }
709
+
710
+ /**
711
+ * <!-- label-success: Web App API only -->
712
+ * When the micro frontend is not embedded in the Luigi Core application and there is no init handshake you can set the target origin that is used in postMessage function calls by Luigi Client. Typically used only in custom micro-frontend frameworks that are compatible with LuigiClient API.
713
+ * @param {string} origin - target origin
714
+ * @memberof Lifecycle
715
+ * @since 0.7.3
716
+ * @example
717
+ * LuigiClient.setTargetOrigin(window.location.origin)
718
+ */
719
+ setTargetOrigin(origin) {
720
+ helpers.setTargetOrigin(origin);
721
+ }
722
+
723
+ /**
724
+ * <!-- label-success: Web App API only -->
725
+ * Sends a custom message to the Luigi Core application.
726
+ * @param {Object} message - an object containing data to be sent to the Luigi Core to process it further. This object is set as an input parameter of the custom message listener on the Luigi Core side
727
+ * @param {string} message.id - a string containing the message id
728
+ * @param {*} message.MY_DATA_FIELD - any other message data field
729
+ * @example
730
+ * LuigiClient.sendCustomMessage({id: 'environment.created', production: false})
731
+ * LuigiClient.sendCustomMessage({id: 'environment.created', data: environmentDataObj})
732
+ * @memberof Lifecycle
733
+ * @since 0.6.2
734
+ */
735
+ sendCustomMessage(message) {
736
+ const customMessageInternal = helpers.convertCustomMessageUserToInternal(message);
737
+ helpers.sendPostMessageToLuigiCore(customMessageInternal);
738
+ }
739
+
740
+ /**
741
+ * Returns the current user settings based on the selected node.
742
+ * @returns {Object} current user settings
743
+ * @since 1.7.1
744
+ * @memberof Lifecycle
745
+ * @example
746
+ * const userSettings = LuigiClient.getUserSettings()
747
+ */
748
+ getUserSettings() {
749
+ return this.currentContext.internal.userSettings;
750
+ }
751
+
752
+ /**
753
+ * Returns the current anchor based on active URL.
754
+ * @memberof Lifecycle
755
+ * @since 1.21.0
756
+ * @returns anchor of URL
757
+ * @example
758
+ * LuigiClient.getAnchor();
759
+ */
760
+ getAnchor() {
761
+ return this.currentContext.internal.anchor || '';
762
+ }
763
+
764
+ /**
765
+ * Sends anchor to Luigi Core. The anchor will be added to the URL.
766
+ * @param {string} anchor
767
+ * @since 1.21.0
768
+ * @memberof Lifecycle
769
+ * @example
770
+ * LuigiClient.setAnchor('luigi');
771
+ */
772
+ setAnchor(anchor) {
773
+ helpers.sendPostMessageToLuigiCore({
774
+ msg: 'luigi.setAnchor',
775
+ anchor
776
+ });
777
+ }
778
+
779
+ /**
780
+ * This function allows you to change node labels within the same {@link navigation-advanced.md#view-groups view group}, e.g. in your node config: `label: 'my Node {viewGroupData.vg1}'`.
781
+ * @since 2.2.0
782
+ * @param {Object} data - a data object containing the view group name and desired label
783
+ * @memberof Lifecycle
784
+ * @example LuigiClient.setViewGroupData({'vg1':' Luigi rocks!'})
785
+ */
786
+ setViewGroupData(data) {
787
+ helpers.sendPostMessageToLuigiCore({
788
+ msg: 'luigi.setVGData',
789
+ data
790
+ });
791
+ }
792
+ }
793
+ const lifecycleManager$1 = new LifecycleManager();
794
+
795
+ /**
796
+ * @summary Split view allows to open a micro frontend in a split screen in the lower part of the content area. Open it by calling `const splitViewHandle = LuigiClient.linkManager().openAsSplitView`. At a given time, you can open only one split view. It closes automatically when you navigate to a different route. When you call `handle.collapse()`, the split view gets destroyed. It recreates when you use `handle.expand()`. `openAsSplitView` returns an instance of the split view handle. The functions, actions, and event handlers listed below allow you to control and manage the split view.
797
+ * @augments LuigiClientBase
798
+ * @name splitView
799
+ * @since 0.6.0
800
+ * @class
801
+ */
802
+ class splitViewHandle extends LuigiClientBase {
803
+ /**
804
+ * @private
805
+ */
806
+ constructor(settings) {
807
+ super();
808
+
809
+ this.validSplitViewEvents = ['expand', 'collapse', 'resize', 'close'];
810
+
811
+ this.splitView = {
812
+ exists: true,
813
+ size: 40,
814
+ collapsed: false
815
+ };
816
+
817
+ Object.assign(this.splitView, settings);
818
+
819
+ const removeSplitViewListeners = () => {
820
+ this.splitView.listeners.forEach((id) => helpers.removeEventListener(id));
821
+ };
822
+
823
+ this.splitView.listeners = [
824
+ helpers.addEventListener(`luigi.navigation.splitview.internal`, (e) => {
825
+ Object.assign(this.splitView, e.data.data);
826
+ })
827
+ ];
828
+ this.on('resize', (newSize) => {
829
+ this.splitView.size = newSize;
830
+ });
831
+ this.on('close', removeSplitViewListeners);
832
+ }
833
+ /*
834
+ * @private
835
+ */
836
+ sendSplitViewEvent(action, data) {
837
+ helpers.sendPostMessageToLuigiCore({
838
+ msg: `luigi.navigation.splitview.${action}`,
839
+ data
840
+ });
841
+ }
842
+
843
+ /**
844
+ * Collapses the split view
845
+ * @memberof splitView
846
+ * @since 0.6.0
847
+ * @example
848
+ * splitViewHandle.collapse();
849
+ */
850
+ collapse() {
851
+ this.sendSplitViewEvent('collapse');
852
+ }
853
+ /**
854
+ * Expands the split view
855
+ * @memberof splitView
856
+ * @since 0.6.0
857
+ * @example
858
+ * splitViewHandle.expand();
859
+ */
860
+ expand() {
861
+ this.sendSplitViewEvent('expand');
862
+ }
863
+
864
+ /**
865
+ * Closes and destroys the split view
866
+ * @memberof splitView
867
+ * @since 0.6.0
868
+ * @example
869
+ * splitViewHandle.close();
870
+ */
871
+ close() {
872
+ this.sendSplitViewEvent('close');
873
+ }
874
+ /**
875
+ * Sets the height of the split view
876
+ * @memberof splitView
877
+ * @param {number} value - lower height in percent
878
+ * @since 0.6.0
879
+ * @example
880
+ * splitViewHandle.setSize(60);
881
+ */
882
+ setSize(value) {
883
+ this.sendSplitViewEvent('resize', value);
884
+ }
885
+ /**
886
+ * Registers a listener for split view events
887
+ * @memberof splitView
888
+ * @param {('expand'|'collapse'|'resize'|'close')} name - event name
889
+ * @param {function} callback - gets called when this event gets triggered by Luigi
890
+ * @returns {string} listener id
891
+ * @since 0.6.0
892
+ * @example
893
+ * const listenerId = splitViewHandle.on('expand', () => {});
894
+ * const listenerId = splitViewHandle.on('collapse', () => {});
895
+ * const listenerId = splitViewHandle.on('resize', () => {});
896
+ * const listenerId = splitViewHandle.on('close', () => {});
897
+ **/
898
+ on(name, callback) {
899
+ if (!this.validSplitViewEvents.includes(name)) {
900
+ console.warn(name + ' is not a valid split view event');
901
+ return false;
902
+ }
903
+ const id = helpers.addEventListener(`luigi.navigation.splitview.${name}.ok`, (e) => {
904
+ const filterParam = typeof e.data.data == 'number' ? e.data.data : undefined;
905
+ callback(filterParam);
906
+ });
907
+ this.splitView.listeners.push(id);
908
+ return id;
909
+ }
910
+ /**
911
+ * Unregisters a split view listener
912
+ * @memberof splitView
913
+ * @param {string} id - listener id
914
+ * @since 0.6.0
915
+ * @example
916
+ * splitViewHandle.removeEventListener(listenerId);
917
+ */
918
+ removeEventListener(id) {
919
+ return helpers.removeEventListener(id);
920
+ }
921
+
922
+ /**
923
+ * Gets the split view status
924
+ * @memberof splitView
925
+ * @returns {boolean} true if a split view is loaded
926
+ * @since 0.6.0
927
+ * @example
928
+ * splitViewHandle.exists();
929
+ */
930
+ exists() {
931
+ return this.splitView.exists;
932
+ }
933
+ /**
934
+ * Reads the size of the split view
935
+ * @memberof splitView
936
+ * @returns {number} height in percent
937
+ * @since 0.6.0
938
+ * @example
939
+ * splitViewHandle.getSize();
940
+ */
941
+ getSize() {
942
+ return this.splitView.size;
943
+ }
944
+ /**
945
+ * Reads the collapse status
946
+ * @memberof splitView
947
+ * @returns {boolean} true if the split view is currently collapsed
948
+ * @since 0.6.0
949
+ * @example
950
+ * splitViewHandle.isCollapsed();
951
+ */
952
+ isCollapsed() {
953
+ return this.splitView.collapsed;
954
+ }
955
+ /**
956
+ * Reads the expand status
957
+ * @memberof splitView
958
+ * @returns {boolean} true if the split view is currently expanded
959
+ * @since 0.6.0
960
+ * @example
961
+ * splitViewHandle.isExpanded();
962
+ */
963
+ isExpanded() {
964
+ return !this.splitView.collapsed;
965
+ }
966
+ }
967
+
968
+ /**
969
+ * @summary The Link Manager allows you to navigate to another route. Use it instead of an internal router to:
970
+ - Provide routing inside micro frontends.
971
+ - Reflect the route.
972
+ - Keep the navigation state in Luigi.
973
+ * @augments LuigiClientBase
974
+ * @name linkManager
975
+ * @class
976
+ */
977
+ let linkManager$1 = class linkManager extends LuigiClientBase {
978
+ /**
979
+ * @private
980
+ */
981
+ constructor(values) {
982
+ super();
983
+ Object.assign(this, values);
984
+
985
+ this.options = {
986
+ preserveView: false,
987
+ nodeParams: {},
988
+ errorSkipNavigation: false,
989
+ fromContext: null,
990
+ fromClosestContext: false,
991
+ fromVirtualTreeRoot: false,
992
+ fromParent: false,
993
+ relative: false,
994
+ link: '',
995
+ newTab: false,
996
+ preserveQueryParams: false,
997
+ anchor: '',
998
+ preventContextUpdate: false,
999
+ preventHistoryEntry: false
1000
+ };
1001
+ }
1002
+
1003
+ /**
1004
+ * Navigates to the given path in the application hosted by Luigi. It contains either a full absolute path or a relative path without a leading slash that uses the active route as a base. This is the standard navigation.
1005
+ * @memberof linkManager
1006
+ * @param {string} path - path to be navigated to
1007
+ * @param {string} sessionId - current Luigi **sessionId**
1008
+ * @param {boolean} preserveView - preserve a view by setting it to `true`. It keeps the current view opened in the background and opens the new route in a new frame. Use the {@link #goBack goBack()} function to navigate back. You can use this feature across different levels. Preserved views are discarded as soon as you use the standard {@link #navigate navigate()} function instead of {@link #goBack goBack()}
1009
+ * @param {Object} modalSettings - opens a view in a modal. Use these settings to configure the modal's title and size
1010
+ * @param {string} modalSettings.title - modal title. By default, it is the node label. If there is no label, it is left empty
1011
+ * @param {('fullscreen'|'l'|'m'|'s')} [modalSettings.size="l"] - size of the modal
1012
+ * @param {string} modalSettings.width - updates the `width` of the modal. Allowed units are 'px', '%', 'rem', 'em', 'vh' and 'vw'.
1013
+ * @param {string} modalSettings.height - updates the `height` of the modal. Allowed units are 'px', '%', 'rem', 'em', 'vh' and 'vw'.
1014
+ * @param {boolean} modalSettings.keepPrevious - lets you open multiple modals. Keeps the previously opened modal and allows to open another modal on top of the previous one. By default the previous modals are discarded.
1015
+ * @param {string} modalSettings.closebtn_data_testid - lets you specify a `data_testid` for the close button. Default value is `lui-modal-index-0`. If multiple modals are opened the index will be increased per modal.
1016
+ * @param {Object} splitViewSettings - opens a view in a split view. Use these settings to configure the split view's behaviour
1017
+ * @param {string} splitViewSettings.title - split view title. By default, it is the node label. If there is no label, it is left empty
1018
+ * @param {number} [splitViewSettings.size=40] - height of the split view in percent
1019
+ * @param {boolean} [splitViewSettings.collapsed=false] - creates split view but leaves it closed initially
1020
+ * @param {Object} drawerSettings - opens a view in a drawer. Use these settings to configure if the drawer has a header, backdrop and size
1021
+ * @param {any} drawerSettings.header - by default, the header is visible. The default title is the node label, but the header could also be an object with a `title` attribute allowing you to specify your own title. An 'x' icon is displayed to close the drawer view
1022
+ * @param {boolean} drawerSettings.backdrop - by default, it is set to `false`. If it is set to `true` the rest of the screen has a backdrop
1023
+ * @param {('l'|'m'|'s'|'xs')} [drawerSettings.size="s"] - size of the drawer
1024
+ * @example
1025
+ * LuigiClient.linkManager().navigate('/overview')
1026
+ * LuigiClient.linkManager().navigate('users/groups/stakeholders')
1027
+ * LuigiClient.linkManager().navigate('/settings', null, true) // preserve view
1028
+ * LuigiClient.linkManager().navigate('#?Intent=Sales-order?id=13') // intent navigation
1029
+ */
1030
+ navigate(path, sessionId, preserveView, modalSettings, splitViewSettings, drawerSettings) {
1031
+ if (this.options.errorSkipNavigation) {
1032
+ this.options.errorSkipNavigation = false;
1033
+ return;
1034
+ }
1035
+ if (modalSettings && splitViewSettings && drawerSettings) {
1036
+ console.warn(
1037
+ 'modalSettings, splitViewSettings and drawerSettings cannot be used together. Only modal setting will be taken into account.'
1038
+ );
1039
+ }
1040
+
1041
+ this.options.preserveView = preserveView;
1042
+ const relativePath = path[0] !== '/';
1043
+
1044
+ if (path === '/' && (modalSettings || splitViewSettings || drawerSettings)) {
1045
+ console.warn('Navigation with an absolute path prevented.');
1046
+ return;
1047
+ }
1048
+ const navigationOpenMsg = {
1049
+ msg: 'luigi.navigation.open',
1050
+ sessionId: sessionId,
1051
+ params: Object.assign(this.options, {
1052
+ link: path,
1053
+ relative: relativePath,
1054
+ intent: helpers.hasIntent(path),
1055
+ modal: modalSettings,
1056
+ splitView: splitViewSettings,
1057
+ drawer: drawerSettings
1058
+ })
1059
+ };
1060
+ helpers.sendPostMessageToLuigiCore(navigationOpenMsg);
1061
+ }
1062
+
1063
+ /**
1064
+ * Updates path of the modalPathParam when internal navigation occurs.
1065
+ * @memberof linkManager
1066
+ * @param {string} path
1067
+ * @param {boolean} addHistoryEntry - adds an entry in the history
1068
+ * @param {Object} [modalSettings] - opens a view in a modal. Use these settings to configure the modal's title and size
1069
+ * @since 1.21.0
1070
+ * @example
1071
+ * LuigiClient.linkManager().updateModalPathInternalNavigation('microfrontend')
1072
+ */
1073
+ updateModalPathInternalNavigation(path, modalSettings = {}, addHistoryEntry = false) {
1074
+ if (!path) {
1075
+ console.warn('Updating path of the modal upon internal navigation prevented. No path specified.');
1076
+ return;
1077
+ }
1078
+
1079
+ const navigationOpenMsg = {
1080
+ msg: 'luigi.navigation.updateModalDataPath',
1081
+ params: Object.assign(this.options, {
1082
+ link: path,
1083
+ modal: modalSettings,
1084
+ history: addHistoryEntry
1085
+ })
1086
+ };
1087
+ helpers.sendPostMessageToLuigiCore(navigationOpenMsg);
1088
+ }
1089
+
1090
+ /**
1091
+ * Offers an alternative way of navigating with intents. This involves specifying a semanticSlug and an object containing
1092
+ * parameters.
1093
+ * This method internally generates a URL of the form `#?intent=<semantic object>-<action>?<param_name>=<param_value>` through the given
1094
+ * input arguments. This then follows a call to the original `linkManager.navigate(...)` function.
1095
+ * Consequently, the following calls shall have the exact same effect:
1096
+ * - linkManager().navigateToIntent('Sales-settings', {project: 'pr2', user: 'john'})
1097
+ * - linkManager().navigate('/#?intent=Sales-settings?project=pr2&user=john')
1098
+ * @param {string} semanticSlug - concatenation of semantic object and action connected with a dash (-), i.e.: `<semanticObject>-<action>`
1099
+ * @param {Object} params - an object representing all the parameters passed, i.e.: `{param1: '1', param2: 2, param3: 'value3'}`
1100
+ * @example
1101
+ * LuigiClient.linkManager().navigateToIntent('Sales-settings', {project: 'pr2', user: 'john'})
1102
+ * LuigiClient.linkManager().navigateToIntent('Sales-settings')
1103
+ */
1104
+ navigateToIntent(semanticSlug, params = {}) {
1105
+ let newPath = '#?intent=';
1106
+ newPath += semanticSlug;
1107
+ if (params && Object.keys(params)?.length) {
1108
+ const paramList = Object.entries(params);
1109
+ // append parameters to the path if any
1110
+ if (paramList.length > 0) {
1111
+ newPath += '?';
1112
+ for (const [key, value] of paramList) {
1113
+ newPath += key + '=' + value + '&';
1114
+ }
1115
+ // trim potential excessive ampersand & at the end
1116
+ newPath = newPath.slice(0, -1);
1117
+ }
1118
+ }
1119
+ this.navigate(newPath);
1120
+ }
1121
+
1122
+ /**
1123
+ * Opens a view in a modal. You can specify the modal's title and size. If you don't specify the title, it is the node label. If there is no node label, the title remains empty. The default size of the modal is `l`, which means 80%. You can also use `m` (60%) and `s` (40%) to set the modal size. Optionally, use it in combination with any of the navigation functions.
1124
+ * @memberof linkManager
1125
+ * @param {string} path - navigation path
1126
+ * @param {Object} [modalSettings] - opens a view in a modal. Use these settings to configure the modal's title and size
1127
+ * @param {string} modalSettings.title - modal title. By default, it is the node label. If there is no label, it is left empty
1128
+ * @param {('fullscreen'|'l'|'m'|'s')} [modalSettings.size="l"] - size of the modal
1129
+ * @param {string} modalSettings.width - updates the `width` of the modal. Allowed units are 'px', '%', 'rem', 'em', 'vh' and 'vw'
1130
+ * @param {string} modalSettings.height - updates the `height` of the modal. Allowed units are 'px', '%', 'rem', 'em', 'vh' and 'vw'
1131
+ * @param {boolean} modalSettings.keepPrevious - lets you open multiple modals. Keeps the previously opened modal and allows to open another modal on top of the previous one. By default the previous modals are discarded
1132
+ * @param {string} modalSettings.closebtn_data_testid - lets you specify a `data_testid` for the close button. Default value is `lui-modal-index-0`. If multiple modals are opened the index will be increased per modal
1133
+ * @returns {promise} which is resolved when closing the modal. By using LuigiClient.linkManager().goBack({ foo: 'bar' }) to close the modal you have access to the `goBackContext` when the promise will be resolved.
1134
+ * @example
1135
+ * LuigiClient.linkManager().openAsModal('projects/pr1/users', {title:'Users', size:'m'}).then((res) => {
1136
+ * // Logic to execute when the modal will be closed
1137
+ * console.log(res.data) //=> {foo: 'bar'}
1138
+ * });
1139
+ */
1140
+ openAsModal(path, modalSettings = {}) {
1141
+ helpers.addEventListener('luigi.navigation.modal.close', (e, listenerId) => {
1142
+ const promise = this.getPromise('modal');
1143
+ if (promise) {
1144
+ promise.resolveFn({ ...e.data, goBackValue: e.data?.data });
1145
+ this.setPromise('modal', undefined);
1146
+ }
1147
+ helpers.removeEventListener(listenerId);
1148
+ });
1149
+ const modalPromise = {};
1150
+ modalPromise.promise = new Promise((resolve, reject) => {
1151
+ modalPromise.resolveFn = resolve;
1152
+ modalPromise.rejectFn = reject;
1153
+ });
1154
+ this.setPromise('modal', modalPromise);
1155
+ this.navigate(path, 0, true, modalSettings);
1156
+ return modalPromise.promise;
1157
+ }
1158
+
1159
+ /**
1160
+ * <!-- label-success: Web App API only -->
1161
+ * Updates the current title and size of a modal. If `routing.showModalPathInUrl` is set to `true`, the URL will be updated with the modal settings data.
1162
+ * In addition, you can specify if a new history entry will be created with the updated URL.
1163
+ * @memberof linkManager
1164
+ * @param {Object} updatedModalSettings - possibility to update the active modal
1165
+ * @param {Object} updatedModalSettings.title - update the `title` of the active modal
1166
+ * @param {Object} updatedModalSettings.size - update the `size` of the active modal
1167
+ * @param {string} updatedModalSettings.width - updates the `width` of the modal. Allowed units are 'px', '%', 'rem', 'em', 'vh' and 'vw'
1168
+ * @param {string} updatedModalSettings.height - updates the `height` of the modal. Allowed units are 'px', '%', 'rem', 'em', 'vh' and 'vw'
1169
+ * @param {boolean} addHistoryEntry - adds an entry in the history, by default it's `false`.
1170
+ * @example
1171
+ * LuigiClient.linkManager().updateModalSettings({title:'LuigiModal', size:'l'});
1172
+ */
1173
+ updateModalSettings(updatedModalSettings = {}, addHistoryEntry = false) {
1174
+ const message = {
1175
+ msg: 'luigi.navigation.updateModalSettings',
1176
+ updatedModalSettings,
1177
+ addHistoryEntry
1178
+ };
1179
+ helpers.sendPostMessageToLuigiCore(message);
1180
+ }
1181
+
1182
+ /**
1183
+ * Opens a view in a split view. You can specify the split view's title and size. If you don't specify the title, it is the node label. If there is no node label, the title remains empty. The default size of the split view is `40`, which means 40% height of the split view.
1184
+ * @memberof linkManager
1185
+ * @param {string} path - navigation path
1186
+ * @param {Object} splitViewSettings - opens a view in a split view. Use these settings to configure the split view's behaviour
1187
+ * @param {string} splitViewSettings.title - split view title. By default, it is the node label. If there is no label, it is left empty
1188
+ * @param {number} [splitViewSettings.size=40] - height of the split view in percent
1189
+ * @param {boolean} [splitViewSettings.collapsed=false] - opens split view in collapsed state
1190
+ * @returns {Object} instance of the SplitView. It provides Event listeners and you can use the available functions to control its behavior.
1191
+ * @see {@link splitView} for further documentation about the returned instance
1192
+ * @since 0.6.0
1193
+ * @example
1194
+ * const splitViewHandle = LuigiClient.linkManager().openAsSplitView('projects/pr1/logs', {title: 'Logs', size: 40, collapsed: true});
1195
+ */
1196
+ openAsSplitView(path, splitViewSettings = {}) {
1197
+ this.navigate(path, 0, true, undefined, splitViewSettings);
1198
+ return new splitViewHandle(splitViewSettings);
1199
+ }
1200
+
1201
+ /**
1202
+ * Opens a view in a drawer. You can specify the size of the drawer, whether the drawer has a header, and whether a backdrop is active in the background. By default, the header is shown. The backdrop is not visible and has to be activated. The size of the drawer is set to `s` by default, which means 25% of the micro frontend size. You can also use `l`(75%), `m`(50%) or `xs`(15.5%). Optionally, use it in combination with any of the navigation functions.
1203
+ * @memberof linkManager
1204
+ * @param {string} path - navigation path
1205
+ * @param {Object} drawerSettings - opens a view in a drawer. Use these settings to configure if the drawer has a header, backdrop and size.
1206
+ * @param {any} drawerSettings.header - by default, the header is visible. The default title is the node label, but the header could also be an object with a `title` attribute allowing you to specify your own title. An 'x' icon is displayed to close the drawer view.
1207
+ * @param {boolean} drawerSettings.backdrop - by default, it is set to `false`. If it is set to `true` the rest of the screen has a backdrop.
1208
+ * @param {('l'|'m'|'s'|'xs')} [drawerSettings.size="s"] - size of the drawer
1209
+ * @param {boolean} [drawerSettings.overlap=true] - enable resizing of main microfrontend iFrame after drawer open
1210
+ * @since 1.6.0
1211
+ * @example
1212
+ * LuigiClient.linkManager().openAsDrawer('projects/pr1/drawer', {header:true, backdrop:true, size:'s'});
1213
+ * LuigiClient.linkManager().openAsDrawer('projects/pr1/drawer', {header:{title:'My drawer component'}, backdrop:true, size:'xs'});
1214
+ */
1215
+ openAsDrawer(path, drawerSettings = {}) {
1216
+ this.navigate(path, 0, true, undefined, undefined, drawerSettings);
1217
+ }
1218
+
1219
+ /**
1220
+ * Sets the current navigation context to that of a specific parent node which has the {@link navigation-configuration.md navigationContext} field declared in the navigation configuration. This navigation context is then used by the `navigate` function.
1221
+ * @memberof linkManager
1222
+ * @param {string} navigationContext
1223
+ * @returns {linkManager} link manager instance
1224
+ * @example
1225
+ * LuigiClient.linkManager().fromContext('project').navigate('/settings')
1226
+ */
1227
+ fromContext(navigationContext) {
1228
+ const navigationContextInParent =
1229
+ this.currentContext.context.parentNavigationContexts &&
1230
+ this.currentContext.context.parentNavigationContexts.indexOf(navigationContext) !== -1;
1231
+ if (navigationContextInParent) {
1232
+ this.options.fromContext = navigationContext;
1233
+ } else {
1234
+ this.options.errorSkipNavigation = true;
1235
+ console.error('Navigation not possible, navigationContext ' + navigationContext + ' not found.');
1236
+ }
1237
+ return this;
1238
+ }
1239
+
1240
+ /**
1241
+ * Sets the current navigation context which is then used by the `navigate` function. This has to be a parent navigation context, it is not possible to use the child navigation contexts.
1242
+ * @memberof linkManager
1243
+ * @returns {linkManager} link manager instance
1244
+ * @example
1245
+ * LuigiClient.linkManager().fromClosestContext().navigate('/users/groups/stakeholders')
1246
+ */
1247
+ fromClosestContext() {
1248
+ const hasParentNavigationContext = this.currentContext?.context.parentNavigationContexts.length > 0;
1249
+ if (hasParentNavigationContext) {
1250
+ this.options.fromContext = null;
1251
+ this.options.fromClosestContext = true;
1252
+ } else {
1253
+ console.error('Navigation not possible, no parent navigationContext found.');
1254
+ }
1255
+ return this;
1256
+ }
1257
+
1258
+ /**
1259
+ * Sets the current navigation base to the parent node that is defined as virtualTree. This method works only when the currently active micro frontend is inside a virtualTree.
1260
+ * @memberof linkManager
1261
+ * @returns {linkManager} link manager instance
1262
+ * @since 1.0.1
1263
+ * @example
1264
+ * LuigiClient.linkManager().fromVirtualTreeRoot().navigate('/users/groups/stakeholders')
1265
+ */
1266
+ fromVirtualTreeRoot() {
1267
+ this.options.fromContext = null;
1268
+ this.options.fromClosestContext = false;
1269
+ this.options.fromVirtualTreeRoot = true;
1270
+ return this;
1271
+ }
1272
+
1273
+ /**
1274
+ * Enables navigating to sibling nodes without knowing the absolute path.
1275
+ * @memberof linkManager
1276
+ * @returns {linkManager} link manager instance
1277
+ * @since 1.0.1
1278
+ * @example
1279
+ * LuigiClient.linkManager().fromParent().navigate('/sibling')
1280
+ */
1281
+ fromParent() {
1282
+ this.options.fromParent = true;
1283
+ return this;
1284
+ }
1285
+
1286
+ /**
1287
+ * Sends node parameters to the route. The parameters are used by the `navigate` function. Use it optionally in combination with any of the navigation functions and receive it as part of the context object in Luigi Client.
1288
+ * @memberof linkManager
1289
+ * @param {Object} nodeParams
1290
+ * @returns {linkManager} link manager instance
1291
+ * @example
1292
+ * LuigiClient.linkManager().withParams({foo: "bar"}).navigate("path")
1293
+ *
1294
+ * // Can be chained with context setting functions such as:
1295
+ * LuigiClient.linkManager().fromContext("currentTeam").withParams({foo: "bar"}).navigate("path")
1296
+ */
1297
+ withParams(nodeParams) {
1298
+ if (nodeParams) {
1299
+ Object.assign(this.options.nodeParams, nodeParams);
1300
+ }
1301
+ return this;
1302
+ }
1303
+
1304
+ /**
1305
+ * <!-- label-success: Web App API only -->
1306
+ * Sets options to customise route changing behaviour. The parameters are used by the `navigate` function. Use it optionally in combination with any of the navigation functions and receive it as part of the context object in Luigi Client.
1307
+ * @memberof linkManager
1308
+ * @param {Object} options - navigation options
1309
+ * @param {boolean} options.preventHistoryEntry - by default, it is set to `false`. If it is set to `true`, there is no browser history being kept.
1310
+ * @param {boolean} options.preventContextUpdate - by default, it is set to `false`. If it is set to `true`, there is no context update being triggered.
1311
+ * @returns {linkManager} link manager instance
1312
+ * @since 1.25.0
1313
+ * @example
1314
+ * LuigiClient.linkManager().withOptions(
1315
+ * { preventContextUpdate:true, preventHistoryEntry: true }
1316
+ * ).navigate('/overview')
1317
+ */
1318
+ withOptions(options) {
1319
+ if (!helpers.isObject(options)) return this;
1320
+
1321
+ if (options['preventHistoryEntry'] !== undefined) {
1322
+ this.options.preventHistoryEntry = options['preventHistoryEntry'];
1323
+ }
1324
+
1325
+ if (options['preventContextUpdate'] !== undefined) {
1326
+ this.options.preventContextUpdate = options['preventContextUpdate'];
1327
+ }
1328
+
1329
+ return this;
1330
+ }
1331
+
1332
+ /** @lends linkManager */
1333
+ /**
1334
+ * Checks if the path you can navigate to exists in the main application. For example, you can use this helper method conditionally to display a DOM element like a button.
1335
+ * @memberof linkManager
1336
+ * @param {string} path - path which existence you want to check
1337
+ * @returns {promise} a promise which resolves to a Boolean variable specifying whether the path exists or not
1338
+ * @example
1339
+ * let pathExists;
1340
+ * LuigiClient
1341
+ * .linkManager()
1342
+ * .pathExists('projects/pr2')
1343
+ * .then(
1344
+ * (pathExists) => { }
1345
+ * );
1346
+ */
1347
+ pathExists(path) {
1348
+ const currentId = helpers.getRandomId();
1349
+ const pathExistsPromises = this.getPromise('pathExistsPromises') || {};
1350
+ pathExistsPromises[currentId] = {
1351
+ resolveFn: function () {},
1352
+ then: function (resolveFn) {
1353
+ this.resolveFn = resolveFn;
1354
+ }
1355
+ };
1356
+ this.setPromise('pathExistsPromises', pathExistsPromises);
1357
+
1358
+ // register event listener, which will be cleaned up after this usage
1359
+ helpers.addEventListener(
1360
+ 'luigi.navigation.pathExists.answer',
1361
+ function (e, listenerId) {
1362
+ const data = e.data.data;
1363
+ const pathExistsPromises = this.getPromise('pathExistsPromises') || {};
1364
+ if (data.correlationId === currentId) {
1365
+ if (pathExistsPromises[data.correlationId]) {
1366
+ pathExistsPromises[data.correlationId].resolveFn(data.pathExists);
1367
+ delete pathExistsPromises[data.correlationId];
1368
+ this.setPromise('pathExistsPromises', pathExistsPromises);
1369
+ }
1370
+ helpers.removeEventListener(listenerId);
1371
+ }
1372
+ }.bind(this)
1373
+ );
1374
+
1375
+ const pathExistsMsg = {
1376
+ msg: 'luigi.navigation.pathExists',
1377
+ data: Object.assign(this.options, {
1378
+ id: currentId,
1379
+ link: path,
1380
+ intent: helpers.hasIntent(path),
1381
+ relative: path[0] !== '/'
1382
+ })
1383
+ };
1384
+ helpers.sendPostMessageToLuigiCore(pathExistsMsg);
1385
+ return pathExistsPromises[currentId];
1386
+ }
1387
+
1388
+ /**
1389
+ * Checks if there is one or more preserved views. You can use it to show a **back** button.
1390
+ * @memberof linkManager
1391
+ * @returns {boolean} indicating if there is a preserved view you can return to
1392
+ */
1393
+ hasBack() {
1394
+ return !!this.currentContext.internal.modal || this.currentContext.internal.viewStackSize !== 0;
1395
+ }
1396
+
1397
+ /**
1398
+ * Discards the active view and navigates back to the last visited view. Works with preserved views, and also acts as the substitute of the browser **back** button. **goBackContext** is only available when using preserved views.
1399
+ * @memberof linkManager
1400
+ * @param {any} goBackValue - data that is passed in the **goBackContext** field to the last visited view when using preserved views
1401
+ * @example
1402
+ * LuigiClient.linkManager().goBack({ foo: 'bar' });
1403
+ * LuigiClient.linkManager().goBack(true);
1404
+ */
1405
+ goBack(goBackValue) {
1406
+ helpers.sendPostMessageToLuigiCore({
1407
+ msg: 'luigi.navigation.back',
1408
+ goBackContext: goBackValue && JSON.stringify(goBackValue)
1409
+ });
1410
+ }
1411
+
1412
+ /**
1413
+ * <!-- label-success: Web App API only -->
1414
+ * Disables the navigation handling for a single navigation request.
1415
+ * It prevents Luigi Core from handling the URL change after `navigate()`.
1416
+ * Used for auto-navigation.
1417
+ * @since 0.7.7
1418
+ * @example
1419
+ * LuigiClient.linkManager().withoutSync().navigate('/projects/xy/foobar');
1420
+ * LuigiClient.linkManager().withoutSync().fromClosestContext().navigate('settings');
1421
+ */
1422
+ withoutSync() {
1423
+ this.options.withoutSync = true;
1424
+ return this;
1425
+ }
1426
+
1427
+ /**
1428
+ * <!-- label-success: Web App API only -->
1429
+ * Enables navigating to a new tab.
1430
+ * @since 1.16.0
1431
+ * @example
1432
+ * LuigiClient.linkManager().newTab().navigate('/projects/xy/foobar');
1433
+ */
1434
+ newTab() {
1435
+ this.options.newTab = true;
1436
+ return this;
1437
+ }
1438
+
1439
+ /**
1440
+ * <!-- label-success: Web App API only -->
1441
+ * Keeps the URL's query parameters for a navigation request.
1442
+ * @param {boolean} preserve - by default, it is set to `false`. If it is set to `true`, the URL's query parameters will be kept after navigation.
1443
+ * @since 1.19.0
1444
+ * @example
1445
+ * LuigiClient.linkManager().preserveQueryParams(true).navigate('/projects/xy/foobar');
1446
+ * LuigiClient.linkManager().preserveQueryParams(false).navigate('/projects/xy/foobar');
1447
+ */
1448
+ preserveQueryParams(preserve = false) {
1449
+ this.options.preserveQueryParams = preserve;
1450
+ return this;
1451
+ }
1452
+
1453
+ /**
1454
+ * Gets the luigi route associated with the current micro frontend.
1455
+ * @returns {promise} a promise which resolves to a String value specifying the current luigi route
1456
+ * @since 1.23.0
1457
+ * @example
1458
+ * LuigiClient.linkManager().getCurrentRoute();
1459
+ * LuigiClient.linkManager().fromContext('project').getCurrentRoute();
1460
+ * LuigiClient.linkManager().fromVirtualTreeRoot().getCurrentRoute();
1461
+ */
1462
+ getCurrentRoute() {
1463
+ const currentId = helpers.getRandomId();
1464
+
1465
+ const currentRoutePromise = this.getPromise('getCurrentRoute') || {};
1466
+ currentRoutePromise[currentId] = {
1467
+ resolveFn: function () {},
1468
+ then: function (resolveFn) {
1469
+ this.resolveFn = resolveFn;
1470
+ }
1471
+ };
1472
+
1473
+ this.setPromise('getCurrentRoute', currentRoutePromise);
1474
+
1475
+ helpers.addEventListener('luigi.navigation.currentRoute.answer', (e, listenerId) => {
1476
+ const data = e.data.data;
1477
+ const currentRoutePromise = this.getPromise('getCurrentRoute') || {};
1478
+
1479
+ if (data.correlationId === currentId) {
1480
+ if (currentRoutePromise[data.correlationId]) {
1481
+ currentRoutePromise[data.correlationId].resolveFn(data.route);
1482
+ delete currentRoutePromise[data.correlationId];
1483
+ this.setPromise('getCurrentRoute', currentRoutePromise);
1484
+ }
1485
+ helpers.removeEventListener(listenerId);
1486
+ }
1487
+ helpers.removeEventListener(listenerId);
1488
+ });
1489
+
1490
+ helpers.sendPostMessageToLuigiCore({
1491
+ msg: 'luigi.navigation.currentRoute',
1492
+ data: Object.assign(this.options, {
1493
+ id: currentId
1494
+ })
1495
+ });
1496
+
1497
+ return currentRoutePromise[currentId];
1498
+ }
1499
+ };
1500
+
1501
+ /**
1502
+ * @summary Use the UX Manager to manage the appearance features in Luigi.
1503
+ * @augments LuigiClientBase
1504
+ * @name uxManager
1505
+ * @class
1506
+ */
1507
+ class UxManager extends LuigiClientBase {
1508
+ /** @private */
1509
+ constructor() {
1510
+ super();
1511
+ helpers.addEventListener('luigi.current-locale-changed', (e) => {
1512
+ if (e.data.currentLocale && lifecycleManager$1.currentContext?.internal) {
1513
+ lifecycleManager$1.currentContext.internal.currentLocale = e.data.currentLocale;
1514
+ lifecycleManager$1._notifyUpdate();
1515
+ }
1516
+ });
1517
+ }
1518
+
1519
+ /**
1520
+ * Adds a backdrop with a loading indicator for the micro frontend frame. This overrides the {@link navigation-parameters-reference.md#node-parameters loadingIndicator.enabled} setting.
1521
+ * @memberof uxManager
1522
+ */
1523
+ showLoadingIndicator() {
1524
+ helpers.sendPostMessageToLuigiCore({ msg: 'luigi.show-loading-indicator' });
1525
+ }
1526
+
1527
+ /**
1528
+ * Removes the loading indicator. Use it after calling {@link #showLoadingIndicator showLoadingIndicator()} or to hide the indicator when you use the {@link navigation-parameters-reference.md#node-parameters loadingIndicator.hideAutomatically: false} node configuration.
1529
+ * @memberof uxManager
1530
+ */
1531
+ hideLoadingIndicator() {
1532
+ helpers.sendPostMessageToLuigiCore({ msg: 'luigi.hide-loading-indicator' });
1533
+ }
1534
+
1535
+ /**
1536
+ * Closes the currently opened micro frontend modal.
1537
+ * @memberof uxManager
1538
+ */
1539
+ closeCurrentModal() {
1540
+ helpers.sendPostMessageToLuigiCore({ msg: 'luigi.close-modal' });
1541
+ }
1542
+
1543
+ /**
1544
+ * Adds a backdrop to block the top and side navigation. It is based on the Fundamental UI Modal, which you can use in your micro frontend to achieve the same behavior.
1545
+ * @memberof uxManager
1546
+ */
1547
+ addBackdrop() {
1548
+ helpers.sendPostMessageToLuigiCore({ msg: 'luigi.add-backdrop' });
1549
+ }
1550
+
1551
+ /**
1552
+ * Removes the backdrop.
1553
+ * @memberof uxManager
1554
+ */
1555
+ removeBackdrop() {
1556
+ helpers.sendPostMessageToLuigiCore({ msg: 'luigi.remove-backdrop' });
1557
+ }
1558
+
1559
+ /**
1560
+ * This method informs the main application that there are unsaved changes in the current view in the iframe. It can be used to prevent navigation away from the current view, for example with form fields which were edited but not submitted. However, this functionality is not restricted to forms. If you use `withoutSync()` together with `setDirtyStatus()`, this is a special case in which the dirty state logic needs to be handled by the micro frontend. For example, if the user navigates with an Angular router, which would trigger `withoutSync()`, Angular needs to take care about dirty state, prevent the navigation and ask for permission to navigate away, through `uxManager().showConfirmationModal(settings)`.
1561
+ * @param {boolean} isDirty - indicates if there are any unsaved changes on the current page or in the component
1562
+ * @memberof uxManager
1563
+ */
1564
+ setDirtyStatus(isDirty) {
1565
+ helpers.sendPostMessageToLuigiCore({
1566
+ msg: 'luigi.set-page-dirty',
1567
+ dirty: isDirty
1568
+ });
1569
+ }
1570
+
1571
+ /**
1572
+ * Shows a confirmation modal.
1573
+ * @memberof uxManager
1574
+ * @param {Object} settings - the settings of the confirmation modal. If you don't provide any value for any of the fields, a default value is used
1575
+ * @param {('confirmation'|'success'|'warning'|'error'|'information')} settings.type - the content of the modal type. (Optional)
1576
+ * @param {string} [settings.header="Confirmation"] - the content of the modal header
1577
+ * @param {string} [settings.body="Are you sure you want to do this?"] - the content of the modal body. It supports HTML formatting elements such as `<br>`, `<b>`, `<strong>`, `<i>`, `<em>`, `<mark>`, `<small>`, `<del>`, `<ins>`, `<sub>`, `<sup>`.
1578
+ * @param {string|false} [settings.buttonConfirm="Yes"] - the label for the modal confirmation button. If set to `false`, the button will not be shown.
1579
+ * @param {string} [settings.buttonDismiss="No"] - the label for the modal dismiss button
1580
+ * @returns {promise} which is resolved when accepting the confirmation modal and rejected when dismissing it
1581
+ * @example
1582
+ * import LuigiClient from '@luigi-project/client';
1583
+ * const settings = {
1584
+ * type: "confirmation",
1585
+ * header: "Confirmation",
1586
+ * body: "Are you sure you want to do this?",
1587
+ * buttonConfirm: "Yes",
1588
+ * buttonDismiss: "No"
1589
+ * }
1590
+ * LuigiClient
1591
+ * .uxManager()
1592
+ * .showConfirmationModal(settings)
1593
+ * .then(() => {
1594
+ * // Logic to execute when the confirmation modal is dismissed
1595
+ * });
1596
+ */
1597
+ showConfirmationModal(settings) {
1598
+ helpers.addEventListener('luigi.ux.confirmationModal.hide', (e, listenerId) => {
1599
+ this.hideConfirmationModal(e.data.data);
1600
+ helpers.removeEventListener(listenerId);
1601
+ });
1602
+ helpers.sendPostMessageToLuigiCore({
1603
+ msg: 'luigi.ux.confirmationModal.show',
1604
+ data: { settings }
1605
+ });
1606
+
1607
+ const confirmationModalPromise = {};
1608
+ confirmationModalPromise.promise = new Promise((resolve, reject) => {
1609
+ confirmationModalPromise.resolveFn = resolve;
1610
+ confirmationModalPromise.rejectFn = reject;
1611
+ });
1612
+ this.setPromise('confirmationModal', confirmationModalPromise);
1613
+ return confirmationModalPromise.promise;
1614
+ }
1615
+
1616
+ /**
1617
+ * @private
1618
+ * @memberof uxManager
1619
+ * @param {Object} modal - confirmed boolean value if ok or cancel has been pressed
1620
+ */
1621
+ hideConfirmationModal(modal) {
1622
+ const promise = this.getPromise('confirmationModal');
1623
+ if (promise) {
1624
+ modal.confirmed ? promise.resolveFn() : promise.rejectFn();
1625
+ this.setPromise('confirmationModal', undefined);
1626
+ }
1627
+ }
1628
+
1629
+ /**
1630
+ * Shows an alert.
1631
+ * @memberof uxManager
1632
+ * @param {Object} settings - the settings for the alert
1633
+ * @param {string} settings.text - the content of the alert. To add a link to the content, you have to set up the link in the `links` object. The key(s) in the `links` object must be used in the text to reference the links, wrapped in curly brackets with no spaces. If you don't specify any text, the alert is not displayed
1634
+ * @param {('info'|'success'|'warning'|'error')} settings.type - sets the type of alert
1635
+ * @param {Object} settings.links - provides links data
1636
+ * @param {Object} settings.links.LINK_KEY - object containing the data for a particular link. To properly render the link in the alert message refer to the description of the **settings.text** parameter
1637
+ * @param {string} settings.links.LINK_KEY.text - text which replaces the link identifier in the alert content
1638
+ * @param {string} settings.links.LINK_KEY.url - URL to navigate when you click the link. Currently, only internal links are supported in the form of relative or absolute paths
1639
+ * @param {string} settings.links.LINK_KEY.dismissKey - dismissKey which represents the key of the link
1640
+ * @param {number} settings.closeAfter - (optional) time in milliseconds that tells Luigi when to close the Alert automatically. If not provided, the Alert will stay on until closed manually. It has to be greater than `100`
1641
+ * @returns {promise} which is resolved when the alert is dismissed
1642
+ * @example
1643
+ * import LuigiClient from '@luigi-project/client';
1644
+ * const settings = {
1645
+ * text: "Ut enim ad minim veniam, {goToHome} quis nostrud exercitation ullamco {relativePath}. Duis aute irure dolor {goToOtherProject} or {neverShowItAgain}",
1646
+ * type: 'info',
1647
+ * links: {
1648
+ * goToHome: { text: 'homepage', url: '/overview' },
1649
+ * goToOtherProject: { text: 'other project', url: '/projects/pr2' },
1650
+ * relativePath: { text: 'relative hide side nav', url: 'hideSideNav' },
1651
+ * neverShowItAgain: { text: 'Never show it again', dismissKey: 'neverShowItAgain' }
1652
+ * },
1653
+ * closeAfter: 3000
1654
+ * }
1655
+ * LuigiClient
1656
+ * .uxManager()
1657
+ * .showAlert(settings)
1658
+ * .then(() => {
1659
+ * // Logic to execute when the alert is dismissed
1660
+ * });
1661
+ */
1662
+ showAlert(settings) {
1663
+ //generate random ID
1664
+ settings.id = helpers.getRandomId();
1665
+
1666
+ helpers.addEventListener('luigi.ux.alert.hide', (e, listenerId) => {
1667
+ if (e.data.id === settings.id) {
1668
+ this.hideAlert(e.data);
1669
+ helpers.removeEventListener(listenerId);
1670
+ }
1671
+ });
1672
+
1673
+ if (settings?.closeAfter < 100) {
1674
+ console.warn(`Message with id='${settings.id}' has too small 'closeAfter' value. It needs to be at least 100ms.`);
1675
+ settings.closeAfter = undefined;
1676
+ }
1677
+ helpers.sendPostMessageToLuigiCore({
1678
+ msg: 'luigi.ux.alert.show',
1679
+ data: { settings }
1680
+ });
1681
+
1682
+ const alertPromises = this.getPromise('alerts') || {};
1683
+ alertPromises[settings.id] = {};
1684
+ alertPromises[settings.id].promise = new Promise((resolve) => {
1685
+ alertPromises[settings.id].resolveFn = resolve;
1686
+ });
1687
+ this.setPromise('alerts', alertPromises);
1688
+ return alertPromises[settings.id].promise;
1689
+ }
1690
+
1691
+ /**
1692
+ * @private
1693
+ * @memberof uxManager
1694
+ * @param {Object} alertObj
1695
+ * @param {string} alertObj.id - alert id
1696
+ * @param {string} alertObj.dismissKey - key of the link
1697
+ */
1698
+ hideAlert({ id, dismissKey }) {
1699
+ const alerts = this.getPromise('alerts');
1700
+ if (id && alerts[id]) {
1701
+ alerts[id].resolveFn(dismissKey ? dismissKey : id);
1702
+ delete alerts[id];
1703
+ this.setPromise('alerts', alerts);
1704
+ }
1705
+ }
1706
+
1707
+ /**
1708
+ * Gets the current locale.
1709
+ * @returns {string} current locale
1710
+ * @memberof uxManager
1711
+ */
1712
+ getCurrentLocale() {
1713
+ return lifecycleManager$1.currentContext?.internal?.currentLocale;
1714
+ }
1715
+
1716
+ /**
1717
+ * <!-- label-success: Web App API only -->
1718
+ * Sets current locale to the specified one.
1719
+ *
1720
+ * **NOTE:** this must be explicitly allowed on the navigation node level by setting `clientPermissions.changeCurrentLocale` to `true`. (See {@link navigation-parameters-reference.md Node parameters}.)
1721
+ *
1722
+ * @param {string} locale - locale to be set as the current locale
1723
+ * @memberof uxManager
1724
+ */
1725
+ setCurrentLocale(locale) {
1726
+ if (locale) {
1727
+ helpers.sendPostMessageToLuigiCore({
1728
+ msg: 'luigi.ux.set-current-locale',
1729
+ data: {
1730
+ currentLocale: locale
1731
+ }
1732
+ });
1733
+ }
1734
+ }
1735
+
1736
+ /**
1737
+ * <!-- label-success: Web App API only -->
1738
+ * Checks if the current micro frontend is displayed inside a split view
1739
+ * @returns {boolean} indicating if it is loaded inside a split view
1740
+ * @memberof uxManager
1741
+ * @since 0.6.0
1742
+ */
1743
+ isSplitView() {
1744
+ return lifecycleManager$1.currentContext?.internal?.splitView;
1745
+ }
1746
+
1747
+ /**
1748
+ * <!-- label-success: Web App API only -->
1749
+ * Checks if the current micro frontend is displayed inside a modal
1750
+ * @returns {boolean} indicating if it is loaded inside a modal
1751
+ * @memberof uxManager
1752
+ * @since 0.6.0
1753
+ */
1754
+ isModal() {
1755
+ return lifecycleManager$1.currentContext?.internal?.modal;
1756
+ }
1757
+
1758
+ /**
1759
+ * <!-- label-success: Web App API only -->
1760
+ * Checks if the current micro frontend is displayed inside a drawer
1761
+ * @returns {boolean} indicating if it is loaded inside a drawer
1762
+ * @memberof uxManager
1763
+ * @since 1.26.0
1764
+ */
1765
+ isDrawer() {
1766
+ return lifecycleManager$1.currentContext?.internal?.drawer;
1767
+ }
1768
+
1769
+ /**
1770
+ * Gets the current theme.
1771
+ * @returns {*} current themeObj
1772
+ * @memberof uxManager
1773
+ */
1774
+ getCurrentTheme() {
1775
+ return lifecycleManager$1.currentContext?.internal?.currentTheme;
1776
+ }
1777
+
1778
+ /**
1779
+ * <!-- label-success: Web App API only -->
1780
+ * Gets the CSS variables from Luigi Core with their key and value.
1781
+ * @returns {Object} CSS variables with their key and value.
1782
+ * @memberof uxManager
1783
+ * @since 2.3.0
1784
+ * @example LuigiClient.uxManager().getCSSVariables();
1785
+ */
1786
+ getCSSVariables() {
1787
+ return lifecycleManager$1.currentContext?.internal?.cssVariables || {};
1788
+ }
1789
+
1790
+ /**
1791
+ * <!-- label-success: Web App API only -->
1792
+ * Adds the CSS variables from Luigi Core in a <style> tag to the document <head> section.
1793
+ * @memberof uxManager
1794
+ * @since 2.3.0
1795
+ * @example LuigiClient.uxManager().applyCSS();
1796
+ */
1797
+ applyCSS() {
1798
+ document.querySelectorAll('head style[luigi-injected]').forEach((luigiInjectedStyleTag) => {
1799
+ luigiInjectedStyleTag.remove();
1800
+ });
1801
+ const vars = lifecycleManager$1.currentContext?.internal?.cssVariables;
1802
+ if (vars) {
1803
+ let cssString = ':root {\n';
1804
+ Object.keys(vars).forEach((key) => {
1805
+ const val = vars[key];
1806
+ cssString += (key.startsWith('--') ? '' : '--') + key + ':' + val + ';\n';
1807
+ });
1808
+ cssString += '}';
1809
+ const themeStyle = document.createElement('style');
1810
+ themeStyle.setAttribute('luigi-injected', true);
1811
+ themeStyle.innerHTML = cssString;
1812
+ document.head.appendChild(themeStyle);
1813
+ }
1814
+ }
1815
+ }
1816
+ const uxManager$1 = new UxManager();
1817
+
1818
+ const pendingOperation = new Map();
1819
+
1820
+ /**
1821
+ * <!-- label-success: Web App API only -->
1822
+ * StorageManager allows you to use browser local storage of key/values. Every storage operation is sent to be managed by Luigi Core.
1823
+ * The idea is that different micro frontends can share or persist items using local storage, as long as they come from the same domain and follow the [same-origin policy](https://developer.mozilla.org/en-US/docs/Web/Security/Same-origin_policy).
1824
+ * Since all storage operations are asynchronous (sending an event to Luigi Core that will reply once operation is finished), all the methods return Promises.
1825
+ * @augments LuigiClientBase
1826
+ * @name storageManager
1827
+ * @class
1828
+ */
1829
+ class StorageManager extends LuigiClientBase {
1830
+ /** @private */
1831
+ constructor() {
1832
+ super();
1833
+ this.storageEventProcessor = new StorageEventProcessor();
1834
+ helpers.addEventListener('storage', (evt, listenerId) => this.storageEventProcessor.processEvent(evt, listenerId));
1835
+ }
1836
+
1837
+ /**
1838
+ * Stores an item for a specific key.
1839
+ * @memberof storageManager
1840
+ * @param {string} key - key used to identify the value
1841
+ * @param {Object} value - item to store; object must be stringifyable
1842
+ * @returns {Promise<void>} resolves an empty value when the storage operation is over. It will launch an error if storage is not supported, the value cannot be stringified, or if you are using a Luigi reserved key.
1843
+ * @example
1844
+ * LuigiClient.storageManager().setItem('keyExample','valueExample').then(() => console.log('Value stored'))
1845
+ * @since 1.6.0
1846
+ */
1847
+ setItem(key, value) {
1848
+ return new Promise((resolve, reject) => {
1849
+ this.storageEventProcessor.execute(resolve, reject, 'setItem', {
1850
+ key,
1851
+ value
1852
+ });
1853
+ });
1854
+ }
1855
+
1856
+ /**
1857
+ * Retrieves an item for a specific key.
1858
+ * @memberof storageManager
1859
+ * @param {string} key - used to identify the value
1860
+ * @returns {Promise<Object>} resolves an item retrieved from storage. It will launch an error if storage is not supported.
1861
+ * @example
1862
+ * LuigiClient.storageManager().getItem('keyExample').then((value) => console.log);
1863
+ * @since 1.6.0
1864
+ */
1865
+ getItem(key) {
1866
+ return new Promise((resolve, reject) => {
1867
+ this.storageEventProcessor.execute(resolve, reject, 'getItem', { key });
1868
+ });
1869
+ }
1870
+
1871
+ /**
1872
+ * Removes an item for a specific key.
1873
+ * @memberof storageManager
1874
+ * @param {string} key - used to identify the value
1875
+ * @returns {Promise<Object>} resolves an item just removed from storage. It will launch an error if storage is not supported or if you are using a Luigi reserved key.
1876
+ * @example
1877
+ * LuigiClient.storageManager().removeItem('keyExample').then((value) => console.log(value + ' just removed')
1878
+ * @since 1.6.0
1879
+ */
1880
+ removeItem(key) {
1881
+ return new Promise((resolve, reject) => {
1882
+ this.storageEventProcessor.execute(resolve, reject, 'removeItem', {
1883
+ key
1884
+ });
1885
+ });
1886
+ }
1887
+
1888
+ /**
1889
+ * Clears all the storage key/values.
1890
+ * @memberof storageManager
1891
+ * @returns {Promise<void>} resolves when storage clear is over.
1892
+ * @example
1893
+ * LuigiClient.storageManager().clear().then(() => console.log('storage cleared'))
1894
+ * @since 1.6.0
1895
+ */
1896
+ clear() {
1897
+ return new Promise((resolve, reject) => {
1898
+ this.storageEventProcessor.execute(resolve, reject, 'clear', {});
1899
+ });
1900
+ }
1901
+
1902
+ /**
1903
+ * Checks if a key is present in storage.
1904
+ * @memberof storageManager
1905
+ * @param {string} key - key in the storage
1906
+ * @returns {Promise<boolean>} `true` if key is present, `false` if it is not
1907
+ * @example
1908
+ * LuigiClient.storageManager().has(key).then((present) => console.log('item is present '+present))
1909
+ * @since 1.6.0
1910
+ */
1911
+ has(key) {
1912
+ return new Promise((resolve, reject) => {
1913
+ this.storageEventProcessor.execute(resolve, reject, 'has', { key });
1914
+ });
1915
+ }
1916
+
1917
+ /**
1918
+ * Gets all the keys used in the storage.
1919
+ * @memberof storageManager
1920
+ * @returns {Promise<string[]>} keys currently present in the storage
1921
+ * @example
1922
+ * LuigiClient.storageManager().getAllKeys().then((keys) => console.log('keys are '+keys))
1923
+ * @since 1.6.0
1924
+ */
1925
+ getAllKeys() {
1926
+ return new Promise((resolve, reject) => {
1927
+ this.storageEventProcessor.execute(resolve, reject, 'getAllKeys', {});
1928
+ });
1929
+ }
1930
+ }
1931
+
1932
+ class StorageEventProcessor {
1933
+ processEvent(evt, listenerId) {
1934
+ try {
1935
+ const data = evt.data.data;
1936
+ if (!pendingOperation.has(data.id)) {
1937
+ console.log('Impossible to find Promise method for message ' + data.id);
1938
+ return;
1939
+ }
1940
+ const promiseOperations = pendingOperation.get(data.id);
1941
+ if (data.status === 'ERROR') {
1942
+ promiseOperations.reject(data.result);
1943
+ } else {
1944
+ promiseOperations.resolve(data.result);
1945
+ }
1946
+ pendingOperation.delete(data.id);
1947
+ } catch (e) {
1948
+ console.error(e);
1949
+ }
1950
+ }
1951
+
1952
+ waitForSyncResult(id) {
1953
+ let start = new Date().getTime();
1954
+ while (!syncOperation.has(id)) {
1955
+ let exec = new Date().getTime() - start;
1956
+ if (exec > 10000) {
1957
+ throw 'Storage operation is taking more than 1 second...Some problem with Luigi Core communication';
1958
+ }
1959
+ }
1960
+ const result = syncOperation.get(id);
1961
+ pendingOperation.delete(id);
1962
+ return result;
1963
+ }
1964
+
1965
+ execute(resolve, reject, operation, params) {
1966
+ let id = helpers.getRandomId();
1967
+ this.createPendingOperation(id, resolve, reject);
1968
+ this.sendMessage(id, operation, params);
1969
+ }
1970
+
1971
+ createPendingOperation(id, resolve, reject) {
1972
+ pendingOperation.set(id, {
1973
+ resolve,
1974
+ reject
1975
+ });
1976
+ }
1977
+ sendMessage(id, operation, params) {
1978
+ helpers.sendPostMessageToLuigiCore({
1979
+ msg: 'storage',
1980
+ data: {
1981
+ id,
1982
+ operation,
1983
+ params
1984
+ }
1985
+ });
1986
+ }
1987
+ }
1988
+
1989
+ const storageManager$1 = new StorageManager();
1990
+
1991
+ /**
1992
+ * @name LuigiClient
1993
+ * @private
1994
+ */
1995
+ class LuigiClient {
1996
+ constructor() {
1997
+ if (window !== window.top) {
1998
+ if (window.document.head.getAttribute('disable-luigi-history-handling') !== 'true') {
1999
+ history.pushState = history.replaceState.bind(history);
2000
+ }
2001
+ if (window.document.head.getAttribute('disable-luigi-runtime-error-handling') !== 'true') {
2002
+ window.addEventListener('error', ({ filename, message, lineno, colno, error }) => {
2003
+ const msg = {
2004
+ msg: 'luigi-runtime-error-handling',
2005
+ errorObj: { filename, message, lineno, colno, error }
2006
+ };
2007
+ helpers.sendPostMessageToLuigiCore(msg);
2008
+ });
2009
+ }
2010
+ }
2011
+ }
2012
+
2013
+ addInitListener(initFn, disableTpcCheck) {
2014
+ return lifecycleManager$1.addInitListener(initFn, disableTpcCheck);
2015
+ }
2016
+ removeInitListener(id) {
2017
+ return lifecycleManager$1.removeInitListener(id);
2018
+ }
2019
+ addContextUpdateListener(contextUpdatedFn) {
2020
+ return lifecycleManager$1.addContextUpdateListener(contextUpdatedFn);
2021
+ }
2022
+ removeContextUpdateListener(id) {
2023
+ return lifecycleManager$1.removeContextUpdateListener(id);
2024
+ }
2025
+ getToken() {
2026
+ return lifecycleManager$1.getToken();
2027
+ }
2028
+ getEventData() {
2029
+ return lifecycleManager$1.getEventData();
2030
+ }
2031
+ getContext() {
2032
+ return lifecycleManager$1.getContext();
2033
+ }
2034
+ addNodeParams(params, keepBrowserHistory) {
2035
+ return lifecycleManager$1.addNodeParams(params, keepBrowserHistory);
2036
+ }
2037
+ getNodeParams(shouldDesanitise) {
2038
+ return lifecycleManager$1.getNodeParams(shouldDesanitise);
2039
+ }
2040
+ getActiveFeatureToggles() {
2041
+ return lifecycleManager$1.getActiveFeatureToggles();
2042
+ }
2043
+ getPathParams() {
2044
+ return lifecycleManager$1.getPathParams();
2045
+ }
2046
+ getCoreSearchParams() {
2047
+ return lifecycleManager$1.getCoreSearchParams();
2048
+ }
2049
+ addCoreSearchParams(searchParams, keepBrowserHistory) {
2050
+ return lifecycleManager$1.addCoreSearchParams(searchParams, keepBrowserHistory);
2051
+ }
2052
+ getClientPermissions() {
2053
+ return lifecycleManager$1.getClientPermissions();
2054
+ }
2055
+ sendCustomMessage(message) {
2056
+ return lifecycleManager$1.sendCustomMessage(message);
2057
+ }
2058
+ addCustomMessageListener(messageId, listener) {
2059
+ return lifecycleManager$1.addCustomMessageListener(messageId, listener);
2060
+ }
2061
+ removeCustomMessageListener(listenerId) {
2062
+ return lifecycleManager$1.removeCustomMessageListener(listenerId);
2063
+ }
2064
+ addInactiveListener(messageId, listener) {
2065
+ return lifecycleManager$1.addInactiveListener(messageId, listener);
2066
+ }
2067
+ removeInactiveListener(listenerId) {
2068
+ return lifecycleManager$1.removeInactiveListener(listenerId);
2069
+ }
2070
+ setTargetOrigin(origin) {
2071
+ return lifecycleManager$1.setTargetOrigin(origin);
2072
+ }
2073
+ getUserSettings() {
2074
+ return lifecycleManager$1.getUserSettings();
2075
+ }
2076
+ isLuigiClientInitialized() {
2077
+ return lifecycleManager$1.isLuigiClientInitialized();
2078
+ }
2079
+ luigiClientInit() {
2080
+ return lifecycleManager$1.luigiClientInit();
2081
+ }
2082
+ getAnchor() {
2083
+ return lifecycleManager$1.getAnchor();
2084
+ }
2085
+ setAnchor(value) {
2086
+ return lifecycleManager$1.setAnchor(value);
2087
+ }
2088
+ setViewGroupData(value) {
2089
+ return lifecycleManager$1.setViewGroupData(value);
2090
+ }
2091
+
2092
+ /**
2093
+ * @private
2094
+ */
2095
+ linkManager() {
2096
+ return new linkManager$1({
2097
+ currentContext: lifecycleManager$1.currentContext
2098
+ });
2099
+ }
2100
+ /**
2101
+ * @private
2102
+ */
2103
+ uxManager() {
2104
+ return uxManager$1;
2105
+ }
2106
+ /**
2107
+ * @private
2108
+ */
2109
+ lifecycleManager() {
2110
+ return lifecycleManager$1;
2111
+ }
2112
+ /**
2113
+ * @private
2114
+ */
2115
+ storageManager() {
2116
+ return storageManager$1;
2117
+ }
2118
+ }
2119
+ var LuigiClient$1 = LuigiClient = new LuigiClient();
2120
+
2121
+ const uxManager = LuigiClient$1.uxManager;
2122
+ const linkManager = LuigiClient$1.linkManager;
2123
+ const lifecycleManager = LuigiClient$1.lifecycleManager;
2124
+ const storageManager = LuigiClient$1.storageManager;
2125
+
2126
+ export { LuigiClient$1 as default, lifecycleManager, linkManager, storageManager, uxManager };